package data_manage

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/yidane/formula"
	"hongze/hz_crm_api/controllers"
	"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"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/services/excel"
	"hongze/hz_crm_api/utils"
	"os"
	"strconv"
	"strings"
	"time"
)

// ExcelInfoController ETA表格管理
type ExcelInfoController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增表格接口
// @Description 新增表格接口
// @Param	request	body request.AddExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/add [post]
func (this *ExcelInfoController) Add() {
	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
	}
	deleteCache := true
	cacheKey := "CACHE_EXCEL_TABLE_INFO_ADD_" + strconv.Itoa(sysUser.AdminId)
	defer func() {
		if deleteCache {
			_ = utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	var req request.AddExcelInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ExcelName = strings.Trim(req.ExcelName, " ")
	if req.ExcelName == "" {
		br.Msg = "请填写表格名称！"
		br.IsSendEmail = false
		return
	}

	if req.ExcelClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		br.IsSendEmail = false
		return
	}

	excelClassify, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			br.IsSendEmail = false
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if excelClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		br.IsSendEmail = false
		return
	}

	var condition string
	var pars []interface{}
	condition += " AND excel_classify_id=? "
	pars = append(pars, req.ExcelClassifyId)

	condition += " AND excel_name=? "
	pars = append(pars, req.ExcelName)

	// 获取分类下是否存在该表格名称
	count, err := data_manage.GetExcelInfoCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "判断表格名称是否存在失败"
		br.ErrMsg = "判断表格名称是否存在失败,Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "表格名称已存在，请重新填写表格名称"
		br.IsSendEmail = false
		return
	}

	// 默认的excel类型是1
	if req.Source == 0 {
		req.Source = 1
	}
	content := req.Content
	// 自定义表格
	if req.Source == 2 {
		jsonStrByte, err := json.Marshal(req.TableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,转json失败，Err:" + err.Error()
			return
		}
		var tableData request.TableDataReq
		err = json.Unmarshal(jsonStrByte, &tableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,json转结构体失败，Err:" + err.Error()
			return
		}

		tableDataConfig, err := data.GetTableDataConfig(tableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,Err:" + err.Error()
			return
		}
		contentByte, err := json.Marshal(tableDataConfig)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取后，转json失败,Err:" + err.Error()
			return
		}
		content = string(contentByte)
	}

	// 混合表格
	if req.Source == 3 {
		contentByte, err := json.Marshal(req.TableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取后，转json失败,Err:" + err.Error()
			return
		}
		content = string(contentByte)
	}

	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	excelInfo := &data_manage.ExcelInfo{
		//ExcelInfoId:     0,
		ExcelName:       req.ExcelName,
		Source:          req.Source,
		ExcelType:       req.ExcelType,
		UniqueCode:      utils.MD5(utils.EXCEL_DATA_PREFIX + "_" + timestamp),
		ExcelClassifyId: req.ExcelClassifyId,
		SysUserId:       sysUser.AdminId,
		SysUserRealName: sysUser.RealName,
		Content:         content,
		ExcelImage:      req.ExcelImage,
		Sort:            0,
		IsDelete:        0,
		ModifyTime:      time.Now(),
		CreateTime:      time.Now(),
	}

	err = data_manage.AddExcelInfo(excelInfo)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	// 更新excel下载地址(默认的EXCEL需要更新，自定义表格不需要更新）
	if req.Source == 1 {
		go UpdateExcelInfoFileUrl(excelInfo)
	}

	resp := new(response.AddExcelInfoResp)
	resp.ExcelInfoId = excelInfo.ExcelInfoId
	resp.UniqueCode = excelInfo.UniqueCode

	//新增操作日志
	//{
	//	excelLog := &data_manage.ExcelInfoLog{
	//		//ExcelInfoLogId:  0,
	//		ExcelInfoId:     excelInfo.ExcelInfoId,
	//		ExcelName:       req.ExcelName,
	//		ExcelClassifyId: req.ExcelClassifyId,
	//		SysUserId:       sysUser.AdminId,
	//		SysUserRealName: sysUser.RealName,
	//		UniqueCode:      excelInfo.UniqueCode,
	//		CreateTime:      time.Now(),
	//		Content:         string(this.Ctx.Input.RequestBody),
	//		Status:          "新增表格",
	//		Method:          this.Ctx.Input.URI(),
	//	}
	//	go data_manage.AddExcelInfoLog(excelLog)
	//}

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

// List
// @Title ETA表格列表接口
// @Description ETA表格列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ExcelClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   AdminId   query   int  false       "创建人id"
// @Success 200 {object} response.ExcelListResp
// @router /excel_info/list [get]
func (this *ExcelInfoController) List() {
	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
	}

	excelClassifyId, _ := this.GetInt("ExcelClassifyId")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyword := this.GetString("Keyword")
	adminId, _ := this.GetInt("AdminId")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

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

	var condition string
	var pars []interface{}

	// 筛选分类
	if excelClassifyId > 0 {
		_, err := data_manage.GetExcelClassifyById(excelClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取表格信息失败"
			br.ErrMsg = "获取信息失败,GetExcelClassify,Err:" + err.Error()
			return
		}
		condition += " AND excel_classify_id = ? "
		pars = append(pars, excelClassifyId)
	}
	if keyword != "" {
		condition += ` AND  ( excel_name LIKE ? )`
		pars = append(pars, `%`+keyword+`%`)
	}
	if adminId > 0 {
		condition += " AND sys_user_id = ? "
		pars = append(pars, adminId)
	}
	//获取表格信息
	list, err := data_manage.GetNoContentExcelListByCondition(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取表格信息失败"
		br.ErrMsg = "获取表格信息失败,Err:" + err.Error()
		return
	}

	if list == nil || len(list) <= 0 || (err != nil && err.Error() == utils.ErrNoRow()) {
		list = make([]*data_manage.MyExcelInfoList, 0)
	}
	// 总数据量
	dataCount, err := data_manage.GetExcelListCountByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取表格列表信息失败"
		br.ErrMsg = "获取表格列表数据总数失败,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, dataCount)

	resp := response.ExcelListResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Detail
// @Title 获取表格详情
// @Description 获取表格详情接口
// @Param   ExcelInfoId   query   int  true       "表格id"
// @Success 200 {object} data_manage.ExcelInfo
// @router /excel_info/detail [get]
func (this *ExcelInfoController) Detail() {
	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
	}

	excelInfoId, _ := this.GetInt("ExcelInfoId")
	if excelInfoId <= 0 {
		br.Msg = "请选择表格"
		br.ErrMsg = "ExcelInfoId未传"
		br.IsSendEmail = false
		return
	}

	// 获取数据详情
	excelDetail, errMsg, err := data.GetExcelDetailInfoByExcelInfoId(excelInfoId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = err.Error()
		return
	}

	// excel表格按钮权限
	excelDetail.Button = data.GetExcelInfoOpButton(sysUser, excelDetail.SysUserId, excelDetail.Source)

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

// Edit
// @Title 编辑表格接口
// @Description 新增表格接口
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/edit [post]
func (this *ExcelInfoController) Edit() {
	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
	}
	deleteCache := true
	var req request.EditExcelInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ExcelInfoId <= 0 {
		br.Msg = "请传入ETA表格标识！"
		return
	}

	cacheKey := "CACHE_TABLE_INFO_EDIT_" + strconv.Itoa(req.ExcelInfoId)
	defer func() {
		if deleteCache {
			_ = utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	req.ExcelName = strings.Trim(req.ExcelName, " ")
	if req.ExcelName == "" {
		br.Msg = "请填写表格名称！"
		br.IsSendEmail = false
		return
	}

	if req.ExcelClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		br.IsSendEmail = false
		return
	}

	excelClassify, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			br.IsSendEmail = false
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if excelClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		br.IsSendEmail = false
		return
	}

	//判断表格是否存在
	var condition string
	var pars []interface{}
	condition += " AND excel_info_id != ? "
	pars = append(pars, req.ExcelInfoId)

	condition += " AND excel_classify_id=? "
	pars = append(pars, req.ExcelClassifyId)

	condition += " AND excel_name=? "
	pars = append(pars, req.ExcelName)

	// 获取分类下是否存在该表格名称
	count, err := data_manage.GetExcelInfoCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "ETA判断表格名称是否存在失败"
		br.ErrMsg = "判断ETA表格名称是否存在失败,Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "ETA表格名称已存在，请重新填写"
		br.IsSendEmail = false
		return
	}

	excelInfo, err := data_manage.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}

	// 操作权限校验
	{
		button := data.GetExcelInfoOpButton(sysUser, excelInfo.SysUserId, excelInfo.Source)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}

	content := req.Content
	switch excelInfo.Source {
	case 2: // 自定义表格
		jsonStrByte, err := json.Marshal(req.TableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,转json失败，Err:" + err.Error()
			return
		}
		var tableData request.TableDataReq
		err = json.Unmarshal(jsonStrByte, &tableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,json转结构体失败，Err:" + err.Error()
			return
		}
		tableDataConfig, err := data.GetTableDataConfig(tableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,Err:" + err.Error()
			return
		}
		contentByte, err := json.Marshal(tableDataConfig)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取后，转json失败,Err:" + err.Error()
			return
		}
		content = string(contentByte)
	case 3: // 混合表格
		contentByte, err := json.Marshal(req.TableData)
		if err != nil {
			br.Msg = "混合表格数据获取失败"
			br.ErrMsg = "混合表格数据获取后，转json失败,Err:" + err.Error()
			return
		}
		content = string(contentByte)
	}

	excelInfo.ModifyTime = time.Now()
	excelInfo.ExcelName = req.ExcelName
	excelInfo.ExcelType = req.ExcelType
	excelInfo.ExcelClassifyId = req.ExcelClassifyId
	excelInfo.ExcelImage = req.ExcelImage
	excelInfo.Content = content

	updateExcelInfoParams := []string{"ModifyTime", "ExcelName", "ExcelType", "ExcelClassifyId", "ExcelImage", "Content"}

	err = data_manage.EditExcelInfo(excelInfo, updateExcelInfoParams)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	// 更新excel下载地址(默认的EXCEL需要更新，自定义表格不需要更新）
	if excelInfo.Source == 1 {
		go UpdateExcelInfoFileUrl(excelInfo)
	}

	// 加入草稿
	{
		excelDraftInfo := &data_manage.ExcelDraft{
			//ExcelDraftId: 0,
			ExcelId:    req.ExcelInfoId,
			Name:       req.ExcelName,
			Content:    content,
			OpUserId:   sysUser.AdminId,
			OpUserName: sysUser.RealName,
			CreateTime: time.Now(),
		}

		err = data_manage.AddExcelDraft(excelDraftInfo)
	}

	resp := response.AddExcelInfoResp{
		ExcelInfoId: excelInfo.ExcelInfoId,
		UniqueCode:  excelInfo.UniqueCode,
	}

	//删除公共图库那边的缓存
	_ = utils.Rc.Delete(utils.HZ_CHART_LIB_EXCEL_TABLE_DETAIL + ":" + excelInfo.UniqueCode)

	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
	br.Data = resp
	br.IsAddLog = true
}

// Move
// @Title 移动表格接口
// @Description 移动表格接口
// @Param	request	body request.MoveExcelInfoReq true "type json string"
// @Success Ret=200 移动成功
// @router /excel_info/move [post]
func (this *ExcelInfoController) Move() {
	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.MoveExcelInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ExcelInfoId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "表格id小于等于0"
		br.IsSendEmail = false
		return
	}

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

	//判断分类是否存在
	_, err = data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取分类信息失败" + err.Error()

		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类已被删除，不可移动，请刷新页面"
			br.ErrMsg = "分类已被删除，不可移动，请刷新页面"
			br.IsSendEmail = false
		}
		return
	}

	// 获取表格信息
	excelInfo, err := data_manage.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取表格信息失败,Err:" + err.Error()
		return
	}

	//如果改变了分类，那么移动该表格数据
	if excelInfo.ExcelClassifyId != req.ExcelClassifyId {
		//查询需要修改的分类下是否存在同一个表格名称
		tmpExcelInfo, tmpErr := data_manage.GetExcelInfoByClassifyIdAndName(req.ExcelClassifyId, excelInfo.ExcelName)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "移动失败,Err:" + tmpErr.Error()
			return
		}
		if tmpExcelInfo != nil {
			br.Msg = "移动失败，同一个分类下表格名称不允许重复"
			br.ErrMsg = "移动失败，同一个分类下表格名称不允许重复"
			br.IsSendEmail = false
			return
		}

		// 变更表格的所属分类
		excelInfo.ExcelClassifyId = req.ExcelClassifyId
		err = excelInfo.Update([]string{"ExcelClassifyId"})
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "移动失败,Err:" + err.Error()
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	//如果有传入 上一个兄弟节点分类id
	if req.PrevExcelInfoId > 0 {
		prevExcelInfo, err := data_manage.GetExcelInfoById(req.PrevExcelInfoId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取上一个兄弟节点分类信息失败,Err:" + err.Error()
			return
		}

		//如果是移动在两个兄弟节点之间
		if req.NextExcelInfoId > 0 {
			//下一个兄弟节点
			nextExcelInfo, err := data_manage.GetExcelInfoById(req.NextExcelInfoId)
			if err != nil {
				br.Msg = "移动失败"
				br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
				return
			}
			//如果上一个兄弟与下一个兄弟的排序权重是一致的，那么需要将下一个兄弟（以及下个兄弟的同样排序权重）的排序权重+2，自己变成上一个兄弟的排序权重+1
			if prevExcelInfo.Sort == nextExcelInfo.Sort || prevExcelInfo.Sort == excelInfo.Sort {
				//变更兄弟节点的排序
				updateSortStr := `sort + 2`
				_ = data_manage.UpdateExcelInfoSortByClassifyId(prevExcelInfo.ExcelClassifyId, prevExcelInfo.Sort, prevExcelInfo.ExcelInfoId, updateSortStr)
			} else {
				//如果下一个兄弟的排序权重正好是上个兄弟节点下一层，那么需要再加一层了
				if nextExcelInfo.Sort-prevExcelInfo.Sort == 1 {
					//变更兄弟节点的排序
					updateSortStr := `sort + 1`
					_ = data_manage.UpdateExcelInfoSortByClassifyId(prevExcelInfo.ExcelClassifyId, prevExcelInfo.Sort, prevExcelInfo.ExcelInfoId, updateSortStr)
				}
			}
		}

		// 变更表格在当前分类下的排序
		excelInfo.Sort = prevExcelInfo.Sort + 1
		excelInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")

	} else {
		firstClassify, err := data_manage.GetFirstExcelInfoByClassifyId(req.ExcelClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + err.Error()
			return
		}

		//如果该分类下存在其他分类，且第一个其他分类的排序等于0，那么需要调整排序
		if firstClassify != nil && firstClassify.Sort == 0 {
			updateSortStr := ` sort + 1 `
			_ = data_manage.UpdateExcelInfoSortByClassifyId(firstClassify.ExcelClassifyId, 0, firstClassify.ExcelInfoId-1, updateSortStr)
		}

		// 变更表格在当前分类下的排序
		excelInfo.Sort = 0 //那就是排在第一位
		excelInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	}

	//更新
	if len(updateCol) > 0 {
		err = excelInfo.Update(updateCol)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "修改失败,Err:" + err.Error()
			return
		}
	}

	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "修改失败,Err:" + err.Error()
		return
	}

	//新增操作日志
	//{
	//	ExcelLog := new(data_manage.ExcelInfoLog)
	//	ExcelLog.ExcelName = ExcelInfo.ExcelName
	//	ExcelLog.ExcelInfoId = req.ExcelInfoId
	//	ExcelLog.ExcelClassifyId = ExcelInfo.ExcelClassifyId
	//	ExcelLog.SysUserId = sysUser.AdminId
	//	ExcelLog.SysUserRealName = sysUser.RealName
	//	ExcelLog.UniqueCode = ExcelInfo.UniqueCode
	//	ExcelLog.CreateTime = time.Now()
	//	ExcelLog.Content = string(this.Ctx.Input.RequestBody)
	//	ExcelLog.Status = "移动表格"
	//	ExcelLog.Method = this.Ctx.Input.URL()
	//	go data_manage.AddExcelInfoLog(ExcelLog)
	//}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "移动成功"
}

// Delete
// @Title 删除表格接口
// @Description 删除表格接口
// @Param	request	body request.DeleteExcelInfoReq true "type json string"
// @Success Ret=200 删除成功
// @router /excel_info/delete [post]
func (this *ExcelInfoController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	resp := response.AddExcelInfoResp{}

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

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

	if req.ExcelInfoId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "表格id小于等于0"
		br.IsSendEmail = false
		return
	}

	// 获取表格信息
	excelInfo, err := data_manage.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "获取表格信息失败,Err:" + err.Error()
		return
	}

	// 操作权限校验
	{
		button := data.GetExcelInfoOpButton(sysUser, excelInfo.SysUserId, excelInfo.Source)
		if !button.DeleteButton {
			br.Msg = "无操作权限"
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}

	//更新
	excelInfo.IsDelete = 1
	err = excelInfo.Update([]string{"IsDelete"})
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	// 返回下一个表格的信息
	{
		var nextItem *data_manage.ExcelInfo
		var condition string
		var pars []interface{}
		condition += " AND excel_classify_id=? "
		pars = append(pars, excelInfo.ExcelClassifyId)

		condition += " AND sort>=? "
		pars = append(pars, excelInfo.Sort)
		nextItem, err = data_manage.GetNextExcelInfoByCondition(condition, pars)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "删除失败"
			br.ErrMsg = "获取下一级表格信息失败，Err:" + err.Error()
			return
		}

		// 如果没找到，那么查找下一个分类的第一个表格
		if nextItem == nil {
			currClassifyInfo, err := data_manage.GetExcelClassifyById(excelInfo.ExcelClassifyId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "删除失败"
				br.ErrMsg = "获取当前表格分类信息失败，Err:" + err.Error()
				return
			}
			//condition += " AND level=3 "
			//pars = append(pars, chartInfo.ExcelClassifyId)

			//var condition string
			//var pars []interface{}
			//condition += " AND sort>=? ORDER BY excel_classify_id ASC LIMIT 1 "
			//pars = append(pars, currClassifyInfo.Sort)
			//
			//classifyItem, err := data_manage.GetNextExcelClassifyByCondition(condition, pars)
			//if err != nil && err.Error() != utils.ErrNoRow() {
			//	br.Msg = "删除失败"
			//	br.ErrMsg = "获取下一级表格分类信息失败，Err:" + err.Error()
			//	return
			//}
			//if classifyItem != nil {
			//	nextItem, err = data_manage.GetNextExcelInfo(excelInfo.ExcelClassifyId,)
			//	if err != nil && err.Error() != utils.ErrNoRow() {
			//		br.Msg = "删除失败"
			//		br.ErrMsg = "获取下一级表格信息失败，Err:" + err.Error()
			//		return
			//	}
			//}

			nextItem, err = data_manage.GetNextExcelInfo(excelInfo.ExcelClassifyId, currClassifyInfo.Sort)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "删除失败"
				br.ErrMsg = "获取下一级表格信息失败，Err:" + err.Error()
				return
			}
		}

		// 如果找到下一个表格了，那么就返回
		if nextItem != nil {
			resp = response.AddExcelInfoResp{
				ExcelInfoId: nextItem.ExcelInfoId,
				UniqueCode:  nextItem.UniqueCode,
			}
		}
	}

	//删除公共图库那边的缓存
	_ = utils.Rc.Delete(utils.HZ_CHART_LIB_EXCEL_TABLE_DETAIL)

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

// AddDraft
// @Title 新增表格草稿接口
// @Description 新增表格草稿接口
// @Param	request	body request.AddExcelDraftReq true "type json string"
// @Success Ret=200 添加成功
// @router /excel_info/draft/add [post]
func (this *ExcelInfoController) AddDraft() {
	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.AddExcelDraftReq

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ExcelName = strings.Trim(req.ExcelName, " ")
	if req.ExcelName == "" {
		br.Msg = "请填写表格名称！"
		br.IsSendEmail = false
		return
	}

	if req.ExcelClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		br.IsSendEmail = false
		return
	}

	excelClassify, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			br.IsSendEmail = false
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if excelClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		br.IsSendEmail = false
		return
	}

	var condition string
	var pars []interface{}
	condition += " AND excel_classify_id=? "
	pars = append(pars, req.ExcelClassifyId)

	condition += " AND excel_name=? "
	pars = append(pars, req.ExcelName)

	// 获取分类下是否存在该表格名称
	_, err = data_manage.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "判断表格名称是否存在失败"
		br.ErrMsg = "判断表格名称是否存在失败,Err:" + err.Error()
		return
	}

	excelDraftInfo := &data_manage.ExcelDraft{
		//ExcelDraftId: 0,
		ExcelId:    req.ExcelInfoId,
		Name:       req.ExcelName,
		Content:    req.Content,
		OpUserId:   sysUser.AdminId,
		OpUserName: sysUser.RealName,
		CreateTime: time.Now(),
	}

	err = data_manage.AddExcelDraft(excelDraftInfo)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "添加成功"
}

// GetExcelTableData
// @Title 获取excel表格的table数据
// @Description 获取excel表格的table数据接口
// @Param   UniqueCode   query   string  true       "表格code"
// @Success 200 {object} response.ExcelTableDetailResp
// @router /excel_info/table_data [get]
func (this *ExcelInfoController) GetExcelTableData() {
	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
	}
	uniqueCode := this.GetString("UniqueCode")

	var err error
	if uniqueCode == `` {
		br.Msg = "请选择表格"
		br.ErrMsg = "UniqueCode未传"
		br.IsSendEmail = false
		return
	}
	//获取eta表格信息
	excelInfo, err := data_manage.GetExcelInfoByUniqueCode(uniqueCode)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取ETA表格信息失败，Err:" + err.Error()
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "ETA表格被删除，请刷新页面"
			br.ErrMsg = "ETA表格被删除，请刷新页面，Err:" + err.Error()
			br.IsSendEmail = false
		}
		return
	}

	var tableData excel.TableData
	switch excelInfo.Source {
	case 1:
		luckySheetData, err := excel.GetLuckySheetData(excelInfo.Content)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取excel数据失败，Err:" + err.Error()
			return
		}
		tableData, err = luckySheetData.GetTableDataByLuckySheetDataStr()
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "转换成table失败，Err:" + err.Error()
			return
		}
	case 2:
		var tableDataConfig data.TableDataConfig
		err = json.Unmarshal([]byte(excelInfo.Content), &tableDataConfig)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "表格json转结构体失败，Err:" + err.Error()
			return
		}
		result, err := data.GetDataByTableDataConfig(tableDataConfig)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取最新的表格数据失败，Err:" + err.Error()
			return
		}
		tableData, err = excel.GetTableDataByCustomData(excelInfo.ExcelType, result)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "转换成table失败，Err:" + err.Error()
			return
		}
	case 3:
		var result request.MixedTableReq
		err = json.Unmarshal([]byte(excelInfo.Content), &result)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "表格json转结构体失败，Err:" + err.Error()
			return
		}
		newResult, tmpErr := data.GetMixedTableCellData(result.Data)
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取最新的数据失败，Err:" + err.Error()
			return
		}
		tableData, err = excel.GetTableDataByMixedTableData(newResult)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "转换成table失败，Err:" + err.Error()
			return
		}

	}

	tableData = excel.HandleTableCell(tableData)

	resp := response.ExcelTableDetailResp{
		UniqueCode: excelInfo.UniqueCode,
		ExcelImage: excelInfo.ExcelImage,
		ExcelName:  excelInfo.ExcelName,
		TableInfo:  tableData,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// UpdateExcelInfoFileUrl 更新excel表格的下载地址
func UpdateExcelInfoFileUrl(excelInfo *data_manage.ExcelInfo) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprintf("更新excel表格的下载地址失败，表格id：%d；表格名称：%s； ERR:%s", excelInfo.ExcelInfoId, excelInfo.ExcelName, err), 3)
		}
	}()
	fileName := excelInfo.ExcelName + "_" + excelInfo.UniqueCode + ".xlsx"
	luckySheetData, err := excel.GetLuckySheetData(excelInfo.Content)
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	//_, err = luckySheetData.GetTableDataByLuckySheetDataStr()
	downloadFilePath, err := luckySheetData.ToExcel()
	defer func() {
		os.Remove(downloadFilePath)
	}()
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	//上传到阿里云
	resourceUrl, err := services.UploadAliyunV2(fileName, downloadFilePath)
	if err != nil {
		return
	}
	excelInfo.FileUrl = resourceUrl
	err = excelInfo.Update([]string{"FileUrl"})
}

//func init() {
//
//	excelInfo, err := data_manage.GetExcelInfoById(52)
//	if err != nil {
//		fmt.Println("err:", err)
//		return
//	}
//
//	luckySheetData, err := excel.GetLuckySheetData(excelInfo.Content)
//	if err != nil {
//		fmt.Println("err:", err)
//		return
//	}
//	//_, err = luckySheetData.GetTableDataByLuckySheetDataStr()
//	downloadFilePath, err := luckySheetData.ToExcel()
//	if err != nil {
//		fmt.Println("err:", err)
//		return
//	}
//	fmt.Println(downloadFilePath)
//
//	//fmt.Println(excel.GetColumnName(988, 283))
//}

// Calculate
// @Title 公式计算接口
// @Description 公式计算接口
// @Param	request	body request.CalculateReq true "type json string"
// @router /excel_info/table/calculate [post]
func (this *ExcelInfoController) Calculate() {
	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.CalculateReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.CalculateFormula == "" {
		br.Msg = "请填写公式"
		return
	}
	calculateFormula := req.CalculateFormula
	calculateFormula = strings.TrimPrefix(calculateFormula, "=")
	calculateFormula = strings.Replace(calculateFormula, "（", "(", -1)
	calculateFormula = strings.Replace(calculateFormula, "）", ")", -1)
	calculateFormula = strings.Replace(calculateFormula, "，", ",", -1)
	calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
	calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)

	formulaFormStr := utils.ReplaceFormula(req.TagMap, calculateFormula)
	//计算公式异常，那么就移除该指标
	if formulaFormStr == `` {
		//removeDateList = append(removeDateList, sk)
		//fmt.Println("异常了")
		br.Msg = "公式异常"
		br.ErrMsg = "公式异常"
		return
	}

	expression := formula.NewExpression(formulaFormStr)
	calResult, err := expression.Evaluate()
	if err != nil {
		br.Msg = "计算失败"
		br.ErrMsg = "计算失败：Err:" + err.Error() + ";formulaStr:" + formulaFormStr
		// 分母为0的报错
		if strings.Contains(err.Error(), "divide by zero") {
			br.Msg = "分母不能为0"
			br.ErrMsg = "分母不能为空，计算公式：" + formulaFormStr
			br.IsSendEmail = false
		}
		return
	}
	// 如果计算结果是NAN，那么就提示报错
	if calResult.IsNan() {
		br.Msg = "计算失败"
		br.ErrMsg = "计算失败：计算结果是:NAN;formulaStr:" + formulaFormStr
		return
	}
	// 计算结果格式化
	calFloat, e := calResult.Float64()
	if e != nil {
		br.Msg = "计算失败"
		br.ErrMsg = "计算失败, Err: " + e.Error()
		return
	}
	calVal := utils.FormatTableDataShowValue(calFloat)

	//calVal := calResult.String()
	//if err != nil {
	//	br.Msg = "计算失败"
	//	br.ErrMsg = "计算失败，结果转 string 失败：Err:" + err.Error() + ";formulaStr:" + formulaFormStr
	//	return
	//}

	br.Ret = 200
	br.Success = true
	br.Msg = "计算成功"
	br.Data = calVal
}

// GetFirstEdbData
// @Title 获取未来日期数据接口
// @Description 获取未来日期数据接口
// @Param   EdbInfoId   query   int  true       "指标id"
// @Param   Num   query   int  true       "默认期数"
// @router /excel_info/table/first_edb_data_list [get]
func (this *ExcelInfoController) GetFirstEdbData() {
	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
	}

	edbInfoId, _ := this.GetInt("EdbInfoId")
	num, _ := this.GetInt("Num")

	if edbInfoId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if num <= 0 {
		br.Msg = "期数必须大于0"
		br.IsSendEmail = false
		return
	}

	edbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取指标信息失败,Err:", err.Error())
		return
	}

	dataList, err := data.GetFirstEdbDataList(edbInfo, num, []string{})
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取失败,Err:", err.Error())
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = response.TableDataItem{
		EdbInfoId: edbInfoId,
		Data:      dataList,
	}
}

// GetOtherEdbData
// @Title 获取指定日期数据接口
// @Description 获取未来日期数据接口
// @Param	request	body request.GetOtherEdbDateDataReq true "type json string"
// @router /excel_info/table/other_edb_data_list [post]
func (this *ExcelInfoController) GetOtherEdbData() {
	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.GetOtherEdbDateDataReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.EdbInfoId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if len(req.DateList) <= 0 {
		br.Msg = "请选择日期"
		br.IsSendEmail = false
		return
	}

	edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取指标信息失败,Err:", err.Error())
		return
	}
	dataList, err := data.GetOtherEdbDataList(edbInfo, req.DateList)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取失败,Err:", err.Error())
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = response.TableDataItem{
		EdbInfoId: req.EdbInfoId,
		Data:      dataList,
	}
}

// GetFutureDateData
// @Title 获取未来日期数据接口
// @Description 获取未来日期数据接口
// @Param	request	body request.GetFutureDateDataReq true "type json string"
// @router /excel_info/table/future_date_list [post]
func (this *ExcelInfoController) GetFutureDateData() {
	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.GetFutureDateDataReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.StartDate == `` {
		br.Msg = "开始日期未传"
		br.IsSendEmail = false
		return
	}
	startDate, err := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
	if err != nil {
		br.Msg = "开始日期异常"
		br.ErrMsg = fmt.Sprint("开始日期异常,startDate:", req.StartDate, ";err:", err.Error())
		return
	}
	if len(req.EdbInfoIdList) <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	baseEdbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoIdList[0])
	if err != nil {
		br.Msg = "查找指标失败"
		br.Msg = "查找指标失败,err:" + err.Error()
		return
	}

	// 第一个指标的数据列表
	var firstEdbDataList []*data_manage.EdbDataList
	{
		switch baseEdbInfo.EdbInfoType {
		case 0:
			firstEdbDataList, err = data_manage.GetEdbDataList(baseEdbInfo.Source, baseEdbInfo.EdbInfoId, req.StartDate, ``)
		case 1:
			_, firstEdbDataList, _, _, err, _ = data.GetPredictDataListByPredictEdbInfoId(baseEdbInfo.EdbInfoId, req.StartDate, ``, false)
		default:
			br.Msg = "指标类型异常"
			br.ErrMsg = fmt.Sprint("获取失败,指标类型异常", baseEdbInfo.EdbInfoType)
			br.IsSendEmail = false
			return
		}
	}
	dateList := make([]time.Time, 0)
	if req.DateType == 1 {
		num := req.Num

		i := 0 // 数据中有的日期数
		for _, v := range firstEdbDataList {
			tmpDate, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
			if err != nil {
				br.Msg = "结束日期异常"
				br.ErrMsg = fmt.Sprint("结束日期异常,startDate:", req.EndDate, ";err:", err.Error())
				return
			}
			if tmpDate.After(startDate) {
				dateList = append(dateList, tmpDate)
				startDate = tmpDate
				i++
			}
			if i >= num {
				break
			}
		}
		num = num - i
		if num > 0 {
			tmpDateList := utils.GetPredictEdbDayListByNum(startDate, num, baseEdbInfo.Frequency)
			dateList = append(dateList, tmpDateList...)
		}
	} else {
		if req.EndDate == `` {
			br.Msg = "结束日期未传"
			br.IsSendEmail = false
			return
		}
		endDate, err := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
		if err != nil {
			br.Msg = "结束日期异常"
			br.ErrMsg = fmt.Sprint("结束日期异常,startDate:", req.EndDate, ";err:", err.Error())
			return
		}
		for _, v := range firstEdbDataList {
			tmpDate, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
			if err != nil {
				br.Msg = "结束日期异常"
				br.ErrMsg = fmt.Sprint("结束日期异常,startDate:", req.EndDate, ";err:", err.Error())
				return
			}
			if tmpDate.Equal(endDate) || (tmpDate.Before(endDate) && tmpDate.After(startDate)) {
				dateList = append(dateList, tmpDate)
				startDate = tmpDate
			}
		}
		if startDate.Before(endDate) {
			tmpDateList := utils.GetPredictEdbDayListByEndDate(startDate, endDate, baseEdbInfo.Frequency)
			dateList = append(dateList, tmpDateList...)
		}
	}

	// 获取所有的指标信息
	edbInfoMap := make(map[int]*data_manage.EdbInfo)
	{
		edbInfoList, err := data_manage.GetEdbInfoByIdList(req.EdbInfoIdList)
		if err != nil {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = "获取指标信息失败,err:" + err.Error()
			return
		}
		for _, v := range edbInfoList {
			edbInfoMap[v.EdbInfoId] = v
		}
	}

	result := make([]response.TableDataItem, 0)
	dateStrList := make([]string, 0)
	lenDate := len(dateList)
	if lenDate > 0 {
		for i := lenDate - 1; i >= 0; i-- {
			dateStrList = append(dateStrList, dateList[i].Format(utils.FormatDate))
		}
		for _, v := range req.EdbInfoIdList {
			tmpEdbInfo, ok := edbInfoMap[v]
			if !ok {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标信息失败,err:" + err.Error()
				return
			}

			dataList, err := data.GetOtherEdbDataList(tmpEdbInfo, dateStrList)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = fmt.Sprint("获取失败,Err:", err.Error())
				return
			}
			result = append(result, response.TableDataItem{
				EdbInfoId: v,
				Data:      dataList,
			})
		}
	}

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

// GetHistoryDateData
// @Title 获取历史日期数据接口
// @Description 获取历史日期数据接口
// @Param	request	body request.GetFutureDateDataReq true "type json string"
// @router /excel_info/table/history_date_list [post]
func (this *ExcelInfoController) GetHistoryDateData() {
	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.GetHistoryDateDataReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.EndDate == `` {
		br.Msg = "结束日期未传"
		br.IsSendEmail = false
		return
	}
	if len(req.EdbInfoIdList) <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	// 获取所有的指标信息
	edbInfoMap := make(map[int]*data_manage.EdbInfo)
	{
		edbInfoList, err := data_manage.GetEdbInfoByIdList(req.EdbInfoIdList)
		if err != nil {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = "获取指标信息失败,err:" + err.Error()
			return
		}
		for _, v := range edbInfoList {
			edbInfoMap[v.EdbInfoId] = v
		}
	}

	result := make([]response.TableDataItem, 0)
	dateStrList := make([]string, 0)

	// 获取A列指标的历史数据
	{
		tmpEdbInfo, ok := edbInfoMap[req.EdbInfoIdList[0]]
		if !ok {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = "获取指标信息失败,err:" + err.Error()
			return
		}
		firstDataList, err := data.GetFirstHistoryEdbDataList(tmpEdbInfo, req.Num, req.EndDate)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = fmt.Sprint("获取失败,Err:", err.Error())
			return
		}

		result = append(result, response.TableDataItem{
			EdbInfoId: req.EdbInfoIdList[0],
			Data:      firstDataList,
		})

		for _, v := range firstDataList {
			dateStrList = append(dateStrList, v.DataTime)
		}
	}

	if len(dateStrList) > 0 {
		for k, v := range req.EdbInfoIdList {
			if k == 0 {
				continue
			}
			tmpEdbInfo, ok := edbInfoMap[v]
			if !ok {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标信息失败,err:" + err.Error()
				return
			}

			dataList, err := data.GetOtherEdbDataList(tmpEdbInfo, dateStrList)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = fmt.Sprint("获取失败,Err:", err.Error())
				return
			}
			result = append(result, response.TableDataItem{
				EdbInfoId: v,
				Data:      dataList,
			})
		}
	}

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

// Refresh
// @Title 刷新
// @Description 刷新接口
// @Param   ExcelInfoId   query   int  true       "表格id"
// @router /excel_info/table/refresh [get]
func (this *ExcelInfoController) Refresh() {
	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
	}

	excelInfoId, _ := this.GetInt("ExcelInfoId")
	if excelInfoId <= 0 {
		br.Msg = "请选择表格"
		br.ErrMsg = "ExcelInfoId未传"
		br.IsSendEmail = false
		return
	}

	// 获取数据详情
	excelDetail, errMsg, err := data.GetExcelDetailInfoByExcelInfoId(excelInfoId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = err.Error()
		return
	}

	// 操作权限校验
	{
		button := data.GetExcelInfoOpButton(sysUser, excelDetail.SysUserId, excelDetail.Source)
		if !button.RefreshButton {
			br.Msg = "无操作权限"
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}

	// 数据刷新（只有自定义表格有刷新）
	if excelDetail.Source == 2 {
		jsonStrByte, err := json.Marshal(excelDetail.TableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,转json失败，Err:" + err.Error()
			return
		}
		var tableData request.TableDataReq
		err = json.Unmarshal(jsonStrByte, &tableData)
		if err != nil {
			br.Msg = "自定义表格数据获取失败"
			br.ErrMsg = "自定义表格数据获取失败,json转结构体失败，Err:" + err.Error()
			return
		}

		if len(tableData.EdbInfoIdList) > 0 {
			err = data.EdbInfoRefreshAllFromBaseV3(tableData.EdbInfoIdList, false)
			if err != nil {
				br.Msg = "刷新失败"
				br.ErrMsg = "刷新失败,Err:" + err.Error()
				return
			}
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

// Download
// @Title 获取表格详情
// @Description 获取表格详情接口
// @Param   UniqueCode   query   string  true       "表格code"
// @Param   ExcelInfoId   query   int  true       "表格id"
// @Success 200 {object} data_manage.ExcelInfo
// @router /excel_info/table/download [get]
func (this *ExcelInfoController) Download() {
	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
	}

	excelInfoId, _ := this.GetInt("ExcelInfoId")
	uniqueCode := this.GetString("UniqueCode")
	if excelInfoId <= 0 && uniqueCode == `` {
		br.Msg = "请选择表格"
		br.ErrMsg = "ExcelInfoId和UniqueCode都未传"
		br.IsSendEmail = false
		return
	}
	var excelInfo *data_manage.ExcelInfo
	var err error
	//获取eta表格信息
	if excelInfoId > 0 {
		excelInfo, err = data_manage.GetExcelInfoById(excelInfoId)
	} else {
		excelInfo, err = data_manage.GetExcelInfoByUniqueCode(uniqueCode)
	}
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取ETA表格信息失败，Err:" + err.Error()
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "ETA表格被删除，请刷新页面"
			br.ErrMsg = "ETA表格被删除，请刷新页面，Err:" + err.Error()
			br.IsSendEmail = false
		}
		return
	}

	if excelInfo.Source == 1 {
		br.Msg = "不是自定义表格"
		br.IsSendEmail = false
		return
	}

	var tableData excel.TableData
	switch excelInfo.Source {
	case 1:
		br.Msg = "表格类型异常"
	case 2: // 自定义表格
		var tableDataConfig data.TableDataConfig
		err = json.Unmarshal([]byte(excelInfo.Content), &tableDataConfig)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "表格json转结构体失败，Err:" + err.Error()
			return
		}
		result, err := data.GetDataByTableDataConfig(tableDataConfig)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取最新的表格数据失败，Err:" + err.Error()
			return
		}
		tableData, err = excel.GetTableDataByCustomData(excelInfo.ExcelType, result)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "转换成table失败，Err:" + err.Error()
			return
		}
	case 3: // 混合表格
		var result request.MixedTableReq
		err = json.Unmarshal([]byte(excelInfo.Content), &result)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "表格json转结构体失败，Err:" + err.Error()
			return
		}
		newResult, tmpErr := data.GetMixedTableCellData(result.Data)
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取最新的数据失败，Err:" + err.Error()
			return
		}
		tableData, err = excel.GetTableDataByMixedTableData(newResult)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "转换成table失败，Err:" + err.Error()
			return
		}
	}

	downloadFilePath, err := tableData.ToExcel()
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	defer func() {
		os.Remove(downloadFilePath)
	}()

	downloadFileName := excelInfo.ExcelName + ".xlsx"
	this.Ctx.Output.Download(downloadFilePath, downloadFileName)

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

// Copy
// @Title 复制表格
// @Description 复制表格接口
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/copy [post]
func (this *ExcelInfoController) Copy() {
	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
	}

	deleteCache := true
	var req request.CopyExcelInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ExcelInfoId <= 0 {
		br.Msg = "请传入ETA表格标识！"
		return
	}

	cacheKey := "CACHE_TABLE_INFO_EDIT_" + strconv.Itoa(req.ExcelInfoId)
	defer func() {
		if deleteCache {
			_ = utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	req.ExcelName = strings.Trim(req.ExcelName, " ")
	if req.ExcelName == "" {
		br.Msg = "请填写表格名称！"
		br.IsSendEmail = false
		return
	}

	if req.ExcelClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		br.IsSendEmail = false
		return
	}

	excelClassify, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			br.IsSendEmail = false
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if excelClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		br.IsSendEmail = false
		return
	}

	// 获取原ETA表格信息
	oldExcelInfo, err := data_manage.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}

	// 操作权限校验
	{
		button := data.GetExcelInfoOpButton(sysUser, oldExcelInfo.SysUserId, oldExcelInfo.Source)
		if !button.CopyButton {
			br.Msg = "无操作权限"
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}

	// 检验分类下是否存在该表格名称
	{
		var condition string
		var pars []interface{}
		condition += " AND excel_classify_id=? "
		pars = append(pars, req.ExcelClassifyId)

		condition += " AND excel_name=? "
		pars = append(pars, req.ExcelName)

		count, err := data_manage.GetExcelInfoCountByCondition(condition, pars)
		if err != nil {
			br.Msg = "判断表格名称是否存在失败"
			br.ErrMsg = "判断表格名称是否存在失败,Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "表格名称已存在，请重新填写表格名称"
			br.IsSendEmail = false
			return
		}
	}

	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	excelInfo := &data_manage.ExcelInfo{
		//ExcelInfoId:     0,
		ExcelName:       req.ExcelName,
		Source:          oldExcelInfo.Source,
		ExcelType:       oldExcelInfo.ExcelType,
		UniqueCode:      utils.MD5(utils.EXCEL_DATA_PREFIX + "_" + timestamp),
		ExcelClassifyId: req.ExcelClassifyId,
		SysUserId:       sysUser.AdminId,
		SysUserRealName: sysUser.RealName,
		Content:         oldExcelInfo.Content,
		ExcelImage:      oldExcelInfo.ExcelImage,
		Sort:            0,
		IsDelete:        0,
		ModifyTime:      time.Now(),
		CreateTime:      time.Now(),
	}

	err = data_manage.AddExcelInfo(excelInfo)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	// 更新excel下载地址(默认的EXCEL需要更新，自定义表格不需要更新）
	if excelInfo.Source == 1 {
		go UpdateExcelInfoFileUrl(excelInfo)
	}

	resp := new(response.AddExcelInfoResp)
	resp.ExcelInfoId = excelInfo.ExcelInfoId
	resp.UniqueCode = excelInfo.UniqueCode

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

//func init() {
//	//list, err := data.GetFirstEdbDataList(102739, 12)
//	list, err := data.GetFirstEdbDataList(101323, 12)
//	if err != nil {
//		fmt.Println(err)
//		return
//	}
//
//	fmt.Println("START")
//	dateList := make([]string, 0)
//	for _, v := range list {
//		fmt.Println(v)
//		dateList = append(dateList, v.DataTime)
//	}
//
//	fmt.Println("End")
//
//	{
//		list, err := data.GetOtherEdbDataList(102227, dateList)
//		if err != nil {
//			fmt.Println(err)
//			return
//		}
//
//		for _, v := range list {
//			fmt.Println(v)
//		}
//	}
//}

//func init() {
//	str := `{"EdbInfoIdList":[101323,102227],"Sort":1,"Data":[{"EdbInfoId":101323,"Tag":"A","Data":[{"DataType":4,"DataTime":"2023-06-10","DataTimeType":4,"ShowValue":"318.2726","Value":"=A2-B2","RelationEdbInfoList":[{"Tag":"A","Row":"2"},{"Tag":"B","Row":"2"}]},{"DataType":3,"DataTime":"2023-06-09","DataTimeType":2,"ShowValue":"15","Value":"15","RelationEdbInfoList":[]},{"DataType":1,"DataTime":"2023-06-07","DataTimeType":1,"ShowValue":"16.43","Value":"16.43","RelationEdbInfoList":[]},{"DataType":1,"DataTime":"2023-06-05","DataTimeType":1,"ShowValue":"16.85","Value":"16.85","RelationEdbInfoList":[]},{"DataType":1,"DataTime":"2023-06-02","DataTimeType":1,"ShowValue":"15.88","Value":"15.88","RelationEdbInfoList":[]}]},{"EdbInfoId":102227,"Tag":"B","Data":[{"DataType":4,"DataTime":"2023-06-10","DataTimeType":1,"ShowValue":"318.2726","Value":"=A2+B2","RelationEdbInfoList":[{"Tag":"A","Row":"2"},{"Tag":"B","Row":"2"}]},{"DataType":1,"DataTime":"2023-06-09","DataTimeType":1,"ShowValue":"318.2726","Value":"318.2726","RelationEdbInfoList":[]},{"DataType":2,"DataTime":"2023-06-07","DataTimeType":1,"ShowValue":"100.43","Value":"100.43","RelationEdbInfoList":[]},{"DataType":2,"DataTime":"2023-06-05","DataTimeType":1,"ShowValue":"102.85","Value":"102.85","RelationEdbInfoList":[]},{"DataType":1,"DataTime":"2023-06-02","DataTimeType":1,"ShowValue":"311.5201","Value":"311.5201","RelationEdbInfoList":[]}]}],"TextRowData":[[{"DataType":3,"DataTime":"","ShowValue":"总计","Value":"总计"},{"DataType":4,"DataTime":"","ShowValue":"0","Value":"=A3+B3","RelationEdbInfoList":[{"Tag":"A","Row":"3"},{"Tag":"B","Row":"3"}]},{"DataType":3,"DataTime":"","ShowValue":"","Value":"","RelationEdbInfoList":[]}],[{"DataType":3,"DataTime":"","ShowValue":"垃圾汇总","Value":"垃圾汇总"},{"DataType":4,"DataTime":"","ShowValue":"0","Value":"=A4+B4","RelationEdbInfoList":[{"Tag":"A","Row":"4"},{"Tag":"B","Row":"4"}]},{"DataType":3,"DataTime":"","ShowValue":"这里是文本文案","Value":"这里是文本文案","RelationEdbInfoList":[]}]]}`
//	str = `{"EdbInfoIdList":[102942,102938,102937],"Sort":1,"Data":[],"Num":12,"RemoveDate":["2023-06-05","2023-06-08"],"ManualDate":null,"TableEdbInfoList":[{"EdbInfoId":102942,"Tag":"A","EdbName":"","EdbAliasName":"","Frequency":"","Unit":""},{"EdbInfoId":102938,"Tag":"B","EdbName":"","EdbAliasName":"","Frequency":"","Unit":""},{"EdbInfoId":102937,"Tag":"C","EdbName":"","EdbAliasName":"","Frequency":"","Unit":""}],"TextRowData":[[{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"dwd","Value":"dwd","RelationEdbInfoList":[]},{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"4454","Value":"4454","RelationEdbInfoList":[]},{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"454","Value":"454","RelationEdbInfoList":[]},{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"51","Value":"51","RelationEdbInfoList":[]}],[{"DataType":4,"DataTime":"","DataTimeType":0,"ShowValue":"a1b1","Value":"=a1+b1","RelationEdbInfoList":[{"Tag":"A","Row":"1"},{"Tag":"B","Row":"1"}]},{"DataType":4,"DataTime":"","DataTimeType":0,"ShowValue":"2247.1444","Value":"=a2+b2","RelationEdbInfoList":[{"Tag":"A","Row":"2"},{"Tag":"B","Row":"2"}]},{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"","Value":"","RelationEdbInfoList":[]},{"DataType":3,"DataTime":"","DataTimeType":0,"ShowValue":"","Value":"","RelationEdbInfoList":[]}]]}`
//
//	//var req request.TableDataReq
//	//err := json.Unmarshal([]byte(str), &req)
//	//if err != nil {
//	//	fmt.Println(err)
//	//	return
//	//}
//	//tableDataConfig, err := data.GetTableDataConfig(req)
//	//if err != nil {
//	//	fmt.Println(err)
//	//	return
//	//}
//	var tableDataConfig data.TableDataConfig
//	err := json.Unmarshal([]byte(str), &tableDataConfig)
//	if err != nil {
//		fmt.Println(err)
//		return
//	}
//
//	fmt.Println(tableDataConfig)
//
//	result, err := data.GetDataByTableDataConfig(tableDataConfig)
//	if err != nil {
//		fmt.Println(err)
//		return
//	}
//	fmt.Println(result)
//	//byteStr, _ := json.Marshal(result)
//	//utils.FileLog.Info(string(byteStr))
//}
