package correlation

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_ETA_mobile_api/controllers"
	"hongze/hongze_ETA_mobile_api/models"
	"hongze/hongze_ETA_mobile_api/models/data_manage"
	"hongze/hongze_ETA_mobile_api/models/system"
	"hongze/hongze_ETA_mobile_api/services/data"
	correlationServ "hongze/hongze_ETA_mobile_api/services/data/correlation"
	"hongze/hongze_ETA_mobile_api/utils"
	"strconv"
	"strings"
	"time"
)

// CorrelationChartInfoController 相关性图表管理
type CorrelationChartInfoController struct {
	controllers.BaseAuthController
}

// GetChartInfoDetailFromUniqueCode 根据编码获取图表详情
func GetChartInfoDetailFromUniqueCode(chartInfo *data_manage.ChartInfoView, isCache bool, sysUser *system.Admin) (resp *data_manage.ChartInfoDetailFromUniqueCodeResp, isOk bool, msg, errMsg string) {
	resp = new(data_manage.ChartInfoDetailFromUniqueCodeResp)

	adminId := sysUser.AdminId

	//判断是否存在缓存，如果存在缓存，那么直接从缓存中获取
	key := data.GetChartInfoDataKey(chartInfo.ChartInfoId)
	if utils.Re == nil && isCache {
		if utils.Re == nil && utils.Rc.IsExist(key) {
			if chartData, err1 := utils.Rc.RedisBytes(key); err1 == nil {
				err := json.Unmarshal(chartData, &resp)
				if err == nil && resp != nil {
					// 这里跟当前用户相关的信息重新查询写入resp, 不使用缓存中的
					var myCond string
					var myPars []interface{}
					myCond += ` AND a.admin_id=? `
					myPars = append(myPars, adminId)
					myCond += ` AND a.chart_info_id=? `
					myPars = append(myPars, chartInfo.ChartInfoId)
					myList, err := data_manage.GetMyChartByCondition(myCond, myPars)
					if err != nil && err.Error() != utils.ErrNoRow() {
						msg = "获取失败"
						errMsg = "获取我的图表信息失败，GetMyChartByCondition，Err:" + err.Error()
						return
					}
					resp.ChartInfo.IsAdd = false
					resp.ChartInfo.MyChartId = 0
					resp.ChartInfo.MyChartClassifyId = ""
					if myList != nil && len(myList) > 0 {
						resp.ChartInfo.IsAdd = true
						resp.ChartInfo.MyChartId = myList[0].MyChartId
						resp.ChartInfo.MyChartClassifyId = myList[0].MyChartClassifyId
					}

					isOk = true
					fmt.Println("source redis")
					return
				}
			}
		}
	}

	chartInfoId := chartInfo.ChartInfoId

	// 相关性图表信息
	correlationChart := new(data_manage.ChartInfoCorrelation)
	if e := correlationChart.GetItemById(chartInfoId); e != nil {
		msg = "获取失败"
		errMsg = "获取图表相关性信息失败, Err:" + e.Error()
		return
	}

	// 获取指标信息
	edbInfoMappingA, e := data_manage.GetChartEdbMappingByEdbInfoId(correlationChart.EdbInfoIdFirst)
	if e != nil {
		msg = "获取失败"
		errMsg = "获取相关性图表, A指标mapping信息失败, Err:" + e.Error()
		return
	}
	edbInfoMappingB, e := data_manage.GetChartEdbMappingByEdbInfoId(correlationChart.EdbInfoIdSecond)
	if e != nil {
		msg = "获取失败"
		errMsg = "获取相关性图表, B指标mapping信息失败, Err:" + e.Error()
		return
	}

	var dataResp interface{} // 绘图数据返回（目前是滚动相关性的图）
	var xEdbIdValue []int
	var xDateTimeValue []string
	var yDataList []data_manage.YData
	switch chartInfo.Source {
	case utils.CHART_SOURCE_CORRELATION: // 相关性图
		moveUnitDays, ok := utils.FrequencyDaysMap[correlationChart.CalculateUnit]
		if !ok {
			msg = "错误的分析周期"
			errMsg = "相关性图表数据有误"
			return
		}
		startDate := time.Now().AddDate(0, 0, -correlationChart.CalculateValue*moveUnitDays).Format(utils.FormatDate)
		endDate := time.Now().Format(utils.FormatDate)

		xEdbIdValue, yDataList, e = correlationServ.GetChartDataByEdbInfo(edbInfoMappingA, edbInfoMappingB, correlationChart.LeadValue, correlationChart.LeadUnit, startDate, endDate)
		if e != nil {
			msg = "获取失败"
			errMsg = "获取相关性图表, 图表计算值失败, Err:" + e.Error()
			return
		}
	case utils.CHART_SOURCE_ROLLING_CORRELATION: // 滚动相关性图
		multipleGraphConfigChartMapping, e := data_manage.GetMultipleGraphConfigChartMappingByChartId(chartInfo.ChartInfoId)
		if e != nil {
			msg = "获取失败"
			errMsg = "获取滚动相关性图表的配置信息失败, Err:" + e.Error()
			return
		}
		baseChartMultipleGraphConfigChartMapping, e := data_manage.GetMultipleGraphConfigChartMappingByIdAndSource(multipleGraphConfigChartMapping.MultipleGraphConfigId, 2)
		if e != nil {
			msg = "获取失败"
			errMsg = "获取相关性图表的配置信息失败, Err:" + e.Error()
			return
		}
		baseChartCorrelationChart := new(data_manage.ChartInfoCorrelation)
		if e := baseChartCorrelationChart.GetItemById(baseChartMultipleGraphConfigChartMapping.ChartInfoId); e != nil {
			msg = "获取失败"
			errMsg = "获取基础相关性图表信息失败, Err:" + e.Error()
			return
		}
		moveUnitDays, ok := utils.FrequencyDaysMap[baseChartCorrelationChart.CalculateUnit]
		if !ok {
			msg = "错误的分析周期"
			errMsg = "错误的分析周期"
			return
		}
		startDate := time.Now().AddDate(0, 0, -baseChartCorrelationChart.CalculateValue*moveUnitDays).Format(utils.FormatDate)
		endDate := time.Now().Format(utils.FormatDate)
		xDateTimeValue, yDataList, e = correlationServ.GetRollingCorrelationChartDataByEdbInfo(edbInfoMappingA, edbInfoMappingB, correlationChart.LeadValue, correlationChart.LeadUnit, correlationChart.CalculateValue, correlationChart.CalculateUnit, startDate, endDate)
		dataResp = data_manage.RollingCorrelationChartDataResp{
			XDateTimeValue: xDateTimeValue,
			YDataList:      yDataList,
		}
	}

	// 完善指标信息
	edbList, e := correlationServ.GetChartEdbInfoFormat(chartInfo.ChartInfoId, edbInfoMappingA, edbInfoMappingB)
	if e != nil {
		msg = "获取失败"
		errMsg = "获取相关性图表, 完善指标信息失败, Err:" + e.Error()
		return
	}
	correlationInfo := new(data_manage.CorrelationInfo)
	correlationInfo.LeadValue = correlationChart.LeadValue
	correlationInfo.LeadUnit = correlationChart.LeadUnit
	correlationInfo.CalculateValue = correlationChart.CalculateValue
	correlationInfo.CalculateUnit = correlationChart.CalculateUnit
	correlationInfo.StartDate = correlationChart.StartDate.Format(utils.FormatDate)
	correlationInfo.EndDate = correlationChart.EndDate.Format(utils.FormatDate)
	correlationInfo.LeadValue = correlationChart.LeadValue
	correlationInfo.EdbInfoIdFirst = correlationChart.EdbInfoIdFirst
	correlationInfo.EdbInfoIdSecond = correlationChart.EdbInfoIdSecond

	if chartInfoId > 0 && chartInfo != nil {
		//判断是否加入我的图库
		{
			var myChartCondition string
			var myChartPars []interface{}
			myChartCondition += ` AND a.admin_id=? `
			myChartPars = append(myChartPars, sysUser.AdminId)
			myChartCondition += ` AND a.chart_info_id=? `
			myChartPars = append(myChartPars, chartInfo.ChartInfoId)

			myChartList, err := data_manage.GetMyChartByCondition(myChartCondition, myChartPars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				msg = "获取失败"
				errMsg = "获取我的图表信息失败，GetMyChartByCondition，Err:" + err.Error()
				return
			}
			if myChartList != nil && len(myChartList) > 0 {
				chartInfo.IsAdd = true
				chartInfo.MyChartId = myChartList[0].MyChartId
				chartInfo.MyChartClassifyId = myChartList[0].MyChartClassifyId
			}
		}
	}

	//图表操作权限
	chartInfo.IsEdit = data.CheckOpChartPermission(sysUser, chartInfo.SysUserId)
	//判断是否需要展示英文标识
	chartInfo.IsEnChart = data.CheckIsEnChart(chartInfo.ChartNameEn, edbList[0:1], chartInfo.Source, chartInfo.ChartType)
	chartInfo.UnitEn = edbInfoMappingA.UnitEn

	isSaveAs := true
	if chartInfo.Source == utils.CHART_SOURCE_ROLLING_CORRELATION {
		isSaveAs = false
	}
	// 另存为
	chartInfo.Button = data_manage.ChartViewButton{
		IsEdit:    chartInfo.IsEdit,
		IsEnChart: chartInfo.IsEnChart,
		IsAdd:     chartInfo.IsAdd,
		IsCopy:    isSaveAs,
		IsSetName: chartInfo.IsSetName,
	}

	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.CorrelationChartInfo = correlationInfo
	resp.DataResp = dataResp
	resp.Status = true

	// 将数据加入缓存
	if utils.Re == nil {
		d, _ := json.Marshal(resp)
		_ = utils.Rc.Put(key, d, 2*time.Hour)
	}
	isOk = true
	return
}

// List
// @Title 相关性图表列表接口
// @Description 相关性图表列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ChartClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Param   Source   query   int  true       "图表类型，3：相关性，4：滚动相关性"
// @Success 200 {object} data_manage.ChartListResp
// @router /chart_info/list [get]
func (this *CorrelationChartInfoController) 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
	}

	chartClassifyId, _ := this.GetInt("ChartClassifyId")

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

	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)

	source, _ := this.GetInt("Source")
	if source <= 0 {
		source = utils.CHART_SOURCE_CORRELATION
	}

	var condition string
	var pars []interface{}

	// 普通图表
	condition += ` AND source = ? `
	pars = append(pars, source)

	if chartClassifyId > 0 {
		chartClassifyId, err := data_manage.GetChartClassify(chartClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取图表信息失败"
			br.ErrMsg = "获取信息失败,GetChartClassify,Err:" + err.Error()
			return
		}
		condition += " AND chart_classify_id IN(" + chartClassifyId + ") "
	}
	if keyword != "" {
		condition += ` AND  ( chart_name LIKE '%` + keyword + `%' )`
	}

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	if isShowMe {
		condition += ` AND sys_user_id = ? `
		pars = append(pars, sysUser.AdminId)
	}

	// 获取当前账号的不可见指标
	noPermissionChartIdList := make([]int, 0)
	{
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllChartListByAdminId(this.SysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败，Err:" + err.Error()
			return
		}
		for _, v := range confList {
			noPermissionChartIdList = append(noPermissionChartIdList, v.ChartInfoId)
		}
	}

	lenNoPermissionChartIdList := len(noPermissionChartIdList)
	if lenNoPermissionChartIdList > 0 {
		condition += ` AND chart_info_id not in (` + utils.GetOrmInReplace(lenNoPermissionChartIdList) + `) `
		pars = append(pars, noPermissionChartIdList)
	}

	//获取图表信息
	list, err := data_manage.GetChartListByCondition(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	myChartList, err := data_manage.GetMyChartListByAdminId(sysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取我的图表信息失败,Err:" + err.Error()
		return
	}
	myChartMap := make(map[int]*data_manage.MyChartView)
	for _, v := range myChartList {
		myChartMap[v.ChartInfoId] = v
	}
	listLen := len(list)
	chartEdbMap := make(map[int][]*data_manage.ChartEdbInfoMapping)
	if listLen > 0 {
		chartInfoIds := ""
		for _, v := range list {
			chartInfoIds += strconv.Itoa(v.ChartInfoId) + ","
		}
		if chartInfoIds != "" {
			chartInfoIds = strings.Trim(chartInfoIds, ",")
			//判断是否需要展示英文标识
			edbList, e := data_manage.GetChartEdbMappingListByChartInfoIds(chartInfoIds)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + e.Error()
				return
			}
			for _, v := range edbList {
				chartEdbMap[v.ChartInfoId] = append(chartEdbMap[v.ChartInfoId], v)
			}
		}
	}
	for i := 0; i < listLen; i++ {
		//判断是否需要展示英文标识
		if edbTmpList, ok := chartEdbMap[list[i].ChartInfoId]; ok {
			list[i].IsEnChart = data.CheckIsEnChart(list[i].ChartNameEn, edbTmpList, list[i].Source, list[i].ChartType)
		}

		if existItem, ok := myChartMap[list[i].ChartInfoId]; ok {
			list[i].IsAdd = true
			list[i].MyChartId = existItem.MyChartId
			list[i].MyChartClassifyId = existItem.MyChartClassifyId
		}
	}

	resp := new(data_manage.ChartListResp)
	if list == nil || len(list) <= 0 || (err != nil && err.Error() == utils.ErrNoRow()) {
		items := make([]*data_manage.ChartInfoView, 0)
		resp.Paging = page
		resp.List = items
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	dataCount, err := data_manage.GetChartListCountByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, dataCount)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Copy
// @Title 复制并新增图表接口
// @Description 新增图表接口
// @Param	request	body data_manage.CopyAddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /chart_info/copy [post]
func (this *CorrelationChartInfoController) 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
	cacheKey := "CACHE_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(this.Ctx.Input.RequestBody)
		return
	}
	var req data_manage.CopyAddChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	// 获取原图表信息
	oldChartInfo, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		br.Msg = "获取原图表信息失败"
		br.ErrMsg = "获取原图表信息失败,Err:" + err.Error()
		return
	}
	if oldChartInfo.Source == utils.CHART_SOURCE_ROLLING_CORRELATION {
		br.Msg = `滚动相关性图不支持另存为`
		br.IsSendEmail = false
		return
	}

	multipleGraphConfigChartMapping, err := data_manage.GetMultipleGraphConfigChartMappingByChartId(req.ChartInfoId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = `保存失败`
		br.ErrMsg = "获取配置与图表的关联关系失败，ERR:" + err.Error()
		return
	}

	correlationChart := new(data_manage.ChartInfoCorrelation)
	if e := correlationChart.GetItemById(req.ChartInfoId); e != nil {
		br.Msg = "另存为失败"
		br.ErrMsg = "获取原图表相关性信息失败, Err:" + e.Error()
		return
	}

	correlationChartInfoReq := data_manage.CorrelationChartInfoReq{
		LeadValue:          correlationChart.LeadValue,
		LeadUnit:           correlationChart.LeadUnit,
		CalculateValue:     correlationChart.CalculateValue,
		CalculateUnit:      correlationChart.CalculateUnit,
		BaseCalculateUnit:  correlationChart.BaseCalculateUnit,
		BaseCalculateValue: correlationChart.BaseCalculateValue,
		StartDate:          correlationChart.StartDate.Format(utils.FormatDate),
		EndDate:            correlationChart.EndDate.Format(utils.FormatDate),
		EdbInfoIdList: []data_manage.CorrelationChartInfoEdbItemReq{
			{
				EdbInfoId: correlationChart.EdbInfoIdFirst,
				Name:      "",
				NameEn:    "",
			}, {
				EdbInfoId: correlationChart.EdbInfoIdSecond,
				Name:      "",
				NameEn:    "",
			},
		},
	}

	chartInfo, err, errMsg, isSendEmail := correlationServ.CopyChartInfo(multipleGraphConfigChartMapping.MultipleGraphConfigId, req.ChartClassifyId, req.ChartName, correlationChartInfoReq, sysUser)

	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

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

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = data_manage.AddChartInfoResp{
		ChartInfoId: chartInfo.ChartInfoId,
		UniqueCode:  chartInfo.UniqueCode,
		ChartType:   chartInfo.ChartType,
	}
	br.IsAddLog = true
}
