package excel

import (
	"archive/zip"
	"encoding/json"
	"errors"
	"eta_gn/eta_api/models"
	"eta_gn/eta_api/models/data_manage"
	"eta_gn/eta_api/models/data_manage/excel"
	"eta_gn/eta_api/models/data_manage/excel/request"
	"eta_gn/eta_api/models/data_manage/excel/response"
	"eta_gn/eta_api/models/system"
	"eta_gn/eta_api/services/data"
	"eta_gn/eta_api/services/data/data_manage_permission"
	excelService "eta_gn/eta_api/services/data/excel"
	excel2 "eta_gn/eta_api/services/excel"
	"eta_gn/eta_api/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"io/ioutil"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"
)

// GetChildTable
// @Title 获取子表
// @Description 获取子表
// @Param	request	body request.MixedTableCellDataReq true "type json string"
// @router /excel_info/child_table [get]
func (c *ExcelInfoController) GetChildTable() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	parentId, _ := c.GetInt("ParentId")
	if parentId <= 0 {
		br.Msg = "请选择父表"
		return
	}
	list := make([]*excel.ExcelInfo, 0)
	// 查询所有子表
	childList, err := excel.GetChildExcelInfoByParentId(parentId)
	if err != nil {
		br.Msg = "查询子表失败"
		return
	}
	if len(childList) > 0 {
		list = childList
	}

	resp := &response.BalanceChildTableResp{List: list}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = resp
}

// Rename
// @Title 表格重命名接口
// @Description 表格重命名接口
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/rename [post]
func (c *ExcelInfoController) Rename() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

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

	req.ExcelName = strings.Trim(req.ExcelName, " ")
	if req.ExcelName == "" {
		br.Msg = "请填写表格名称!"
		br.IsSendEmail = false
		return
	}

	excelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}
	//判断表格是否存在
	var condition string
	var pars []interface{}
	condition += " AND excel_info_id != ? AND excel_classify_id=? AND excel_name=?  AND parent_id=?"
	pars = append(pars, req.ExcelInfoId, excelInfo.ExcelClassifyId, req.ExcelName, excelInfo.ParentId)

	// 获取分类下是否存在该表格名称
	count, err := excel.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
	}

	// 操作权限校验, 增加协作人判断
	{
		checkExcelInfo := excelInfo
		if excelInfo.Source == utils.BALANCE_TABLE {
			checkExcelInfoId := excelInfo.ExcelInfoId
			if excelInfo.BalanceType == 1 {
				checkExcelInfoId = excelInfo.RelExcelInfoId
			} else {
				if excelInfo.ParentId > 0 {
					checkExcelInfoId = excelInfo.ParentId
				}
			}
			if checkExcelInfoId != excelInfo.ExcelInfoId {
				checkExcelInfo, err = excel.GetExcelInfoById(checkExcelInfoId)
				if err != nil {
					br.Msg = "获取平衡表格信息失败"
					br.ErrMsg = "获取平衡表格信息失败,Err:" + err.Error()
					return
				}
			}
		}
		// 数据权限
		haveOperaAuth, e := data_manage_permission.CheckExcelPermissionByExcelInfoId(checkExcelInfo.ExcelInfoId, checkExcelInfo.ExcelClassifyId, checkExcelInfo.IsJoinPermission, c.SysUser.AdminId)
		if e != nil {
			br.Msg = "获取ETA表格权限失败"
			br.ErrMsg = "获取表格权限信息失败,Err" + e.Error()
			return
		}

		button := excelService.GetBalanceExcelInfoOpButton(sysUser.AdminId, checkExcelInfo.SysUserId, haveOperaAuth, checkExcelInfo.ExcelInfoId)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}

	excelInfo.ModifyTime = time.Now()
	excelInfo.ExcelName = req.ExcelName
	excelInfo.UpdateUserId = sysUser.AdminId
	excelInfo.UpdateUserRealName = sysUser.RealName
	// 自动保存时不会传缩略图,也就不更新这个字段
	updateExcelInfoParams := []string{"ModifyTime", "ExcelName", "UpdateUserId", "UpdateUserRealName"}

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

	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
}

// SaveExcelWorker
// @Title 新增编辑表格协作人接口
// @Description 新增编辑表格协作人接口
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/worker/save [post]
func (c *ExcelInfoController) SaveExcelWorker() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

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

	excelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}
	if excelInfo.SysUserId != sysUser.AdminId {
		br.Msg = "您没有权限操作!"
		br.ErrMsg = "您没有权限操作!"
		return
	}
	// 操作权限校验, 增加协作人判断
	{
		// 数据权限
		haveOperaAuth, err := data_manage_permission.CheckExcelPermissionByExcelInfoId(excelInfo.ExcelInfoId, excelInfo.ExcelClassifyId, excelInfo.IsJoinPermission, c.SysUser.AdminId)
		if err != nil {
			br.Msg = "获取ETA表格失败"
			br.ErrMsg = "获取ETA表格权限失败,Err:" + err.Error()
			return
		}
		button := excelService.GetExcelInfoOpButton(sysUser, excelInfo.SysUserId, excelInfo.Source, haveOperaAuth)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}
	obj := new(excel.ExcelWorker)
	notDeleteWorkerIds := make([]string, 0)
	workerMap := make(map[int]struct{})
	if req.SysUserIds != "" {
		notDeleteWorkerIds = strings.Split(req.SysUserIds, ",")
	}
	existList, err := obj.GetByExcelInfoId(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取表格协作人失败!"
		br.ErrMsg = "获取表格协作人失败,Err:" + err.Error()
		return
	}
	for _, v := range existList {
		workerMap[v.SysUserId] = struct{}{}
	}
	addIds := make([]int, 0)
	for _, v := range notDeleteWorkerIds {
		id, _ := strconv.Atoi(v)
		if _, ok := workerMap[id]; !ok {
			addIds = append(addIds, id)
		}
	}
	// 查询协作人姓名
	adminList, err := system.GetAdminListByIdListWithoutEnable(addIds)
	addList := make([]*excel.ExcelWorker, 0)
	for _, v := range adminList {
		addList = append(addList, &excel.ExcelWorker{
			ExcelInfoId:     req.ExcelInfoId,
			SysUserId:       v.AdminId,
			SysUserRealName: v.RealName,
			CreateTime:      time.Now(),
			ModifyTime:      time.Now(),
		})
	}
	// 保存协作人
	err = obj.AddWorker(req.ExcelInfoId, addList, notDeleteWorkerIds)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// GetWorker
// @Title 查询协作人接口
// @Description 新增编辑表格协作人接口
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/worker [get]
func (c *ExcelInfoController) GetWorker() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

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

	obj := new(excel.ExcelWorker)

	list, err := obj.GetByExcelInfoId(excelInfoId)
	if err != nil {
		br.Msg = "获取表格协作人失败!"
		br.ErrMsg = "获取表格协作人失败,Err:" + err.Error()
		return
	}
	ret := &response.BalanceTableWorkerResp{List: list}
	br.Data = ret
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// BalanceChartInfoAdd
// @Title 新增图表接口
// @Description 新增图表接口
// @Param	request	body data_manage.AddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /excel_info/balance/chart_add [post]
func (c *ExcelInfoController) BalanceChartInfoAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	deleteCache := true
	cacheKey := "CACHE_EXCEL_CHART_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(c.Ctx.Input.RequestBody)
		return
	}
	var req request.AddBalanceTableChartReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	req.ChartName = strings.Trim(req.ChartName, " ")
	if req.ChartName == "" {
		br.Msg = "请填写图表名称!"
		return
	}
	// 获取表格信息
	excelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		return
	}

	if excelInfo.Source != utils.BALANCE_TABLE {
		br.Msg = "EXCEL类型错误!"
		return
	}
	// 操作权限校验, 增加协作人判断
	{
		checkExcelInfo := excelInfo
		if excelInfo.Source == utils.BALANCE_TABLE {
			checkExcelInfoId := excelInfo.ExcelInfoId
			if excelInfo.BalanceType == 1 {
				checkExcelInfoId = excelInfo.RelExcelInfoId
			} else {
				if excelInfo.ParentId > 0 {
					checkExcelInfoId = excelInfo.ParentId
				}
			}
			if checkExcelInfoId != excelInfo.ExcelInfoId {
				checkExcelInfo, err = excel.GetExcelInfoById(checkExcelInfoId)
				if err != nil {
					br.Msg = "获取平衡表格信息失败"
					br.ErrMsg = "获取平衡表格信息失败,Err:" + err.Error()
					return
				}
			}
		}
		// 数据权限
		haveOperaAuth, e := data_manage_permission.CheckExcelPermissionByExcelInfoId(checkExcelInfo.ExcelInfoId, checkExcelInfo.ExcelClassifyId, checkExcelInfo.IsJoinPermission, c.SysUser.AdminId)
		if e != nil {
			br.Msg = "获取ETA表格权限失败"
			br.ErrMsg = "获取表格权限信息失败,Err" + e.Error()
			return
		}

		button := excelService.GetBalanceExcelInfoOpButton(sysUser.AdminId, checkExcelInfo.SysUserId, haveOperaAuth, checkExcelInfo.ExcelInfoId)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}
	// 判断如果是静态表,则查询表数据,落库
	dataListMap := make(map[int][]*data_manage.EdbDataList)
	if excelInfo.BalanceType == 1 {
		newExcelDataMap, excelAllRows, excelAllCols, e, errMsg := excelService.GetBalanceExcelData(excelInfo, c.Lang)
		if e != nil {
			br.Msg = "获取表格数据失败"
			if errMsg != "" {
				br.Msg = errMsg
			}
			br.ErrMsg = "获取表格数据失败,Err:" + e.Error()
			return
		}

		for k, mapping := range req.ChartEdbInfoList {
			tmpMapping := &excel.ExcelChartEdb{
				ExcelChartEdbId: k,
				DateSequence:    mapping.DateSequenceStr,
				DataSequence:    mapping.DataSequenceStr,
			}
			er, msg := excelService.GetBalanceExcelEdbData(tmpMapping, newExcelDataMap, dataListMap, excelAllRows, excelAllCols)
			if er != nil {
				utils.FileLog.Info(fmt.Sprintf(" 获取图表,指标信息失败 Err:%s, %s", msg, er.Error()))
				continue
			}
		}
	}
	chartInfo, err, errMsg, isSendEmail := data.AddBalanceExcelChart(excelInfo, req, sysUser, dataListMap)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		br.IsSendEmail = isSendEmail
		return
	}
	resp := new(data_manage.AddChartInfoResp)
	resp.ChartInfoId = chartInfo.ChartInfoId
	resp.UniqueCode = chartInfo.UniqueCode
	resp.ChartType = req.ChartType

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartInfoId = chartInfo.ChartInfoId
		chartLog.ChartName = req.ChartName
		chartLog.ChartClassifyId = 0
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartInfo.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(c.Ctx.Input.RequestBody)
		chartLog.Status = "新增图表"
		chartLog.Method = c.Ctx.Input.URI()
		go data_manage.AddChartInfoLog(chartLog)
	}

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

// BalanceChartInfoEdit
// @Title 编辑图表接口
// @Description 新增图表接口
// @Param	request	body data_manage.AddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /excel_info/balance/chart_edit [post]
func (c *ExcelInfoController) BalanceChartInfoEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	deleteCache := true
	cacheKey := "CACHE_EXCEL_CHART_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(c.Ctx.Input.RequestBody)
		return
	}
	var req request.AddBalanceTableChartReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	req.ChartName = strings.Trim(req.ChartName, " ")
	if req.ChartName == "" {
		br.Msg = "请填写图表名称!"
		return
	}
	if req.ChartInfoId <= 0 {
		br.Msg = "请选择图表"
		return
	}
	// 获取表格信息
	excelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		return
	}

	if excelInfo.Source != utils.BALANCE_TABLE {
		br.Msg = "EXCEL类型错误!"
		return
	}
	// 操作权限校验, 增加协作人判断
	{
		checkExcelInfo := excelInfo
		if excelInfo.Source == utils.BALANCE_TABLE {
			checkExcelInfoId := excelInfo.ExcelInfoId
			if excelInfo.BalanceType == 1 {
				checkExcelInfoId = excelInfo.RelExcelInfoId
			} else {
				if excelInfo.ParentId > 0 {
					checkExcelInfoId = excelInfo.ParentId
				}
			}
			if checkExcelInfoId != excelInfo.ExcelInfoId {
				checkExcelInfo, err = excel.GetExcelInfoById(checkExcelInfoId)
				if err != nil {
					br.Msg = "获取平衡表格信息失败"
					br.ErrMsg = "获取平衡表格信息失败,Err:" + err.Error()
					return
				}
			}
		}
		// 数据权限
		haveOperaAuth, e := data_manage_permission.CheckExcelPermissionByExcelInfoId(checkExcelInfo.ExcelInfoId, checkExcelInfo.ExcelClassifyId, checkExcelInfo.IsJoinPermission, c.SysUser.AdminId)
		if e != nil {
			br.Msg = "获取ETA表格权限失败"
			br.ErrMsg = "获取表格权限信息失败,Err" + e.Error()
			return
		}

		button := excelService.GetBalanceExcelInfoOpButton(sysUser.AdminId, checkExcelInfo.SysUserId, haveOperaAuth, checkExcelInfo.ExcelInfoId)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}
	// 判断如果是静态表,则查询表数据,落库
	dataListMap := make(map[int][]*data_manage.EdbDataList)
	if excelInfo.BalanceType == 1 {
		newExcelDataMap, excelAllRows, excelAllCols, e, errMsg := excelService.GetBalanceExcelData(excelInfo, c.Lang)
		if e != nil {
			br.Msg = "获取表格数据失败"
			if errMsg != "" {
				br.Msg = errMsg
			}
			br.ErrMsg = "获取表格数据失败,Err:" + e.Error()
			return
		}

		for k, mapping := range req.ChartEdbInfoList {
			tmpMapping := &excel.ExcelChartEdb{
				ExcelChartEdbId: k,
				DateSequence:    mapping.DateSequenceStr,
				DataSequence:    mapping.DataSequenceStr,
			}
			er, msg := excelService.GetBalanceExcelEdbData(tmpMapping, newExcelDataMap, dataListMap, excelAllRows, excelAllCols)
			if er != nil {
				utils.FileLog.Info(fmt.Sprintf(" 获取图表,指标信息失败 Err:%s, %s", msg, er.Error()))
				continue
			}
		}
	}
	chartItem, err, errMsg, isSendEmail := data.EditBalanceExcelChart(excelInfo, req, sysUser, dataListMap)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	resp := new(data_manage.AddChartInfoResp)
	resp.ChartInfoId = chartItem.ChartInfoId
	resp.UniqueCode = chartItem.UniqueCode
	resp.ChartType = req.ChartType

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(c.Ctx.Input.RequestBody)
		chartLog.Status = "编辑图表"
		chartLog.Method = c.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}

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

// GetBalanceChartList
// @Title 获取平衡表表关联的图表
// @Description 获取平衡表表关联的图表
// @Param	request	body request.MixedTableCellDataReq true "type json string"
// @router /excel_info/balance/chart_list [get]
func (c *ExcelInfoController) GetBalanceChartList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	excelInfoId, _ := c.GetInt("ExcelInfoId")
	if excelInfoId <= 0 {
		br.Msg = "请选择平衡表"
		return
	}
	// 查询所有子表
	excelInfo, err := excel.GetExcelInfoById(excelInfoId)
	if err != nil {
		if utils.IsErrNoRow(err) {
			br.Msg = "表格不存在"
			return
		}
		br.Msg = "查询子表失败"
		br.ErrMsg = "查询子表失败,Err:" + err.Error()
		return
	}
	list := make([]*data_manage.BalanceChartInfoDetailResp, 0)
	chartInfoList, mappingListMap, dataListMap, err, errMsg := excelService.GetBalanceExcelChartList(excelInfo, "")
	if err != nil {
		if errMsg != "" {
			br.Msg = errMsg
			br.ErrMsg = err.Error()
			return
		} else {
			br.Msg = "查询图表失败"
			br.ErrMsg = "查询图表失败,Err:" + err.Error()
		}
		return
	}
	for _, chartInfo := range chartInfoList {
		mappingList, ok := mappingListMap[chartInfo.ChartInfoId]
		if !ok {
			br.Msg = "未找到图表关联的指标信息"
			return
		}
		var chartInfoResp *data_manage.ChartInfoDetailResp
		chartInfoResp, err, errMsg = data.GetBalanceExcelChartDetail(chartInfo, mappingList, sysUser, dataListMap)
		if err != nil {
			br.Msg = "查询图表详情失败"
			br.ErrMsg = "查询图表详情失败,Err:" + err.Error()
			return
		}
		chartEdbList := make([]*data_manage.ExcelChartEdbView, 0)
		for _, v := range mappingList {
			tmp := &data_manage.ExcelChartEdbView{
				ExcelChartEdbId: v.ExcelChartEdbId,
				DateSequenceStr: v.DateSequence,
				DataSequenceStr: v.DataSequence,
				FromTag:         v.FromTag,
			}
			chartEdbList = append(chartEdbList, tmp)
		}

		balanceChartInfoResp := &data_manage.BalanceChartInfoDetailResp{
			ChartInfoDetailResp: chartInfoResp,
			ExcelEdbList:        chartEdbList,
		}
		list = append(list, balanceChartInfoResp)
	}

	ret := &data_manage.BalanceTableChartListResp{List: list}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = ret
}

// DeleteBalanceChart
// @Title 删除平衡表图表
// @Description 删除平衡表图表
// @Param	request	body data_manage.DeleteChartClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /excel_info/balance/chart_del [post]
func (c *ExcelInfoController) DeleteBalanceChart() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

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

	if req.ChartInfoId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}
	//删除图表
	if req.ChartInfoId > 0 {
		chartInfo, err := data_manage.GetChartInfoById(req.ChartInfoId)
		if err != nil {
			if utils.IsErrNoRow(err) {
				br.Msg = "图表已删除,请刷新页面"
				br.ErrMsg = "指标不存在,Err:" + err.Error()
				return
			} else {
				br.Msg = "删除失败"
				br.ErrMsg = "删除失败,获取指标信息失败,Err:" + err.Error()
				return
			}
		}
		if chartInfo == nil {
			br.Msg = "图表已删除,请刷新页面"
			return
		}

		// 操作权限校验, 增加协作人判断
		{
			// 获取表格信息
			excelInfo, e := excel.GetExcelInfoByChartInfoId(req.ChartInfoId)
			if e != nil {
				br.Msg = "获取ETA表格失败"
				return
			}
			checkExcelInfo := excelInfo
			if excelInfo.Source == utils.BALANCE_TABLE {
				checkExcelInfoId := excelInfo.ExcelInfoId
				if excelInfo.BalanceType == 1 {
					checkExcelInfoId = excelInfo.RelExcelInfoId
				} else {
					if excelInfo.ParentId > 0 {
						checkExcelInfoId = excelInfo.ParentId
					}
				}
				if checkExcelInfoId != excelInfo.ExcelInfoId {
					checkExcelInfo, e = excel.GetExcelInfoById(checkExcelInfoId)
					if e != nil {
						br.Msg = "获取平衡表格信息失败"
						br.ErrMsg = "获取平衡表格信息失败,Err:" + e.Error()
						return
					}
				}
			}
			// 数据权限
			haveOperaAuth, e := data_manage_permission.CheckExcelPermissionByExcelInfoId(checkExcelInfo.ExcelInfoId, checkExcelInfo.ExcelClassifyId, checkExcelInfo.IsJoinPermission, c.SysUser.AdminId)
			if e != nil {
				br.Msg = "获取ETA表格权限失败"
				br.ErrMsg = "获取表格权限信息失败,Err" + e.Error()
				return
			}

			button := excelService.GetBalanceExcelInfoOpButton(sysUser.AdminId, checkExcelInfo.SysUserId, haveOperaAuth, checkExcelInfo.ExcelInfoId)
			if !button.OpButton {
				br.Msg = "无操作权限"
				br.IsSendEmail = false
				return
			}
		}

		// 获取引用该图表的MyCharts, 用于ES删除
		var myCond string
		var myPars []interface{}
		myCond += ` AND a.chart_info_id = ? `
		myPars = append(myPars, req.ChartInfoId)
		myCharts, e := data_manage.GetMyChartListGroupByCharyInfoIdAndAdminIdByCondition(myCond, myPars)
		if e != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "获取引用图表的MyChats失败, Err: " + e.Error()
			return
		}
		myIds := make([]int, 0)
		for _, m := range myCharts {
			myIds = append(myIds, m.MyChartId)
		}

		//删除图表及关联指标
		e = excel.DeleteBalanceExcelChartInfoAndData(req.ChartInfoId)
		if e != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败,Err:" + e.Error()
			return
		}
		//删除ES
		{
			go data.DeleteChartInfoToEs(req.ChartInfoId)
			// 删除MY ETA 图表 es数据
			//go data.EsDeleteMyChartInfoByChartInfoId(req.ChartInfoId)
			go data.EsDeleteMyChartInfoByMyChartIds(myIds)
		}

		//新增操作日志
		{
			chartLog := new(data_manage.ChartInfoLog)
			chartLog.ChartName = chartInfo.ChartName
			chartLog.ChartInfoId = req.ChartInfoId
			chartLog.ChartClassifyId = chartInfo.ChartClassifyId
			chartLog.SysUserId = sysUser.AdminId
			chartLog.SysUserRealName = sysUser.RealName
			chartLog.UniqueCode = chartInfo.UniqueCode
			chartLog.CreateTime = time.Now()
			chartLog.Content = string(c.Ctx.Input.RequestBody)
			chartLog.Status = "删除图表"
			chartLog.Method = c.Ctx.Input.URI()
			go data_manage.AddChartInfoLog(chartLog)
		}
	}
	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// BalanceSeasonChartLegendPreview
// @Title 季节性图例预览接口
// @Description 季节性图例预览接口
// @Param	request	body request.BalanceSeasonChartLegendPreviewReq true "type json string"
// @Success 200 {object} data_manage.BalanceSeasonChartLegendPreviewResp
// @router /excel_info/balance/chartLegend/preview [post]
func (c *ExcelInfoController) BalanceSeasonChartLegendPreview() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

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

	if len(req.DateArr) == 0 || len(req.DateArr) == 0 || len(req.DateArr) != len(req.DataArr) {
		br.Msg = "请输入正确的日期和数据"
		return
	}
	newDataMap := make(map[int]float64)
	for i, v := range req.DataArr {
		fv, e := strconv.ParseFloat(v, 64)
		if e != nil {
			br.Msg = "数据格式错误"
			return
		}
		newDataMap[i] = fv
	}
	//组装成excelEdbData
	dataList := make([]*data_manage.EdbDataList, 0)

	for i, v := range req.DateArr {
		dataTime, e := time.ParseInLocation(utils.FormatDate, v, time.Local)
		if e != nil {
			br.Msg = "日期格式错误"
			br.ErrMsg = v + "日期格式错误,Err:" + e.Error()
			return
		}
		timestamp := dataTime.UnixNano() / 1e6
		tmp := &data_manage.EdbDataList{
			EdbDataId:     i,
			DataTime:      v,
			DataTimestamp: timestamp,
			Value:         newDataMap[i],
		}
		dataList = append(dataList, tmp)
	}

	// 对dataList 根据dataTimestamp 进行排序
	sort.Slice(dataList, func(i, j int) bool {
		return dataList[i].DataTimestamp < dataList[j].DataTimestamp
	})

	list, err, errMsg := data.GetBalanceExcelSeasonChartLegendPreview(dataList, req.Calendar, req.SeasonExtraConfig)
	if err != nil {
		if errMsg != "" {
			br.Msg = errMsg
		} else {
			br.Msg = "预览失败"
		}
		br.ErrMsg = err.Error()
		return
	}

	ret := &data_manage.BalanceSeasonChartLegendPreviewResp{List: list}
	br.Data = ret
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// AddStaticExcel
// @Title 新增静态表
// @Description 新增静态表
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/balance/static/add [post]
func (c *ExcelInfoController) AddStaticExcel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.AddBalanceStaticExcelInfoReq
	err := json.Unmarshal(c.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_BALANCE_STATIC_ADD_" + strconv.Itoa(req.ExcelInfoId)
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		br.Msg = "系统处理中,请稍后重试!"
		br.ErrMsg = "系统处理中,请稍后重试!"
		return
	}
	defer func() {
		_ = utils.Rc.Delete(cacheKey)
	}()

	req.VersionName = strings.Trim(req.VersionName, " ")
	if req.VersionName == "" {
		br.Msg = "请填写版本名称!"
		br.IsSendEmail = false
		return
	}

	// 获取原ETA表格信息
	oldExcelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		return
	}
	// 操作权限校验, 增加协作人判断
	{
		// 数据权限
		haveOperaAuth, err := data_manage_permission.CheckExcelPermissionByExcelInfoId(oldExcelInfo.ExcelInfoId, oldExcelInfo.ExcelClassifyId, oldExcelInfo.IsJoinPermission, c.SysUser.AdminId)
		if err != nil {
			br.Msg = "获取ETA表格失败"
			br.ErrMsg = "获取ETA表格权限失败,Err:" + err.Error()
			return
		}
		button := excelService.GetExcelInfoOpButton(sysUser, oldExcelInfo.SysUserId, oldExcelInfo.Source, haveOperaAuth)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}
	// 查询出每个子表的内容,并将内容转为静态版本
	excelDataMap := make(map[int]map[int][]*data_manage.EdbDataList)
	//查询动态表所有的子表,并复制为静态表
	condition := " AND parent_id = ? AND balance_type = 0 "
	var pars []interface{}
	pars = append(pars, req.ExcelInfoId)
	childExcelList, err := excel.GetExcelInfoListByCondition(condition, pars)
	if err != nil {
		br.Msg = "获取子表失败"
		br.ErrMsg = fmt.Sprintf("获取子表失败 %s", err.Error())
		return
	}
	for k, childExcelInfo := range childExcelList {
		//得到表格数据并落库

		newExcelDataMap, excelAllRows, excelAllCols, e, errMsg := excelService.GetBalanceExcelData(childExcelInfo, c.Lang)
		if e != nil {
			br.Msg = "获取表格数据失败"
			if errMsg != "" {
				br.Msg = errMsg
			}
			br.ErrMsg = "获取表格数据失败,Err:" + e.Error()
			return
		}
		tmpMappingList, e := excel.GetExcelChartEdbMappingByExcelInfoId(childExcelInfo.ExcelInfoId)
		if e != nil {
			br.Msg = "获取图表,指标信息失败"
			br.ErrMsg = fmt.Sprintf(" 获取图表,指标信息失败 Err:%s", err.Error())
			return
		}
		if len(tmpMappingList) > 0 {
			for _, mapping := range tmpMappingList {
				child, ok := excelDataMap[mapping.ChartInfoId]
				if !ok {
					child = make(map[int][]*data_manage.EdbDataList)
				}
				er, msg := excelService.GetBalanceExcelEdbData(mapping, newExcelDataMap, child, excelAllRows, excelAllCols)
				if er != nil {
					utils.FileLog.Info(fmt.Sprintf(" 获取图表,指标信息失败 Err:%s, %s", msg, er.Error()))
					continue
				}
				excelDataMap[mapping.ChartInfoId] = child
			}
		}

		content, e := excelService.TransferBalanceExcelContentToStatic(childExcelInfo, c.Lang)
		if e != nil {
			br.Msg = "动态内容转成静态失败"
			br.ErrMsg = fmt.Sprintf("动态内容转成静态失败 %s", e.Error())
			return
		}
		childExcelList[k].Content = content
	}

	excelInfo, err, errMsg, isSendEmail := data.AddBalanceStaticExcel(oldExcelInfo, oldExcelInfo.ExcelClassifyId, req.VersionName, sysUser, 0, req.ExcelInfoId, 1, childExcelList, true, excelDataMap)
	if err != nil {
		br.Msg = "复制失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "复制失败,Err:" + err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	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
}

// BalanceVersionList
// @Title 查询平衡表版本号列表
// @Description 查询平衡表版本号列表
// @Param	request	body request.EditExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/balance/version [get]
func (c *ExcelInfoController) BalanceVersionList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	excelInfoId, _ := c.GetInt("ExcelInfoId")
	if excelInfoId <= 0 {
		br.Msg = "请选择表格"
		br.ErrMsg = "ExcelInfoId未传"
		br.IsSendEmail = false
		return
	}
	excelInfo, err := excel.GetExcelInfoById(excelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}
	if excelInfo.Source != utils.BALANCE_TABLE {
		br.Msg = "请选择平衡表"
		return
	}
	if excelInfo.BalanceType != 0 && excelInfo.ParentId != 0 {
		br.Msg = "请选择动态平衡表"
		return
	}
	list := make([]*response.BalanceTableVersionListItem, 0)
	list = append(list, &response.BalanceTableVersionListItem{
		ExcelInfoId:    excelInfo.ExcelInfoId,
		UniqueCode:     excelInfo.UniqueCode,
		BalanceType:    excelInfo.BalanceType,
		RelExcelInfoId: excelInfo.RelExcelInfoId,
		VersionName:    "动态表", //todo 有个默认的版本名称
	})
	//查询动态表所有的子表,并复制为静态表
	condition := " AND rel_excel_info_id=? AND parent_id = 0 AND balance_type = 1 "
	var pars []interface{}
	pars = append(pars, excelInfoId)

	staticList, err := excel.GetNoContentExcelInfoListByConditionNoPage(condition, pars)
	if err != nil {
		br.Msg = "获取子表失败"
		br.ErrMsg = fmt.Sprintf("获取子表失败 %s", err.Error())
		return
	}

	for _, staticInfo := range staticList {
		tmp := &response.BalanceTableVersionListItem{
			ExcelInfoId:    staticInfo.ExcelInfoId,
			UniqueCode:     staticInfo.UniqueCode,
			BalanceType:    staticInfo.BalanceType,
			RelExcelInfoId: staticInfo.RelExcelInfoId,
			VersionName:    staticInfo.VersionName,
		}
		list = append(list, tmp)
	}
	ret := &response.BalanceTableVersionListResp{List: list}
	br.Data = ret
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// ModifyBalanceExcelVersion
// @Title 版本号重命名
// @Description 版本号重命名
// @Param	request	body request.AddBalanceStaticExcelInfoReq true "type json string"
// @Success 200 {object} response.AddExcelInfoResp
// @router /excel_info/balance/version/modify [post]
func (c *ExcelInfoController) ModifyBalanceExcelVersion() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

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

	req.VersionName = strings.Trim(req.VersionName, " ")
	if req.VersionName == "" {
		br.Msg = "请填写版本名称!"
		br.IsSendEmail = false
		return
	}
	excelInfo, err := excel.GetExcelInfoById(req.ExcelInfoId)
	if err != nil {
		br.Msg = "获取ETA表格失败"
		br.ErrMsg = "获取ETA表格失败,Err:" + err.Error()
		return
	}
	if excelInfo.Source != utils.BALANCE_TABLE {
		br.Msg = "请选择平衡表"
		return
	}
	if excelInfo.BalanceType != 1 && excelInfo.ParentId != 0 {
		br.Msg = "请选择静态表"
		return
	}

	// 操作权限校验, 增加协作人判断
	{
		checkExcelInfo := excelInfo
		if excelInfo.Source == utils.BALANCE_TABLE {
			checkExcelInfoId := excelInfo.ExcelInfoId
			if excelInfo.BalanceType == 1 {
				checkExcelInfoId = excelInfo.RelExcelInfoId
			} else {
				if excelInfo.ParentId > 0 {
					checkExcelInfoId = excelInfo.ParentId
				}
			}
			if checkExcelInfoId != excelInfo.ExcelInfoId {
				checkExcelInfo, err = excel.GetExcelInfoById(checkExcelInfoId)
				if err != nil {
					br.Msg = "获取平衡表格信息失败"
					br.ErrMsg = "获取平衡表格信息失败,Err:" + err.Error()
					return
				}
			}
		}
		// 数据权限
		haveOperaAuth, e := data_manage_permission.CheckExcelPermissionByExcelInfoId(checkExcelInfo.ExcelInfoId, checkExcelInfo.ExcelClassifyId, checkExcelInfo.IsJoinPermission, c.SysUser.AdminId)
		if e != nil {
			br.Msg = "获取ETA表格权限失败"
			br.ErrMsg = "获取表格权限信息失败,Err" + e.Error()
			return
		}

		button := excelService.GetBalanceExcelInfoOpButton(sysUser.AdminId, checkExcelInfo.SysUserId, haveOperaAuth, checkExcelInfo.ExcelInfoId)
		if !button.OpButton {
			br.Msg = "无操作权限"
			br.IsSendEmail = false
			return
		}
	}
	// 检验分类下是否存在该版本号
	{
		var condition string
		var pars []interface{}
		condition += " AND rel_excel_info_id=? AND parent_id=0"
		pars = append(pars, req.ExcelInfoId)

		condition += " AND version_name=? "
		pars = append(pars, req.VersionName)

		count, tmpErr := excel.GetExcelInfoCountByCondition(condition, pars)
		if tmpErr != nil {
			br.Msg = "查询版本名称失败"
			br.ErrMsg = tmpErr.Error()
			return
		}
		if count > 0 {
			br.Msg = "表格版本名称已存在,请重新填写版本名称"
			br.IsSendEmail = false
			return
		}
	}

	excelInfo.ModifyTime = time.Now()
	excelInfo.VersionName = req.VersionName
	updateExcelInfoParams := []string{"ModifyTime", "VersionName"}
	// todo 同步修改静态表中的图表和指标名称
	// ETA表格信息变更
	err = excelInfo.Update(updateExcelInfoParams)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

func downloadBalanceTable(excelInfo *excel.ExcelInfo, lang string) (savePath, zipName string, uploadDir string, err error, errMsg string) {
	dateDir := time.Now().Format("20060102")
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	uploadDir = "static/xls/" + dateDir + "/" + randStr
	err = os.MkdirAll(uploadDir, utils.DIR_MOD)
	if err != nil {
		return
	}
	fileList := make([]string, 0)
	if excelInfo.ParentId != 0 && excelInfo.BalanceType != 0 {
		errMsg = "平衡表类型错误"
		err = fmt.Errorf("平衡表类型错误 ")
		return
	}
	//复制静态表
	staticCondition := " AND parent_id = 0 AND balance_type = 1 AND rel_excel_info_id=? "
	var staticPars []interface{}
	staticPars = append(staticPars, excelInfo.ExcelInfoId)
	excelList, err := excel.GetExcelInfoListByCondition(staticCondition, staticPars)
	if err != nil {
		errMsg = "获取表格失败"
		err = fmt.Errorf("获取表格失败 %s", err.Error())
		return
	}
	excelList = append(excelList, excelInfo)
	for _, staticExcelInfo := range excelList {
		cCondition := " AND parent_id = ?"
		var cPars []interface{}
		cPars = append(cPars, staticExcelInfo.ExcelInfoId)
		childList, e := excel.GetExcelInfoListByCondition(cCondition, cPars)
		if e != nil {
			errMsg = "获取子表失败"
			err = fmt.Errorf("获取子表失败 %s", err.Error())
			return
		}
		xlsxFile := xlsx.NewFile()
		fileName := staticExcelInfo.ExcelName + ".xlsx"
		fpath := uploadDir + "/" + fileName
		for _, childExcelInfo := range childList {
			var result request.MixedTableReq
			err = json.Unmarshal([]byte(childExcelInfo.Content), &result)
			if err != nil {
				errMsg = "获取失败"
				err = fmt.Errorf("表格json转结构体失败,Err:" + err.Error())
				return
			}
			newResult, er, msg := excelService.GetMixedTableCellData(result, lang)
			if er != nil {
				err = er
				errMsg = msg
				return
			}
			tableData, er := excel2.GetTableDataByMixedTableData(newResult, false)
			if er != nil {
				errMsg = "获取失败"
				err = fmt.Errorf("转换成table失败,Err:" + err.Error())
				return
			}

			// 将单个sheet的数据写入到excel
			err = tableData.WriteExcelSheetData(xlsxFile, childExcelInfo.ExcelName)
			if err != nil {
				return
			}
		}
		//处理excel文件
		//return
		err = xlsxFile.Save(fpath)
		if err != nil {
			return
		}
		fileList = append(fileList, fileName)
	}
	// 创建zip
	zipName = excelInfo.ExcelName + ".zip"

	savePath = uploadDir + "/" + zipName
	fmt.Println(savePath)
	zipFile, err := os.Create(savePath)
	if err != nil {
		return
	}
	zipWriter := zip.NewWriter(zipFile)
	// 生成zip过程中报错关闭
	defer func() {
		if err != nil {
			zipWriter.Close()
			zipFile.Close()
		}
		//os.Remove(savePath)
	}()
	//写入zip
	for i := 0; i < len(fileList); i++ {
		ioWriter, e := zipWriter.Create(fileList[i])
		if e != nil {
			err = fmt.Errorf("创建zip失败,Err:" + e.Error())
			if os.IsPermission(e) {
				fmt.Println("权限不足: ", e)
				return
			}
			return
		}
		fullPath := uploadDir + "/" + fileList[i]
		content, e := ioutil.ReadFile(fullPath)
		if e != nil {
			err = fmt.Errorf("读取文件失败,Err:" + e.Error())
			return
		}
		ioWriter.Write(content)
	}
	// 生成zip后关闭,否则下载文件会损坏
	zipWriter.Close()
	zipFile.Close()
	//this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	return
}

func refreshBalanceTable(excelDetail response.ExcelInfoDetail, lang string) (err error) {
	edbInfoIds := make([]int, 0)
	edbInfoIdExist := make(map[int]bool)
	if excelDetail.ParentId > 0 {
		newResult := excelDetail.TableData.(request.MixedTableReq)
		newData := newResult.Data
		if len(newData) > 0 {
			for _, t := range newData {
				for _, v := range t {
					if v.EdbInfoId > 0 && !edbInfoIdExist[v.EdbInfoId] {
						edbInfoIdExist[v.EdbInfoId] = true
						edbInfoIds = append(edbInfoIds, v.EdbInfoId)
					}
				}
			}
		}

		// 清除缓存
		key := utils.HZ_CHART_LIB_EXCEL_TABLE_DETAIL + ":" + excelDetail.UniqueCode
		if utils.Re == nil {
			_ = utils.Rc.Delete(key)
		}
	} else {
		//查询父表和子表
		cCondition := " AND parent_id = ? AND balance_type=0"
		var cPars []interface{}
		cPars = append(cPars, excelDetail.ExcelInfoId)
		childList, e := excel.GetExcelInfoListByCondition(cCondition, cPars)
		if e != nil {
			err = fmt.Errorf("获取子表失败 %s", err.Error())
			return
		}
		// 遍历
		for _, child := range childList {
			var result request.MixedTableReq
			err = json.Unmarshal([]byte(child.Content), &result)
			if err != nil {
				err = errors.New("表格json转结构体失败,Err:" + err.Error())
				return
			}
			var newData [][]request.MixedTableCellDataReq
			newData, err, _ = excelService.GetMixedTableCellData(result, lang)
			if err != nil {
				return
			}

			if len(newData) > 0 {
				for _, t := range newData {
					for _, v := range t {
						if v.EdbInfoId > 0 && !edbInfoIdExist[v.EdbInfoId] {
							edbInfoIdExist[v.EdbInfoId] = true
							edbInfoIds = append(edbInfoIds, v.EdbInfoId)
						}
					}
				}
			}

			// 清除缓存
			key := utils.HZ_CHART_LIB_EXCEL_TABLE_DETAIL + ":" + child.UniqueCode
			if utils.Re == nil {
				_ = utils.Rc.Delete(key)
			}
		}
	}

	if len(edbInfoIds) > 0 {
		err, _ = data.EdbInfoRefreshAllFromBaseV3(edbInfoIds, false, true, false)
		if err != nil {
			err = fmt.Errorf("刷新混合表格数据失败, Err: " + err.Error())
			return
		}
	}
	return
}

// BalanceChartInfoBaseEdit
// @Title 编辑图表基础信息接口
// @Description 编辑图表基础信息接口
// @Param	request	body data_manage.EditChartEnInfoBaseReq true "type json string"
// @Success Ret=200 编辑成功
// @router /excel_info/balance/chart_base_edit [post]
func (this *ExcelInfoController) BalanceChartInfoBaseEdit() {
	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 data_manage.EditChartInfoBaseReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	req.ChartName = strings.Trim(req.ChartName, " ")
	if req.ChartInfoId <= 0 {
		br.Msg = "请选择图表"
		return
	}

	//判断指标名称是否存在
	chartItem, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if utils.IsErrNoRow(err) {
			br.Msg = "图表已被删除,请刷新页面"
			br.ErrMsg = "图表已被删除,请刷新页面"
			return
		}
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	// 判断是否有传入对应的指标配置
	noEdbInfoType := []int{10}
	if len(req.ChartEdbInfoList) <= 0 && !utils.InArrayByInt(noEdbInfoType, chartItem.ChartType) {
		br.Msg = "请选择指标!"
		return
	}

	var edbCondition string
	var edbPars []interface{}
	for _, v := range req.ChartEdbInfoList {
		edbInfoId := v.EdbInfoId
		edbInfo, err := excel.GetExcelChartEdbById(edbInfoId)
		if err != nil {
			if utils.IsErrNoRow(err) {
				br.Msg = "图表不存在!"
				br.ErrMsg = "图表指标不存在,ChartInfoId:" + strconv.Itoa(edbInfoId)
				return
			} else {
				br.Msg = "获取图表信息失败!"
				br.ErrMsg = "获取图表的指标信息失败,Err:" + err.Error()
				return
			}
		}
		if edbInfo == nil {
			br.Msg = "指标不存在!"
			br.ErrMsg = "指标不存在,ChartInfoId:" + strconv.Itoa(edbInfoId)
			return
		}

		//判断指标名称是否重复
		if v.EdbName != "" {
			edbCondition = ""
			edbPars = make([]interface{}, 0)

			edbCondition += " AND excel_chart_edb_id<>?  AND chart_info_id=?"
			edbPars = append(edbPars, edbInfo.ExcelChartEdbId, chartItem.ChartInfoId)

			switch this.Lang {
			case utils.EnLangVersion:
				edbCondition += " AND edb_name_en =? "
			default:
				edbCondition += " AND edb_name =? "
			}

			edbPars = append(edbPars, v.EdbName)

			edbExist, err := excel.GetBalanceChartEdbByCondition(edbCondition, edbPars)
			if err != nil {
				if !utils.IsErrNoRow(err) {
					br.Msg = "判断英文指标名称是否存在失败"
					br.ErrMsg = "判断英文指标名称是否存在失败,Err:" + err.Error()
					return
				}
			}

			if err == nil && edbExist.ExcelChartEdbId > 0 {
				br.Msg = edbExist.EdbName + ":" + v.EdbName + "指标名称已存在"
				br.ErrMsg = "指标名称已存在,请重新填写"
				br.IsSendEmail = false
				return
			}
		}
	}
	if req.ChartName != "" || req.ExtraConfig != `` {
		var condition string
		var pars []interface{}
		condition += " AND chart_info_id<>? "
		pars = append(pars, req.ChartInfoId)

		switch this.Lang {
		case utils.EnLangVersion:
			condition += " AND chart_name_en = ? "
		default:
			condition += " AND chart_name = ? "
		}

		pars = append(pars, req.ChartName)

		existItem, err := data_manage.GetChartInfoByCondition(condition, pars)
		if err != nil {
			if !utils.IsErrNoRow(err) {
				br.Msg = "判断英文图表名称是否存在失败"
				br.ErrMsg = "判断英文图表名称是否存在失败,Err:" + err.Error()
				return
			}
		}

		if err == nil && existItem.ChartInfoId > 0 {
			br.Msg = existItem.ChartName + ":" + req.ChartName + "图表名称已存在"
			return
		}
	}

	err = excel.EditBalanceChartBaseInfoAndEdbEnInfo(&req, chartItem, this.Lang)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	//添加es数据
	go data.AddOrEditChartInfoToEs(chartItem.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "编辑图表英文信息"
		chartLog.Method = this.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}
	//清除缓存
	if utils.Re == nil && utils.Rc != nil {
		utils.Rc.Delete(utils.HZ_CHART_LIB_DETAIL + chartItem.UniqueCode) //图表分享链接缓存
		utils.Rc.Delete(data.GetChartInfoDataKey(req.ChartInfoId))
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}