package data_manage

import (
	"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"
)

// EiaSteoClassify
// @Title EiaSteo数据分类
// @Description EiaSteo数据分类接口
// @Success 200 {object} data_manage.LzClassify
// @router /eia_steo/classify [get]
func (this *EdbInfoController) EiaSteoClassify() {
	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.GetEiaSteoClassifyList()
	if err != nil {
		br.Msg = "获取分类失败"
		br.ErrMsg = "获取分类失败,Err:" + err.Error()
		return
	}
	for _, v := range classifyList {
		if v.ClassifyName == `` {
			v.ClassifyName = v.ClassifyNameOriginal
		}
	}

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

// EiaSteoData
// @Title 获取EiaSteo数据
// @Description 获取EiaSteo数据接口
// @Param   BaseFromEiaSteoClassifyId   query   int  true       "指标分类id"
// @Param   IndexCode   query   string  true       "指标code"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} data_manage.LzFrequency
// @router /eia_steo/data [get]
func (this *EdbInfoController) EiaSteoData() {
	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
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

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

	var condition string
	var pars []interface{}

	indexCode := this.GetString("IndexCode")
	if indexCode != "" {
		condition += ` AND index_code = ? `
		pars = append(pars, utils.TrimStr(indexCode))
	}
	classifyId, _ := this.GetInt("BaseFromEiaSteoClassifyId")
	if classifyId > 0 {
		condition += ` AND base_from_eia_steo_classify_id = ? `
		pars = append(pars, classifyId)
	}

	//获取指标
	indexList, err := data_manage.GetEiaSteoIndexList(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	resultList := make([]data_manage.EiaSteoIndexListResp, 0)
	for _, v := range indexList {

		indexName := v.IndexName
		if indexName == `` {
			indexName = v.IndexNameOriginal
		}
		product := data_manage.EiaSteoIndexListResp{
			BaseFromEiaSteoIndexId:    v.BaseFromEiaSteoIndexId,
			BaseFromEiaSteoClassifyId: v.BaseFromEiaSteoClassifyId,
			IndexCode:                 v.IndexCode,
			IndexName:                 indexName,
			//IndexNameOriginal:          v.IndexNameOriginal,
			Unit:       v.Unit,
			Frequency:  v.Frequency,
			StartDate:  v.StartDate.Format(utils.FormatDate),
			EndDate:    v.EndDate.Format(utils.FormatDate),
			ModifyTime: v.ModifyTime.Format(utils.FormatDateTime),
			CreateTime: v.CreateTime.Format(utils.FormatDateTime),
			//Paging:     tmpPaging,
			//DataList:   nil,
		}

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

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

	//导出excel
	if isExport {
		EiaSteoDataExport(this, resultList, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resultList
}

// EiaSteoSearchList
// @Title EiaSteo模糊搜索
// @Description EiaSteo模糊搜索
// @Param   Keyword   query   string  ture       "关键字搜索"
// @Success 200 {object} models.BaseResponse
// @router /eia_steo/search_list [get]
func (this *EdbInfoController) EiaSteoSearchList() {
	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.GetEiaSteoItemList(utils.TrimStr(keyword))
	if err != nil {
		br.ErrMsg = "获取失败，Err:" + err.Error()
		br.Msg = "获取失败"
		return
	}

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

// EiaSteoDataExport 表格导出
func EiaSteoDataExport(this *EdbInfoController, list []data_manage.EiaSteoIndexListResp, br *models.BaseResponse) {
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

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

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

	sheet, err := xlsxFile.AddSheet("数据报表")

	//获取指标数据
	rowSecName := sheet.AddRow()
	celSecName := rowSecName.AddCell()
	celSecName.SetValue("指标名称")
	rowUnit := sheet.AddRow()
	celUnit := rowUnit.AddCell()
	celUnit.SetValue("单位")

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

	dataMap := make(map[string]map[string]*data_manage.BaseFromEiaSteoDataItem)
	var indexCodeList []string
	for _, v := range list {
		cellSenName := rowSecName.AddCell()
		cellSenName.SetValue(v.IndexName)
		celUnit := rowUnit.AddCell()
		celUnit.SetValue(v.Unit)
		rowModifyCell := rowModifyDate.AddCell()
		rowModifyCell.SetValue(v.ModifyTime)

		indexCodeList = append(indexCodeList, v.IndexCode)

		dataMap[v.IndexCode] = make(map[string]*data_manage.BaseFromEiaSteoDataItem)
		for _, item := range v.DataList {
			dataMap[item.IndexCode][item.DataTime] = item
		}
	}

	dateList, err := data_manage.GetEiaSteoDateList(indexCodeList)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	for _, n := range dateList {
		dateStr := n.DataTime //当前日期
		rowData := sheet.AddRow()
		celDate := rowData.AddCell()
		celDate.SetValue(dateStr)

		for _, m := range list {
			celData := rowData.AddCell()
			if dataMap[m.IndexCode][dateStr] != nil {
				celData.SetValue(dataMap[m.IndexCode][dateStr].Value)
			}
		}
	}

	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 := `EiaSteo数据`
	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"
}
