package data_manage

import (
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/utils"
	"os"
	"path/filepath"
	"time"
)

// @Title 钢联数据分类
// @Description 隆众数据分类接口
// @Success 200 {object} data_manage.LzClassify
// @router /gl/classify [get]
func (this *EdbInfoController) GlClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	classifyList, err := data_manage.GetGlSurveyClassify()
	if err != nil {
		br.Msg = "获取分类失败"
		br.ErrMsg = "获取分类失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = classifyList
}

// @Title 钢联数据频度
// @Description 钢联数据频度接口
// @Param   BreedShortName   query   string  true       "分类名称"
// @Success 200 {object} data_manage.LzFrequency
// @router /gl/frequency [get]
func (this *EdbInfoController) GlFrequency() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	breedShortName := this.GetString("BreedShortName")
	if breedShortName == "" {
		br.Msg = "分类不可为空"
		br.ErrMsg = "分类不可为空"
		return
	}
	fmt.Println("breedShortName:", breedShortName)
	frequencyList, err := data_manage.GetGlFrequencyByClassifyId(breedShortName)
	if err != nil {
		br.Msg = "获取频度失败"
		br.ErrMsg = "获取频度失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = frequencyList
}

// @Title 获取钢联数据
// @Description 获取钢联数据接口
// @Param   BreedShortName   query   string  true       "分类名称"
// @Param   Frequency   query   string  true       "频度名称"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} data_manage.LzFrequency
// @router /gl/data [get]
func (this *EdbInfoController) GlData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	breedShortName := this.GetString("BreedShortName")
	if breedShortName == "" {
		br.Msg = "请选择分类"
		br.ErrMsg = "请选择分类"
		return
	}
	frequency := this.GetString("Frequency")
	if frequency == "" {
		br.Msg = "请选择频度"
		br.ErrMsg = "请选择频度"
		return
	}
	//获取指标

	glList, err := data_manage.GetGlIndex(breedShortName, frequency)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	resultList := make([]*data_manage.GlIndexList, 0)
	for _, v := range glList {
		product := new(data_manage.GlIndexList)
		product.UnitName = v.UnitName
		product.Id = v.Id
		product.IndexCode = v.IndexCode
		product.IndexName = v.IndexName
		product.UnitName = v.UnitName
		product.FrequencyName = v.FrequencyName
		product.UpdateTime = v.UpdateTime

		total, err := data_manage.GetGlIndexDataCount(v.IndexCode)
		page := paging.GetPaging(currentIndex, pageSize, total)

		dataList, err := data_manage.GetGlIndexData(v.IndexCode, startSize, pageSize)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取指标数据失败,Err:" + err.Error()
			return
		}
		if dataList == nil {
			dataList = make([]*data_manage.GlIndexData, 0)
		}
		product.DataList = dataList
		product.Paging = page
		resultList = append(resultList, product)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resultList
}

// GlSearchList
// @Title 钢联模糊搜索
// @Description 钢联模糊搜索
// @Param   Keyword   query   string  ture       "关键字搜索"
// @Success 200 {object} models.BaseResponse
// @router /gl/search_list [get]
func (this *EdbInfoController) GlSearchList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	//关键字
	keyword := this.GetString("Keyword")

	list, err := data_manage.GetGlItemList(keyword)
	if err != nil {
		br.ErrMsg = "获取失败，Err:" + err.Error()
		br.Msg = "获取失败"
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// GlSingleData
// @Title 获取钢联数据
// @Description 获取钢联单条数据接口
// @Param   IndexCode   query   string  true       "指标唯一编码"
// @Success 200 {object} models.BaseResponse
// @router /gl/single_data [get]
func (this *EdbInfoController) GlSingleData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	indexCode := this.GetString("IndexCode")
	dataList, err := data_manage.GetGlDataByCode(indexCode)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = dataList
}

// ExportGlList
// @Title 导出钢联数据
// @Description 导出钢联数据
// @Param   QuotaName   query   string  false       "名称关键词"
// @Param   IndexCode   query   string  false       "指标唯一编码"
// @Param   BreedName   query   string  true       "分类"
// @Param   Frequency   query   string  true       "频度"
// @Param   UnitName   query   string  false       "单位"
// @Param   ModifyTime   query   string  false       "更新时间"
// @Success 200  导出成功
// @router /export/glList [get]
func (this *EdbInfoController) ExportGlList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	breedName := this.GetString("BreedName") //分类
	//frequency := this.GetString("Frequency")

	secNameList := make([]*models.EdbdataExportList, 0)

	dir, _ := os.Executable()
	exPath := filepath.Dir(dir)

	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()

	frequencies, err := data_manage.GetGlFrequency(breedName)
	if err != nil {
		fmt.Println("GetGlFrequency err:", err.Error())
		utils.FileLog.Info("GetGlFrequency err:" + err.Error())
		return
	}

	if breedName != "" {
		for _, frequency := range frequencies {
			//获取指标
			secNameList, err := data_manage.GetGlIndex(breedName, *frequency)
			if err != nil {
				fmt.Println("获取数据失败，Err:" + err.Error())
				return
			}
			if len(secNameList) <= 0 {
				fmt.Println("secNameList长度为0")
				return
			}
			if breedName == "1/3焦煤" {
				breedName = "三分之一焦煤"
			}
			sheetNew, err := xlsxFile.AddSheet(*frequency)

			if err != nil {
				fmt.Println("新增Sheet失败", err.Error())
				return
			}
			//sheetNew.SetColWidth()
			//获取指标数据
			windRow := sheetNew.AddRow()
			secNameRow := sheetNew.AddRow()
			indexCodeRow := sheetNew.AddRow()
			frequencyRow := sheetNew.AddRow()
			unitRow := sheetNew.AddRow()
			lastModifyDateRow := sheetNew.AddRow()
			//获取分类下指标最大数据量
			dataMax, err := data_manage.GetGlDataMaxCount(breedName)
			if err != nil {
				fmt.Println("获取指标最大数据量失败", err.Error())
				return
			}
			fmt.Println("dataMax:", dataMax)
			setRowIndex := 6
			for k, sv := range secNameList {
				//获取数据
				dataList, err := data_manage.GetGlDataByCode(sv.IndexCode)
				if err != nil {
					br.Msg = "获取数据失败"
					br.ErrMsg = "获取数据失败,Err:" + err.Error()
					return
				}
				if len(dataList) > 0 {
					windRow.AddCell().SetValue("钢联")
					secNameRow.AddCell().SetValue("指标名称")
					indexCodeRow.AddCell().SetValue("指标ID")
					frequencyRow.AddCell().SetValue("频率")
					unitRow.AddCell().SetValue("单位")
					lastModifyDateRow.AddCell().SetValue("更新时间")

					secNameRow.AddCell().SetValue(sv.IndexName)
					indexCodeRow.AddCell().SetValue(sv.IndexCode)
					frequencyRow.AddCell().SetValue(sv.FrequencyName)

					unitRow.AddCell().SetValue(sv.UnitName)
					lastModifyDateRow.AddCell().SetValue(sv.UpdateTime)

					windRow.AddCell()
					windRow.AddCell()
					secNameRow.AddCell()
					indexCodeRow.AddCell()
					frequencyRow.AddCell()
					unitRow.AddCell()
					lastModifyDateRow.AddCell()
					min := k * 3
					sheetNew.SetColWidth(min, min, 15)

					if len(dataList) <= 0 {
						for n := 0; n < dataMax; n++ {
							rowIndex := setRowIndex + n
							row := sheetNew.Row(rowIndex)
							row.AddCell()
							row.AddCell()
							row.AddCell()
						}
					} else {
						endRowIndex := 0
						for rk, dv := range dataList {
							rowIndex := setRowIndex + rk
							row := sheetNew.Row(rowIndex)
							displayDate, _ := time.Parse(utils.FormatDate, dv.DataTime)
							displayDateCell := row.AddCell()
							style := new(xlsx.Style)
							style.ApplyAlignment = true
							style.Alignment.WrapText = true
							displayDateCell.SetStyle(style)
							displayDateCell.SetDate(displayDate)

							row.AddCell().SetValue(dv.InputValue)
							row.AddCell()
							endRowIndex = rowIndex
						}
						if len(dataList) < dataMax {
							dataLen := dataMax - len(dataList)
							for n := 0; n < dataLen; n++ {
								rowIndex := (endRowIndex + 1) + n
								row := sheetNew.Row(rowIndex)
								row.AddCell()
								row.AddCell()
								row.AddCell()
							}
						}
					}
				}
			}
		}
	} else {
		name := this.GetString("QuotaName")
		indexCode := this.GetString("IndexCode") //指标唯一编码
		unit := this.GetString("UnitName")
		modifyTime := this.GetString("ModifyTime")
		frequency := this.GetString("Frequency")
		sheet, err := xlsxFile.AddSheet(frequency)
		if err != nil {
			br.Msg = "新增Sheet失败"
			br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
			return
		}

		//获取指标数据
		windRow := sheet.AddRow()
		windRow.AddCell().SetValue("钢联")
		rowSecName := sheet.AddRow()
		celSecName := rowSecName.AddCell()
		celSecName.SetValue("指标名称")
		cellSenName := rowSecName.AddCell()
		cellSenName.SetValue(name)
		indexCodeRow := sheet.AddRow()
		indexCodeRow.AddCell().SetValue("指标ID")
		indexCodeRow.AddCell().SetValue(indexCode)

		rowFrequency := sheet.AddRow()
		celFrequency := rowFrequency.AddCell()
		celFrequency.SetValue("频率")
		cellFrequency := rowFrequency.AddCell()
		cellFrequency.SetValue(frequency)

		rowUnit := sheet.AddRow()
		celUnit := rowUnit.AddCell()
		celUnit.SetValue("单位")
		cellUnit := rowUnit.AddCell()
		cellUnit.SetValue(unit)

		rowModifyDate := sheet.AddRow()
		rowModifyCell := rowModifyDate.AddCell()
		rowModifyCell.SetValue("更新时间")
		rowModifyCell = rowModifyDate.AddCell()
		rowModifyCell.SetValue(modifyTime)

		//获取数据
		dataList, err := data_manage.GetGlDataByCode(indexCode)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取数据失败,Err:" + err.Error()
			return
		}
		fmt.Println("len(dataList):", len(dataList))
		dataMax, err := data_manage.GetGlDataMaxCount(breedName)
		fmt.Println("dataMax:", dataMax)
		if len(dataList) <= 0 {
			for n := 0; n < dataMax; n++ {
				rowIndex := 6 + n
				row := sheet.Row(rowIndex)
				row.AddCell()
				row.AddCell()
				row.AddCell()
			}
		} else {
			endRowIndex := 0
			for rk, dv := range dataList {
				rowIndex := 6 + rk
				row := sheet.Row(rowIndex)
				displayDate, _ := time.Parse(utils.FormatDate, dv.DataTime)
				displayDateCell := row.AddCell()
				style := new(xlsx.Style)
				style.ApplyAlignment = true
				style.Alignment.WrapText = true
				displayDateCell.SetStyle(style)
				displayDateCell.SetDate(displayDate)

				row.AddCell().SetValue(dv.InputValue)
				row.AddCell()
				endRowIndex = rowIndex
			}
			if len(dataList) < dataMax {
				dataLen := dataMax - len(dataList)
				for n := 0; n < dataLen; n++ {
					rowIndex := (endRowIndex + 1) + n
					row := sheet.Row(rowIndex)
					row.AddCell()
					row.AddCell()
					row.AddCell()
				}
			}
		}
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		//有指标无数据时先导出一遍空表
		sheet, err := xlsxFile.AddSheet("无数据")
		if err != nil {
			br.Msg = "新增Sheet失败"
			br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
			return
		}
		rowSecName := sheet.AddRow()
		celSecName := rowSecName.AddCell()
		celSecName.SetValue("")
		err = xlsxFile.Save(downLoadnFilePath)
		if err != nil {
			br.Msg = "保存文件失败"
			br.ErrMsg = "保存文件失败"
			return
		}
	}
	fileName := `钢联数据`
	if len(secNameList) > 0 {
		fileName = secNameList[0].ClassifyName
	}
	fileName += time.Now().Format("06.01.02") + `.xlsx` //文件名称
	this.Ctx.Output.Download(downLoadnFilePath, fileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "success"

}
