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/services/alarm_msg"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// @Title 有色数据分类
// @Description 有色数据分类接口
// @Success 200 {object} data_manage.SciClassify
// @router /sci/classify [get]
func (this *EdbInfoController) SciClassify() {
	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.GetBaseFromSciClassifyByParentId(0)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

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

	baseFromSciIndexMap := make(map[int][]*data_manage.BaseFromSciClassifyItems)

	allBaseFromSciIndex, err := data_manage.GetSciIndexAll()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取指标信息失败，Err:" + err.Error()
		return
	}
	for _, v := range allBaseFromSciIndex {
		baseFromSciIndexMap[v.ClassifyId] = append(baseFromSciIndexMap[v.ClassifyId], v)
	}

	rootChildMap := make(map[int][]*data_manage.BaseFromSciClassifyItems)
	for _, v := range classifyAll {
		rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], v)
		if existItems, ok := baseFromSciIndexMap[v.ClassifyId]; ok {
			v.Children = existItems
		} else {
			items := make([]*data_manage.BaseFromSciClassifyItems, 0)
			v.Children = items
		}
	}
	var ret data_manage.BaseFromSciClassifyResp
	nodeAll := make([]*data_manage.BaseFromSciClassifyItems, 0)
	for _, v := range rootList {
		if existItems, ok := rootChildMap[v.ClassifyId]; ok {
			v.Children = existItems
		} else {
			items := make([]*data_manage.BaseFromSciClassifyItems, 0)
			v.Children = items
		}
		nodeAll = append(nodeAll, v)
	}

	//查询未分类的指标列表
	initClassify := &data_manage.BaseFromSciClassifyItems{
		ClassifyId:         0,
		BaseFromSciIndexId: 0,
		ClassifyName:       "未分类",
		ParentId:           0,
		Level:              1,
		Sort:               0,
		Children:           nil,
	}
	initIndexList, err := data_manage.GetBaseFromSciIndexByClassifyId(initClassify.ClassifyId)
	if err != nil {
		br.Msg = "获取未分类指标失败"
		br.ErrMsg = "获取未分类指标失败，Err:" + err.Error()
		return
	}

	for _, v := range initIndexList {
		tmp := &data_manage.BaseFromSciClassifyItems{
			ClassifyId:           v.ClassifyId,
			BaseFromSciIndexId:   v.BaseFromSciIndexId,
			BaseFromSciIndexCode: v.IndexCode,
			ClassifyName:         v.IndexName,
			ParentId:             0,
			Level:                0,
			Sort:                 0,
			Children:             nil,
		}
		initClassify.Children = append(initClassify.Children, tmp)
	}
	finalList := make([]*data_manage.BaseFromSciClassifyItems, 0)
	finalList = append(finalList, initClassify)
	finalList = append(finalList, nodeAll...)
	ret.List = finalList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = ret
}

// SciClassifyName
// @Title 有色数据分类名称查询
// @Description 有色数据分类名称查询接口
// @Success 200 {object} data_manage.SciClassify
// @router /sci/classify/name [get]
func (this *EdbInfoController) SciClassifyName() {
	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.GetBaseFromSciClassifyByParentId(0)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

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

	rootChildMap := make(map[int][]*data_manage.BaseFromSciClassifyNameItems)
	for _, v := range classifyAll {
		tmp := &data_manage.BaseFromSciClassifyNameItems{
			ClassifyId:   v.ClassifyId,
			ClassifyName: v.ClassifyName,
			ParentId:     v.ParentId,
			Children:     nil,
		}
		rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], tmp)
	}
	var ret data_manage.BaseFromSciClassifyNameResp
	nodeAll := make([]*data_manage.BaseFromSciClassifyNameItems, 0)
	for _, v := range rootList {
		tmp := &data_manage.BaseFromSciClassifyNameItems{
			ClassifyId:   v.ClassifyId,
			ClassifyName: v.ClassifyName,
			ParentId:     v.ParentId,
			Children:     nil,
		}
		if existItems, ok := rootChildMap[v.ClassifyId]; ok {
			tmp.Children = existItems
		} else {
			items := make([]*data_manage.BaseFromSciClassifyNameItems, 0)
			tmp.Children = items
		}
		nodeAll = append(nodeAll, tmp)
	}

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

// AddSciClassify
// @Title 新增分类
// @Description 新增分类接口
// @Param	request	body data_manage.AddBaseFromSciClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /sci/classify/add [post]
func (this *EdbInfoController) AddSciClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddBaseFromSciClassifyReq
	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)

	//添加指标
	sciClassifyInfo, err, errMsg := data.AddSciClassify(req.ClassifyName, req.ParentId, 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 sciClassifyInfo.ParentId == 0 {
		secondClassifyList := []string{"价格", "供应", "需求", "库存"}
		for _, v := range secondClassifyList {
			_, _, tmpErrMsg := data.AddSciClassify(v, sciClassifyInfo.ClassifyId, this.SysUser.AdminId, this.SysUser.RealName)
			if tmpErrMsg != `` {
				go alarm_msg.SendAlarmMsg("SCI原始数据-添加一级分类时，默认添加二级分类失败,一级分类名称："+req.ClassifyName+",二级分类名称："+v+", Err："+tmpErrMsg, 3)
				return
			}
		}
	}
	resp := data_manage.AddSciClassifyResp{
		ClassifyId: sciClassifyInfo.ClassifyId,
		//UniqueCode:                        fmt.Sprint(SciClassifyInfo.BaseFromSciClassifyId),
	}
	br.Data = resp
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// EditSciClassify
// @Title 修改分类
// @Description 修改分类接口
// @Param	request	body data_manage.EditBaseFromMysteelChemicalClassifyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /sci/classify/edit [post]
func (this *EdbInfoController) EditSciClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.EditBaseFromSciClassifyReq
	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.ClassifyId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data.EditSciClassify(req.ClassifyId, 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
}

// @Title 有色数据频度
// @Description 有色数据频度接口
// @Param   ClassifyId   query   string  true       "分类Id"
// @Success 200 {object} data_manage.LzFrequency
// @router /sci/frequency [get]
func (this *EdbInfoController) SciFrequency() {
	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("ClassifyId")
	if classifyId < 0 {
		br.Msg = "请选择分类"
		br.ErrMsg = "请选择分类"
		return
	}

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

// MoveSciClassify
// @Title 分类移动接口
// @Description 分类移动接口
// @Success 200 {object} data_manage.MoveBaseFromMysteelChemicalClassifyReq
// @router /sci/classify/move [post]
func (this *EdbInfoController) MoveSciClassify() {
	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.MoveBaseFromSciClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

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

	err, errMsg := data.MoveSciClassify(req.ClassifyId, req.ParentId, req.PrevClassifyId, req.NextClassifyId)
	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 = "移动成功"
}

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

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

	err, errMsg := data.DelSciClassify(req.ClassifyId, 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
}

// MoveSciData
// @Title SCI指标移动接口
// @Description SCI指标移动接口
// @Success 200 {object} data_manage.MoveBaseFromSciReq
// @router /sci/move [post]
func (this *EdbInfoController) MoveSciData() {
	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.MoveBaseFromSciReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

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

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

	err, errMsg := data.MoveSciData2(req.BaseFromSciIndexId, req.ClassifyId, req.PrevBaseFromSciIndexId, req.NextBaseFromSciIndexId)
	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 = "移动成功"
}

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

	//编辑指标
	sciIndexInfo, err, errMsg := data.EditSciIndex(req.BaseFromSciIndexId, req.ClassifyId, 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 := data_manage.EditSciIndexInfoResp{
		BaseFromSciIndexId: sciIndexInfo.BaseFromSciIndexId,
		IndexCode:          sciIndexInfo.IndexCode,
	}
	br.Data = resp
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// @Title 获取钢联数据
// @Description 获取钢联数据接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyId   query   string  true       "分类id"
// @Param   Frequency   query   string  true       "频度名称"
// @Success 200 {object} data_manage.LzFrequency
// @router /sci/data [get]
func (this *EdbInfoController) SciData() {
	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)

	classifyId, _ := this.GetInt("ClassifyId")
	if classifyId < 0 {
		br.Msg = "请选择分类"
		br.ErrMsg = "请选择分类"
		return
	}
	frequency := this.GetString("Frequency")
	if frequency == "" {
		br.Msg = "请选择频度"
		br.ErrMsg = "请选择频度"
		return
	}

	//获取指标
	var condition string
	var pars []interface{}

	if classifyId >= 0 {
		condition += ` AND classify_id=? `
		pars = append(pars, classifyId)
	}

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

	sciList, err := data_manage.GetSciIndex(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	resultList := make([]*data_manage.SciIndexList, 0)
	for _, v := range sciList {
		product := new(data_manage.SciIndexList)
		product.BaseFromSciIndexId = v.BaseFromSciIndexId
		product.Unit = v.Unit
		product.IndexCode = v.IndexCode
		product.IndexName = v.IndexName
		product.Frequency = v.Frequency
		product.ModifyTime = v.ModifyTime

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

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

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

// SciSingleData
// @Title 获取Sci数据
// @Description 获取sci单条数据接口
// @Param   IndexCode   query   string  true       "指标唯一编码"
// @Success 200 {object} models.BaseResponse
// @router /sci/single_data [get]
func (this *EdbInfoController) SciSingleData() {
	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")
	indexInfo, err := data_manage.GetBaseFromSciIndexByIndexCode(indexCode)
	if err != nil {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标信息失败,Err:" + err.Error()
		return
	}
	dataList, err := data_manage.GetSciIndexDataByCode(indexCode)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	var ret data_manage.SciSingleDataResp
	ret.ClassifyId = indexInfo.ClassifyId
	ret.BaseFromSciIndexId = indexInfo.BaseFromSciIndexId
	ret.IndexCode = indexInfo.IndexCode
	ret.IndexName = indexInfo.IndexName
	ret.Frequency = indexInfo.Frequency
	ret.Interface = indexInfo.Interface
	ret.CreateTime = indexInfo.CreateTime.Format(utils.FormatDateTime)
	ret.ModifyTime = indexInfo.ModifyTime.Format(utils.FormatDateTime)
	ret.Unit = indexInfo.Unit
	ret.Data = dataList

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

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

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

	err, errMsg := data.DelSciData(req.BaseFromSciIndexId)
	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
}

// ResetSciData
// @Title 指标数据清除分类
// @Description 指标数据清除分类
// @Param	request	body data_manage.DelBaseFromSciReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /sci/reset [post]
func (this *EdbInfoController) ResetSciData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.DelBaseFromSciReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

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

	err, errMsg := data.ResetSciData(req.BaseFromSciIndexId)
	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
}

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

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

	//typeName := this.GetString("TypeName") //分类
	//frequency := this.GetString("Frequency")

	indexCode := this.GetString("IndexCode") //指标唯一编码
	classifyId, _ := this.GetInt("ClassifyId")
	secNameList := make([]*models.EdbdataExportList, 0)

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

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

	if classifyId >= 0 && indexCode == "" {

		frequencies, err := data_manage.GetSciFrequency(classifyId)
		if err != nil {
			fmt.Println("GetSciFrequency err:", err.Error())
			utils.FileLog.Info("GetSciFrequency err:" + err.Error())
			return
		}
		for _, frequency := range frequencies {

			//获取指标
			var pars []interface{}
			pars = append(pars, classifyId)
			pars = append(pars, frequency)
			condition := " AND classify_id=? AND frequency=? "
			secNameList, err := data_manage.GetSciIndex(condition, pars)
			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.GetSciDataMaxCount(classifyId)
			if err != nil {
				fmt.Println("获取指标最大数据量失败", err.Error())
				return
			}
			fmt.Println("dataMax:", dataMax)
			setRowIndex := 6
			for k, sv := range secNameList {
				//获取数据
				dataList, err := data_manage.GetSciIndexDataByCode(sv.IndexCode)
				if err != nil {
					br.Msg = "获取数据失败"
					br.ErrMsg = "获取数据失败,Err:" + err.Error()
					return
				}
				if len(dataList) > 0 {
					windRow.AddCell().SetValue("Sci")
					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.Frequency)

					unitRow.AddCell().SetValue(sv.Unit)
					lastModifyDateRow.AddCell().SetValue(sv.ModifyTime)

					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.Value)
							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 {
		frequencies, err := data_manage.GetSciFrequencyByCode(indexCode)
		if err != nil {
			fmt.Println("GetSciFrequencyByCode err:", err.Error())
			utils.FileLog.Info("GetSciFrequencyByCode err:" + err.Error())
			return
		}
		for _, frequency := range frequencies {
			//获取数据
			dataList, err := data_manage.GetSciIndexDataByCode(indexCode)
			if err != nil {
				br.Msg = "获取数据失败"
				br.ErrMsg = "获取数据失败,Err:" + err.Error()
				return
			}
			if len(dataList) > 0 {
				name := this.GetString("IndexName")
				unit := this.GetString("UnitName")
				modifyTime := this.GetString("ModifyTime")

				sheet, err := xlsxFile.AddSheet(*frequency)
				if err != nil {
					br.Msg = "新增Sheet失败"
					br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
					return
				}
				//获取指标数据
				windRow := sheet.AddRow()
				windRow.AddCell().SetValue("Sci")
				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)
				dataMax, err := data_manage.GetSciIndexDataCount(indexCode)
				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.Value)
						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 := `Sci数据`
	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"

}
