package excel

import (
	"archive/zip"
	"encoding/json"
	"errors"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_manage/excel"
	"eta/eta_mobile/models/data_manage/excel/request"
	"eta/eta_mobile/models/data_manage/excel/response"
	"eta/eta_mobile/services/data"
	"eta/eta_mobile/services/data/data_manage_permission"
	excelService "eta/eta_mobile/services/data/excel"
	excel2 "eta/eta_mobile/services/excel"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"io/ioutil"
	"os"
	"time"
)

// 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 err.Error() == utils.ErrNoRow() {
				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.EsDeleteChartInfo(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
}

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
}

// 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
}

// 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 = "操作成功"
}

// 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 err.Error() == utils.ErrNoRow() {
			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
}

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
			}
			tableData, err = excel2.HandleRuleToTableCell(childExcelInfo.ExcelInfoId, tableData)
			if err != nil {
				errMsg = "获取失败"
				err = fmt.Errorf("处理条件格式管理规则失败，Err:%w", err)
				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
}
