package data_manage

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/models/data_manage/request"
	"hongze/hz_crm_api/models/data_manage/response"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

// MysteelChemicalClassify
// @Title 钢联化工数据分类
// @Description 钢联化工分类接口
// @Success 200 {object} data_manage.BaseFromMysteelChemicalClassifyItems
// @router /mysteel_chemical/classify [get]
func (this *EdbInfoController) MysteelChemicalClassify() {
	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
	}

	rootList, err := data_manage.GetBaseFromMysteelChemicalClassifyByParentId(0)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	classifyAll, err := data_manage.GetAllBaseFromMysteelChemicalClassify()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	baseFromMysteelChemicalIndexMap := make(map[int][]*data_manage.BaseFromMysteelChemicalClassifyItems)

	allBaseFromMysteelChemicalIndex, err := data_manage.GetMysteelChemicalIndexAll()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取指标信息失败，Err:" + err.Error()
		return
	}
	for _, v := range allBaseFromMysteelChemicalIndex {
		v.UniqueCode = fmt.Sprint(v.BaseFromMysteelChemicalClassifyId, "_", v.BaseFromMysteelChemicalIndexId)
		button := data.GetMysteelChemicalOpButton(sysUser, v.SysUserId)
		button.AddButton = false //不管有没有权限，指标都是没有添加按钮的
		v.Button = button

		baseFromMysteelChemicalIndexMap[v.BaseFromMysteelChemicalClassifyId] = append(baseFromMysteelChemicalIndexMap[v.BaseFromMysteelChemicalClassifyId], v)
	}

	rootChildMap := make(map[int][]*data_manage.BaseFromMysteelChemicalClassifyItems)
	for _, v := range classifyAll {
		v.UniqueCode = fmt.Sprint(v.BaseFromMysteelChemicalClassifyId)

		button := data.GetMysteelChemicalOpButton(sysUser, v.SysUserId)
		button.AddButton = false //不管有没有权限，二级分类都是没有添加按钮的
		v.Button = button

		rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], v)
		if existItems, ok := baseFromMysteelChemicalIndexMap[v.BaseFromMysteelChemicalClassifyId]; ok {
			v.Children = existItems
		} else {
			items := make([]*data_manage.BaseFromMysteelChemicalClassifyItems, 0)
			v.Children = items
		}
	}

	nodeAll := make([]*data_manage.BaseFromMysteelChemicalClassifyItems, 0)
	for k, v := range rootList {
		button := data.GetMysteelChemicalOpButton(sysUser, v.SysUserId)
		rootList[k].Button = button
		rootList[k].UniqueCode = fmt.Sprint(v.BaseFromMysteelChemicalClassifyId)

		if existItems, ok := rootChildMap[v.BaseFromMysteelChemicalClassifyId]; ok {
			v.Children = existItems
		} else {
			items := make([]*data_manage.BaseFromMysteelChemicalClassifyItems, 0)
			v.Children = items
		}
		nodeAll = append(nodeAll, v)
	}

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

// AddMysteelChemicalClassify
// @Title 新增分类
// @Description 新增分类接口
// @Param	request	body data_manage.AddBaseFromMysteelChemicalClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /mysteel_chemical/classify/add [post]
func (this *EdbClassifyController) AddMysteelChemicalClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddBaseFromMysteelChemicalClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}
	req.ClassifyName = utils.TrimStr(req.ClassifyName)
	req.ClassifyName = strings.Replace(req.ClassifyName, "/t", "", -1)

	//添加指标
	mysteelChemicalClassifyInfo, err, errMsg := data.AddMysteelChemicalClassify(req.ClassifyName, req.ParentId, req.Level, this.SysUser.AdminId, this.SysUser.RealName)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	// 如果是添加一级分类，那么默认加上 价格、供应、需求、库存 四个二级分类
	if mysteelChemicalClassifyInfo.ParentId == 0 {
		secondClassifyList := []string{"价格", "供应", "需求", "库存"}
		for _, v := range secondClassifyList {
			_, _, tmpErrMsg := data.AddMysteelChemicalClassify(v, mysteelChemicalClassifyInfo.BaseFromMysteelChemicalClassifyId, mysteelChemicalClassifyInfo.Level, this.SysUser.AdminId, this.SysUser.RealName)
			if tmpErrMsg != `` {
				go alarm_msg.SendAlarmMsg("钢联化工-添加一级分类时，默认添加二级分类失败,一级分类名称："+req.ClassifyName+",二级分类名称："+v+", Err："+tmpErrMsg, 3)
				return
			}
		}
	}
	resp := response.AddMysteelChemicalClassifyResp{
		BaseFromMysteelChemicalClassifyId: mysteelChemicalClassifyInfo.BaseFromMysteelChemicalClassifyId,
		UniqueCode:                        fmt.Sprint(mysteelChemicalClassifyInfo.BaseFromMysteelChemicalClassifyId),
	}
	br.Data = resp
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// EditMysteelChemicalClassify
// @Title 修改分类
// @Description 修改分类接口
// @Param	request	body data_manage.EditBaseFromMysteelChemicalClassifyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /mysteel_chemical/classify/edit [post]
func (this *EdbClassifyController) EditMysteelChemicalClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.EditBaseFromMysteelChemicalClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}

	if req.BaseFromMysteelChemicalClassifyId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.EditMysteelChemicalClassify(req.BaseFromMysteelChemicalClassifyId, req.ClassifyName, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// MoveMysteelChemicalClassify
// @Title 分类移动接口
// @Description 分类移动接口
// @Success 200 {object} data_manage.MoveBaseFromMysteelChemicalClassifyReq
// @router /mysteel_chemical/classify/move [post]
func (this *EdbClassifyController) MoveMysteelChemicalClassify() {
	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
	}

	var req request.MoveBaseFromMysteelChemicalClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.BaseFromMysteelChemicalClassifyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "分类id小于等于0"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.MoveMysteelChemicalClassify(req.BaseFromMysteelChemicalClassifyId, req.ParentBaseFromMysteelChemicalClassifyId, req.PrevBaseFromMysteelChemicalClassifyId, req.NextBaseFromMysteelChemicalClassifyId, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "移动成功"
}

// DeleteMysteelChemicalClassify
// @Title 删除分类
// @Description 删除分类接口
// @Param	request	body data_manage.DelBaseFromMysteelChemicalClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /mysteel_chemical/classify/del [post]
func (this *EdbClassifyController) DeleteMysteelChemicalClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.DelBaseFromMysteelChemicalClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.BaseFromMysteelChemicalClassifyId < 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.DelMysteelChemicalClassify(req.BaseFromMysteelChemicalClassifyId, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// MysteelChemicalSearch
// @Title 钢联化工指标查询
// @Description 钢联化工指标查询
// @Param   BaseFromMysteelChemicalClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "名称关键词"
// @Success 200 {object} data_manage.LzFrequency
// @router /mysteel_chemical/search [get]
func (this *EdbInfoController) MysteelChemicalSearch() {
	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
	}
	classifyId, _ := this.GetInt("BaseFromMysteelChemicalClassifyId")

	var condition string
	var pars []interface{}
	if classifyId > 0 {
		condition += " AND base_from_mysteel_chemical_classify_id=? "
		pars = append(pars, classifyId)
	}
	keyword := this.GetString("Keyword")
	if keyword != `` {
		condition += " AND (index_name like ? OR index_code like ?) "
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	list, err := data_manage.GetMysteelChemicalIndex(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	for _, v := range list {
		v.UniqueCode = fmt.Sprint(v.BaseFromMysteelChemicalClassifyId, "_", v.Id)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// MysteelChemicalFrequency
// @Title 钢联化工数据频度
// @Description 钢联化工数据频度接口
// @Param   BaseFromMysteelChemicalClassifyId   query   int  true       "分类id"
// @Param   BaseFromMysteelChemicalIndexId   query   int  true       "钢联化工指标id"
// @Param   Keyword   query   string  true       "名称关键词"
// @Success 200 {object} data_manage.LzFrequency
// @router /mysteel_chemical/frequency [get]
func (this *EdbInfoController) MysteelChemicalFrequency() {
	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
	}

	var condition string
	var pars []interface{}

	var classifyId int
	var frequency string
	// 指定指标
	indexId, _ := this.GetInt("BaseFromMysteelChemicalIndexId")
	if indexId > 0 {
		condition += " AND base_from_mysteel_chemical_index_id = ? "
		pars = append(pars, indexId)
	} else {
		classifyId, _ = this.GetInt("BaseFromMysteelChemicalClassifyId")
		if classifyId <= 0 {
			br.Msg = "请选择分类"
			br.ErrMsg = "请选择分类"
			return
		}
	}

	if classifyId > 0 {
		condition += " AND base_from_mysteel_chemical_classify_id=? "
		pars = append(pars, classifyId)
	}
	if frequency != `` {
		condition += " AND frequency=? "
		pars = append(pars, frequency)
	}

	// 关键词搜索
	keyword := this.GetString("Keyword")
	if keyword != `` {
		condition += " AND (index_name like ? OR index_code like ?) "
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	edbFrequencyList := make([]string, 0)
	frequencyList, err := data_manage.GetMysteelChemicalFrequency(condition, pars)
	for _, unit := range frequencyList {
		edbFrequencyList = append(edbFrequencyList, unit.Frequency)
	}
	edbFrequencyList = sortEdbFrequency(edbFrequencyList)

	for i, v := range edbFrequencyList {
		frequencyList[i].Frequency = v
	}

	if err != nil {
		br.Msg = "获取频度失败"
		br.ErrMsg = "获取频度失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = frequencyList
}

// MysteelChemicalData
// @Title 获取钢联化工数据
// @Description 获取钢联化工数据
// @Param   BaseFromMysteelChemicalClassifyId   query   int  true       "分类id"
// @Param   BaseFromMysteelChemicalIndexId   query   int  true       "钢联化工指标id"
// @Param   Frequency   query   string  true       "频度名称"
// @Param   Keyword   query   string  true       "名称关键词"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} data_manage.LzFrequency
// @router /mysteel_chemical/data [get]
func (this *EdbInfoController) MysteelChemicalData() {
	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)

	var condition string
	var pars []interface{}

	var classifyId int
	var frequency string
	// 指定指标
	indexId, _ := this.GetInt("BaseFromMysteelChemicalIndexId")
	if indexId > 0 {
		condition += " AND base_from_mysteel_chemical_index_id = ? "
		pars = append(pars, indexId)
	} else {
		classifyId, _ = this.GetInt("BaseFromMysteelChemicalClassifyId")
		if classifyId <= 0 {
			br.Msg = "请选择分类"
			br.ErrMsg = "请选择分类"
			br.IsSendEmail = false
			return
		}
		frequency = this.GetString("Frequency")
		if frequency == "" {
			br.Msg = "请选择频度"
			br.ErrMsg = "请选择频度"
			br.IsSendEmail = false
			return
		}
	}

	if classifyId > 0 {
		condition += " AND base_from_mysteel_chemical_classify_id=? "
		pars = append(pars, classifyId)
	}
	if frequency != `` {
		condition += " AND frequency=? "
		pars = append(pars, frequency)
	}

	// 关键词搜索
	keyword := this.GetString("Keyword")
	if keyword != `` {
		condition += " AND (index_name like ? OR index_code like ?) "
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	//获取指标
	list, err := data_manage.GetMysteelChemicalIndex(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		total, err := data_manage.GetMysteelChemicalIndexDataCount(v.IndexCode)
		page := paging.GetPaging(currentIndex, pageSize, total)

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

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

// MysteelChemicalExport
// @Title 导出钢联化工数据
// @Description 导出钢联化工数据
// @Param   BaseFromMysteelChemicalClassifyId   query   int  true       "分类"
// @Param   BaseFromMysteelChemicalIndexId   query   string  true       "钢联化工指标id"
// @Param   Keyword   query   string  true       "名称关键词"
// @Success 200  导出成功
// @router /mysteel_chemical/export/dataList [get]
func (this *EdbClassifyController) MysteelChemicalExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	classifyId, _ := this.GetInt("BaseFromMysteelChemicalClassifyId") //分类
	frequency := this.GetString("Frequency")

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

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

	var condition string
	var pars []interface{}
	indexId, _ := this.GetInt("BaseFromMysteelChemicalIndexId")
	if indexId > 0 {
		condition += " AND base_from_mysteel_chemical_index_id = ? "
		pars = append(pars, indexId)
	}
	if classifyId > 0 {
		condition += " AND base_from_mysteel_chemical_classify_id=? "
		pars = append(pars, classifyId)
	}
	if frequency != `` {
		condition += " AND frequency=? "
		pars = append(pars, frequency)
	}
	// 关键词搜索
	keyword := this.GetString("Keyword")
	if keyword != `` {
		condition += " AND (index_name like ? OR index_code like ?) "
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	var frequencies []string
	frequencyList, err := data_manage.GetMysteelChemicalFrequency(condition, pars)
	for _, v := range frequencyList {
		frequencies = append(frequencies, v.Frequency)
	}

	fileName := `钢联化工数据`
	if frequencies == 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("")
	}
	for _, frequency := range frequencies {
		//获取指标
		var tmpCondition string
		var tmpPars []interface{}
		if indexId > 0 {
			tmpCondition += " AND base_from_mysteel_chemical_index_id = ? "
			tmpPars = append(pars, indexId)
		}
		if classifyId > 0 {
			tmpCondition += " AND base_from_mysteel_chemical_classify_id=? "
			tmpPars = append(pars, classifyId)
		}
		if frequency != `` {
			tmpCondition += " AND frequency=? "
			tmpPars = append(pars, frequency)
		}
		// 关键词搜索
		keyword := this.GetString("Keyword")
		if keyword != `` {
			tmpCondition += " AND (index_name like ? OR index_code like ?) "
			tmpPars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
		}
		//获取指标
		secNameList, err := data_manage.GetMysteelChemicalIndex(tmpCondition, tmpPars)
		if err != nil {
			fmt.Println("获取数据失败，Err:" + err.Error())
			return
		}
		if len(secNameList) <= 0 {
			fmt.Println("secNameList长度为0")
			return
		}

		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.GetBaseFromMysteelChemicalDataMaxCount(classifyId)
		if err != nil {
			fmt.Println("获取指标最大数据量失败", err.Error())
			return
		}
		fmt.Println("dataMax:", dataMax)
		setRowIndex := 6
		for k, sv := range secNameList {
			//获取数据
			dataList, err := data_manage.GetMysteelChemicalIndexDataByCode(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()
						}
					}
				}
			}
		}
	}

	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 += 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"
}

// AddMysteelChemical
// @Title 新增钢联化工指标
// @Description 新增钢联化工指标接口
// @Param	request	body data_manage.AddEdbClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /mysteel_chemical/add [post]
func (this *EdbClassifyController) AddMysteelChemical() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddBaseFromMysteelChemicalReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.IndexCode == "" {
		br.Msg = "请输入指标ID"
		br.IsSendEmail = false
		return
	}
	if req.BaseFromMysteelChemicalClassifyId <= 0 {
		br.Msg = "请选择分类"
		br.IsSendEmail = false
		return
	}

	req.IndexCode = utils.TrimStr(req.IndexCode)
	req.IndexCode = strings.Replace(req.IndexCode, "\t", "", -1)

	// 因为excel获取数据是界面化的，所以同一时间只能存在一个指标添加
	key := `mysteel_chemical:add`
	res := utils.Rc.SetNX(key, 1, 30*time.Second)
	if !res {
		br.Msg = "当前已存在添加中的指标，请在30秒后添加"
		br.IsSendEmail = false
		return
	}
	//添加指标
	mysteelChemicalIndexInfo, err, errMsg := data.AddMysteelChemicalIndex(req.BaseFromMysteelChemicalClassifyId, strings.ToUpper(req.IndexCode), req.UpdateWeek, req.UpdateTime, this.SysUser.AdminId, this.SysUser.RealName)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	resp := response.AddMysteelChemicalIndexInfoResp{
		BaseFromMysteelChemicalIndexId: mysteelChemicalIndexInfo.BaseFromMysteelChemicalIndexId,
		IndexCode:                      mysteelChemicalIndexInfo.IndexCode,
		UniqueCode:                     fmt.Sprint(mysteelChemicalIndexInfo.BaseFromMysteelChemicalClassifyId, "_", mysteelChemicalIndexInfo.BaseFromMysteelChemicalIndexId),
	}
	br.Data = resp
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

func sortEdbFrequency(frequencyList []string) (newFrequencyList []string) {
	var frequencyMap1 = map[string]int{
		"日度":  1,
		"周度":  2,
		"旬度":  3,
		"月度":  4,
		"季度":  5,
		"半年度": 6,
		"年度":  7,
	}

	var frequencyMap2 = map[int]string{
		1: "日度",
		2: "周度",
		3: "旬度",
		4: "月度",
		5: "季度",
		6: "半年度",
		7: "年度",
	}

	idList := make([]int, 0)
	for _, frequency := range frequencyList {
		idList = append(idList, frequencyMap1[frequency])
	}
	sort.Ints(idList)

	for _, id := range idList {
		newFrequencyList = append(newFrequencyList, frequencyMap2[id])
	}
	return
}

// EditMysteelChemical
// @Title 编辑钢联化工指标
// @Description 新增钢联化工指标接口
// @Param	request	body data_manage.AddEdbClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /mysteel_chemical/edit [post]
func (this *EdbClassifyController) EditMysteelChemical() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddBaseFromMysteelChemicalReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.BaseFromMysteelChemicalIndexId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if req.BaseFromMysteelChemicalClassifyId <= 0 {
		br.Msg = "请选择分类"
		br.IsSendEmail = false
		return
	}

	//编辑指标
	mysteelChemicalIndexInfo, err, errMsg := data.EditMysteelChemicalIndex(req.BaseFromMysteelChemicalIndexId, req.BaseFromMysteelChemicalClassifyId, req.UpdateWeek, req.UpdateTime, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	resp := response.AddMysteelChemicalIndexInfoResp{
		BaseFromMysteelChemicalIndexId: mysteelChemicalIndexInfo.BaseFromMysteelChemicalIndexId,
		IndexCode:                      mysteelChemicalIndexInfo.IndexCode,
		UniqueCode:                     fmt.Sprint(mysteelChemicalIndexInfo.BaseFromMysteelChemicalClassifyId, "_", mysteelChemicalIndexInfo.BaseFromMysteelChemicalIndexId),
	}
	br.Data = resp
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// DeleteMysteelChemical
// @Title 删除指标
// @Description 删除指标接口
// @Param	request	body data_manage.DelBaseFromMysteelChemicalReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /mysteel_chemical/del [post]
func (this *EdbClassifyController) DeleteMysteelChemical() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.DelBaseFromMysteelChemicalReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.BaseFromMysteelChemicalIndexId < 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.DelMysteelChemical(req.BaseFromMysteelChemicalIndexId, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = errMsg + ";Err:" + err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// MoveMysteelChemical
// @Title 指标移动接口
// @Description 分类移动接口
// @Success 200 {object} data_manage.MoveBaseFromMysteelChemicalReq
// @router /mysteel_chemical/move [post]
func (this *EdbClassifyController) MoveMysteelChemical() {
	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
	}

	var req request.MoveBaseFromMysteelChemicalReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.BaseFromMysteelChemicalIndexId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "指标id小于等于0"
		br.IsSendEmail = false
		return
	}

	if req.BaseFromMysteelChemicalClassifyId <= 0 {
		br.Msg = "请选择分类"
		br.ErrMsg = "请选择分类"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.MoveMysteelChemical(req.BaseFromMysteelChemicalIndexId, req.BaseFromMysteelChemicalClassifyId, req.PrevBaseFromMysteelChemicalIndexId, req.NextBaseFromMysteelChemicalIndexId, this.SysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "移动成功"
}

// MysteelChemicalDetail
// @Title 钢联化工指标详情
// @Description 钢联化工指标详情接口
// @Param   BaseFromMysteelChemicalIndexId   query   string  true       "钢联化工指标id"
// @Success 200 {object} data_manage.BaseFromMysteelChemicalClassifyItems
// @router /mysteel_chemical/detail [get]
func (this *EdbInfoController) MysteelChemicalDetail() {
	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
	}

	indexId, _ := this.GetInt("BaseFromMysteelChemicalIndexId")
	if indexId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	item, err := data_manage.GetBaseFromMysteelChemicalIndexByIndexId(indexId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err：" + err.Error()
	}

	if item.UpdateTime2 != `` {
		item.UpdateTime = item.UpdateTime + "," + item.UpdateTime2
	}

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

// MysteelChemicalDetail
// @Title 钢联化工指标详情
// @Description 钢联化工指标详情接口
// @Param   BaseFromMysteelChemicalIndexId   query   string  true       "钢联化工指标id"
// @Success 200 {object} data_manage.BaseFromMysteelChemicalClassifyItems
// @router /mysteel_chemical/refresh [get]
func (this *EdbInfoController) MysteelChemicalRefresh() {
	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
	}

	// 每次刷新都需要两分钟的等待时间
	setNxKey := utils.CACHE_KEY_MYSTEEL_REFRESH
	if !utils.Rc.SetNX(setNxKey, 1, 2*60*time.Second) {
		br.Msg = "系统正在处理数据生成，请2分钟之后刷新"
		br.IsSendEmail = false
		return
	}

	indexId, _ := this.GetInt("BaseFromMysteelChemicalIndexId")
	if indexId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	item, err := data_manage.GetBaseFromMysteelChemicalIndexByIndexId(indexId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err：" + err.Error()
	}

	if item.MergeFilePath == "" {
		br.Msg = "系统正在处理数据生成，请5分钟之后刷新"
		br.IsSendEmail = false
		return
	}

	go data.CurlRefreshMysteelChemicalData(item.MergeFilePath)
	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
	br.Data = item
}
