package data_manage

import (
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_source"
	"eta/eta_api/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// @Title 隆众数据分类
// @Description 隆众数据分类接口
// @Success 200 {object} data_manage.LzClassify
// @router /lz/classify [get]
func (this *EdbInfoController) LzClassify() {
	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.GetLzSurveyClassify()
	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   BreedId   query   int  true       "分类id"
// @Success 200 {object} data_manage.LzFrequency
// @router /lz/frequency [get]
func (this *EdbInfoController) LzFrequency() {
	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
	}
	breedId, _ := this.GetInt("BreedId")
	if breedId <= 0 {
		br.Msg = "分类id错误"
		br.ErrMsg = "分类id错误:breedId" + strconv.Itoa(breedId)
		return
	}
	frequencyList, err := data_manage.GetLzFrequencyByClassifyId(breedId)
	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   BreedId   query   int  true       "分类id"
// @Param   Frequency   query   int  true       "频度"
// @Success 200 {object} data_manage.LzFrequency
// @router /lz/data [get]
func (this *EdbInfoController) LzData() {
	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
	}
	breedId, _ := this.GetInt("BreedId")
	if breedId <= 0 {
		br.Msg = "分类id错误"
		br.ErrMsg = "分类id错误:breedId" + strconv.Itoa(breedId)
		return
	}
	frequency, _ := this.GetInt("Frequency")
	if frequency <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "频度错误:frequency" + strconv.Itoa(frequency)
		return
	}
	//获取指标
	fmt.Println("breedId:", breedId)
	fmt.Println("frequency:", frequency)
	productList, err := data_manage.GetLongzhongSurveyProduct(breedId, frequency)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	resultList := make([]*data_manage.LzProductList, 0)
	for _, v := range productList {
		fmt.Println(v.SurveyProductId)
		product := new(data_manage.LzProductList)
		product.SurveyProductId = v.SurveyProductId
		product.BreedName = v.BreedName
		product.QuotaName = v.SampleName + v.BreedName + v.Custom + v.QuotaName
		product.UnitName = v.UnitName
		product.SampleType = v.SampleType
		product.SampleName = v.SampleName
		product.Device = v.Device
		product.Frequency = v.Frequency
		product.Custom = v.Custom
		product.StartDate = v.StartDate
		product.EndDate = v.EndDate
		product.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
		product.LzCode = v.LzCode

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

// LzSearchList
// @Title 隆众模糊搜索
// @Description 隆众模糊搜索
// @Param   Keyword   query   string  ture       "关键字搜索"
// @Success 200 {object} models.BaseResponse
// @router /lz/search_list [get]
func (this *EdbInfoController) LzSearchList() {
	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_source.GetLzItemList(keyword)
	if err != nil {
		br.ErrMsg = "获取失败，Err:" + err.Error()
		br.Msg = "获取失败"
		return
	}
	resultList := make([]*data_manage.LzProductList, 0)
	for _, v := range list {
		product := new(data_manage.LzProductList)
		product.SurveyProductId = v.SurveyProductId
		product.BreedName = v.BreedName
		product.QuotaName = v.SampleName + v.BreedName + v.Custom + v.QuotaName
		product.UnitName = v.UnitName
		product.SampleType = v.SampleType
		product.SampleName = v.SampleName
		product.Device = v.Device
		product.Frequency = v.Frequency
		product.Custom = v.Custom
		product.StartDate = v.StartDate
		product.EndDate = v.EndDate
		product.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
		product.LzCode = v.LzCode

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

// ExportLzList
// @Title 导出隆众数据
// @Description 导出数据列表
// @Param   QuotaName   query   string  false       "名称关键词"
// @Param   LzCode   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/lzList [get]
func (this *EdbInfoController) ExportLzList() {
	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 := models.GetLzFrequency(breedName)
	if err != nil {
		fmt.Println("GetLzFrequency err:", err.Error())
		utils.FileLog.Info("GetLzFrequency err:" + err.Error())
		return
	}
	if breedName != "" {
		for _, frequency := range frequencies {
			//获取指标
			secNameList, err := models.GetLzSurveyProductByNameAndFrequency(breedName, *frequency)
			if err != nil {
				fmt.Println("获取数据失败，Err:" + err.Error())
				return
			}
			if len(secNameList) <= 0 {
				fmt.Println("secNameList长度为0")
				return
			}
			var frequencyName string
			if *frequency == 1 {
				frequencyName = "日度"
			} else if *frequency == 2 {
				frequencyName = "周度"
			} else if *frequency == 3 {
				frequencyName = "月度"
			} else if *frequency == 4 {
				frequencyName = "季度"
			} else if *frequency == 5 {
				frequencyName = "年度"
			} else if *frequency == 99 {
				frequencyName = "无固定频率"
			}
			singalDataMax, err := data_source.GetLongzhongSurveyDataMaxCountByFrequency(breedName, *frequency)
			if err != nil {
				fmt.Println("获取指标最大数据量失败", err.Error())
				return
			}
			if singalDataMax <= 0 {
				continue
			}
			sheetNew, err := xlsxFile.AddSheet(frequencyName)

			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_source.GetLongzhongSurveyDataMaxCount(breedName)
			if err != nil {
				fmt.Println("获取指标最大数据量失败", err.Error())
				return
			}
			setRowIndex := 6
			for k, sv := range secNameList {
				//获取数据
				dataList, err := data_source.GetLongzhongSurveyDataById(sv.SurveyProductId)
				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.SampleName + sv.BreedName + sv.Custom + sv.QuotaName)
					indexCodeRow.AddCell().SetValue(sv.LzCode)
					if sv.Frequency == 1 {
						frequencyRow.AddCell().SetValue("日度")
					} else if sv.Frequency == 2 {
						frequencyRow.AddCell().SetValue("周度")
					} else if sv.Frequency == 3 {
						frequencyRow.AddCell().SetValue("月度")
					} else if sv.Frequency == 4 {
						frequencyRow.AddCell().SetValue("季度")
					} else if sv.Frequency == 5 {
						frequencyRow.AddCell().SetValue("年度")
					} else if sv.Frequency == 99 {
						frequencyRow.AddCell().SetValue("无固定频率")
					}

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

					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().SetFloat(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")
		lzCode := this.GetString("LzCode") //指标唯一编码
		unit := this.GetString("UnitName")
		modifyTime := this.GetString("ModifyTime")
		frequency, _ := this.GetInt("Frequency")

		sheet, err := xlsxFile.AddSheet("指标")
		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(lzCode)

		rowFrequency := sheet.AddRow()
		celFrequency := rowFrequency.AddCell()
		celFrequency.SetValue("频率")
		if frequency == 1 {
			rowFrequency.AddCell().SetValue("日度")
		} else if frequency == 2 {
			rowFrequency.AddCell().SetValue("周度")
		} else if frequency == 3 {
			rowFrequency.AddCell().SetValue("月度")
		} else if frequency == 4 {
			rowFrequency.AddCell().SetValue("季度")
		} else if frequency == 5 {
			rowFrequency.AddCell().SetValue("年度")
		} else if frequency == 99 {
			rowFrequency.AddCell().SetValue("无固定频率")
		}

		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)

		surveyProductId, err := data_source.GetLzProductIdByCode(lzCode)
		//获取数据
		dataList, err := data_source.GetLongzhongSurveyDataById(surveyProductId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取数据失败,Err:" + err.Error()
			return
		}
		fmt.Println("len(dataList):", len(dataList))
		dataMax, err := data_source.GetLzSurveyDataMaxCountByProductId(surveyProductId)
		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().SetFloat(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"

}

// ExportLzQuotasData
// @Title 导出隆众多个指标数据
// @Description 导出隆众多个指标数据
// @Param   BreedIds	query	string	false	"品种ID集合"
// @Success 200  导出成功
// @router /export/lzQuotasData [get]
func (this *EdbInfoController) ExportLzQuotasData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	breedIdsStr := this.GetString("BreedIds")
	breedIds := strings.Split(breedIdsStr, ",")
	if len(breedIds) <= 0 {
		br.Msg = "请选择品种"
		br.ErrMsg = "请选择品种"
		return
	}

	// 获取多个品种的指标信息
	quotaList, err := models.GetExportLzSurveyProductByBreedIds(breedIds)
	if err != nil {
		br.Msg = "导出失败"
		br.ErrMsg = "获取指标信息失败, Err: " + err.Error()
		return
	}

	// 获取多个品种的指标最大数据量
	quotaMaxCountList, err := data_source.GetExportLzSurveyDataMaxCount(breedIds)
	if err != nil {
		br.Msg = "导出失败"
		br.ErrMsg = "获取指标最大数据量失败, Err: " + err.Error()
		return
	}
	quotaMaxCountMatch := make(map[string]int)
	for i := 0; i < len(quotaMaxCountList); i++ {
		quotaMaxCountMatch[strconv.Itoa(quotaMaxCountList[i].BreedId)] = quotaMaxCountList[i].Count
	}

	// 获取多个品种对应的指标数据
	productIdDataMatch := make(map[int][]*data_source.LongzhongSurveyData)
	for i := 0; i < len(quotaList); i++ {
		var iniArr []*data_source.LongzhongSurveyData
		productIdDataMatch[quotaList[i].SurveyProductId] = iniArr
	}
	quotaDataList, err := data_source.GetExportLzSurveyDataByBreedIds(breedIds)
	for k, _ := range productIdDataMatch {
		var tmpArr []*data_source.LongzhongSurveyData
		for _, qd := range quotaDataList {
			if k == qd.SurveyProductId {
				tmpArr = append(tmpArr, qd)
			}
		}
		productIdDataMatch[k] = tmpArr
	}

	dir, _ := os.Executable()
	exPath := filepath.Dir(dir)
	downloadFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	excelFile := xlsx.NewFile()

	frequencyMatch := map[int64]string{
		1:  "日度",
		2:  "周度",
		3:  "月度",
		4:  "季度",
		5:  "年度",
		99: "无固定频率",
	}
	for i := 0; i < len(breedIds); i++ {
		breedId := breedIds[i]
		breedName := ""

		var breedQuotas []*models.LongzhongSurveyProduct
		for _, quota := range quotaList {
			if quota.BreedId == breedId {
				breedName = quota.BreedName
				breedQuotas = append(breedQuotas, quota)
			}
		}
		if len(breedQuotas) <= 0 {
			continue
		}

		sheetNew, err := excelFile.AddSheet(breedName)
		if err != nil {
			br.Msg = "导出失败"
			br.ErrMsg = "新增sheet失败, Err: " + err.Error()
			return
		}

		windRow := sheetNew.AddRow()
		secNameRow := sheetNew.AddRow()
		indexCodeRow := sheetNew.AddRow()
		frequencyRow := sheetNew.AddRow()
		unitRow := sheetNew.AddRow()
		lastModifyDateRow := sheetNew.AddRow()

		dataMax := quotaMaxCountMatch[breedId] // 最大数据量
		setRowIndex := 6
		for k, sv := range breedQuotas {
			// 指标信息
			windRow.AddCell().SetValue("隆众")
			secNameRow.AddCell().SetValue("指标名称")
			indexCodeRow.AddCell().SetValue("指标ID")
			frequencyRow.AddCell().SetValue("频率")
			unitRow.AddCell().SetValue("单位")
			lastModifyDateRow.AddCell().SetValue("更新时间")

			secNameRow.AddCell().SetValue(sv.SampleName + sv.BreedName + sv.Custom + sv.QuotaName)
			indexCodeRow.AddCell().SetValue(sv.LzCode)
			frequencyRow.AddCell().SetValue(frequencyMatch[sv.Frequency])
			unitRow.AddCell().SetValue(sv.UnitName)
			lastModifyDateRow.AddCell().SetValue(sv.EndDate)

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

			// 指标数据
			quotaData := productIdDataMatch[sv.SurveyProductId]
			if len(quotaData) <= 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 quotaData {
					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().SetFloat(dv.InputValue)
					row.AddCell()
					endRowIndex = rowIndex
				}
				if len(quotaData) < dataMax {
					dataLen := dataMax - len(quotaData)
					for n := 0; n < dataLen; n++ {
						rowIndex := (endRowIndex + 1) + n
						row := sheetNew.Row(rowIndex)
						row.AddCell()
						row.AddCell()
						row.AddCell()
					}
				}
			}
		}
	}

	err = excelFile.Save(downloadFilePath)
	if err != nil {
		br.Msg = "导出失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	fileName := `隆众数据`
	fileName += time.Now().Format("06.01.02") + `.xlsx` //文件名称
	this.Ctx.Output.Download(downloadFilePath, fileName)
	defer func() {
		os.Remove(downloadFilePath)
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "success"
}
