package chart

import (
	"context"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response/chart_info"
	chartEdbMappingModel "hongze/hongze_yb/models/tables/chart_edb_mapping"
	chartInfoModel "hongze/hongze_yb/models/tables/chart_info"
	"hongze/hongze_yb/models/tables/chart_info_log"
	edbDataModel "hongze/hongze_yb/models/tables/edb_data"
	edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
	"hongze/hongze_yb/services/chart"
	edbDataService "hongze/hongze_yb/services/edb_data"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"io/ioutil"
	"sort"
	"strconv"
	"strings"
	"time"
)

// GetChartInfoDetail 获取图表详情
// @Tags 图库模块
// @Summary  获取图表详情
// @Description 获取图表详情
// @Security ApiKeyAuth
// @Param Authorization	header string true "Bearer 31a165baebe6dec616b1f8f3207b4273"
// @Accept  json
// @Product json
// @Param DateType query string false "时间段：1-00年至今; 2-10年至今; 3-15年至今; 4-21年至今; 5-指定区间; 6-指定年月至今; 7-18年至今; 8-19年至今; 9-20年至今"
// @Param ClassifyId query string false "图表分类ID"
// @Success 200 {object} chart_info.ChartInfoDetailResp
// @failure 400 {string} string "图表详情获取失败"
// @Router /my_chart/getChartInfoDetail [get]
func GetChartInfoDetail(c *gin.Context)  {
	// 图表ID
	reqChartInfoId := c.DefaultQuery("ChartInfoId", "")
	if reqChartInfoId == "" {
		response.Fail("参数有误:图表ID", c)
		return
	}
	chartInfoId, _ := strconv.Atoi(reqChartInfoId)

	startDate := c.DefaultQuery("StartDate", "")
	endDate := c.DefaultQuery("EndDate", "")
	// 时段筛选
	reqDateType := c.DefaultQuery("DateType", "")
	dateType, _ := strconv.Atoi(reqDateType)
	if dateType <= 0 {
		dateType = 3	// 默认同后台15年至今
	}
	switch dateType {
	case 1:
		startDate = "2000-01-01"
	case 2:
		startDate = "2010-01-01"
	case 3:
		startDate = "2015-01-01"
	case 4:
		startDate = "2021-01-01"
	case 5:
		startDate = startDate + "-01"
		endDate = endDate + "-01"
	case 6:
		startDate = startDate + "-01"
	case 7:
		startDate = "2018-01-01"
	case 8:
		startDate = "2019-01-01"
	case 9:
		startDate = "2020-01-01"
	}
	// 图表样式类型
	reqChartType := c.DefaultQuery("ChartType", "")
	chartType, _ := strconv.Atoi(reqChartType)
	// 季节性图表时间
	seasonStartDate := c.DefaultQuery("SeasonStartDate", "")
	seasonEndDate := c.DefaultQuery("SeasonEndDate", "")
	// 指标ID
	edbInfoId := c.DefaultQuery("EdbInfoId", "")
	// 公历/农历
	calendar := c.DefaultQuery("Calendar", "公历")

	// 获取图表信息
	var err error
	chartInfo := new(chartInfoModel.ChartInfoView)
	if chartInfoId > 0 {
		chartInfo, err = chartInfoModel.GetChartInfoViewById(chartInfoId)
		if err != nil {
			if err == utils.ErrNoRow {
				response.Fail("图表不存在，请刷新页面", c)
				return
			}
			response.FailMsg("获取失败", "获取图表信息失败, Err:" + err.Error(), c)
			return
		}
		chartType = chartInfo.ChartType
	}
	if chartType == 2 {
		// 季节性图表
		if seasonStartDate != "" {
			startDate = seasonStartDate + "-01-01"
		} else {
			fivePre := time.Now().AddDate(-4, 0, 0).Year()
			startDate = strconv.Itoa(fivePre) + "-01-01"
		}
		if seasonEndDate != "" {
			endDate = seasonEndDate + "-12-31"
		} else {
			endDate = ""
		}
	}

	// 获取图表指标映射
	mappingList := make([]*chartEdbMappingModel.ChartEdbInfoMapping, 0)
	if chartInfoId > 0 {
		mappingList, err = chartEdbMappingModel.GetMappingListByChartInfoId(chartInfoId)
		if err != nil {
			response.FailMsg("获取失败", "获取图表指标信息失败4001, Err:" + err.Error(), c)
			return
		}
	} else {
		if edbInfoId != "" {
			mappingList, err = chartEdbMappingModel.GetMappingListByEdbInfoId(edbInfoId)
			if err != nil {
				response.FailMsg("获取失败", "获取图表指标信息失败4002, Err:" + err.Error(), c)
				return
			}
		}
	}

	// 指标列表
	edbList := make([]*chartEdbMappingModel.ChartEdbInfoMapping, 0)
	for _, v := range mappingList {
		item := new(chartEdbMappingModel.ChartEdbInfoMapping)
		item.EdbInfoId = v.EdbInfoId
		item.SourceName = v.SourceName
		item.Source = v.Source
		item.EdbCode = v.EdbCode
		item.EdbName = v.EdbName
		item.Frequency = v.Frequency
		item.Unit = v.Unit
		item.StartDate = v.StartDate
		item.EndDate = v.EndDate
		item.ModifyTime = v.ModifyTime
		if chartInfoId <= 0 {
			item.IsAxis = 1
			item.LeadValue = 0
			item.LeadUnit = ""
			item.ChartEdbMappingId = 0
			item.ChartInfoId = 0
			item.IsOrder = false
			item.EdbInfoType = 1
			item.ChartStyle = ""
			item.ChartColor = ""
			item.ChartWidth = 0
			item.MaxData = v.MaxValue
			item.MinData = v.MinValue
		} else {
			item.IsAxis = v.IsAxis
			item.EdbInfoType = v.EdbInfoType
			item.LeadValue = v.LeadValue
			item.LeadUnit = v.LeadUnit
			item.ChartEdbMappingId = v.ChartEdbMappingId
			item.ChartInfoId = v.ChartInfoId
			item.ChartStyle = v.ChartStyle
			item.ChartColor = v.ChartColor
			item.ChartWidth = v.ChartWidth
			item.IsOrder = v.IsOrder
			item.MaxData = v.MaxData
			item.MinData = v.MinData
		}
		item.LatestValue = v.LatestValue
		item.LatestDate = v.LatestDate
		item.UniqueCode = v.UniqueCode

		var startDateReal string
		var diffSeconds int64
		if chartType == 1 {
			if v.EdbInfoType == 0 && v.LeadUnit != "" && v.LeadValue > 0 {
				// 领先指标
				var startTimeRealTemp time.Time
				startDateParse, _ := time.Parse(utils.FormatDate, startDate)
				switch v.LeadUnit {
				case "天":
					startTimeRealTemp = startDateParse.AddDate(0, 0, -v.LeadValue)
				case "月":
					startTimeRealTemp = startDateParse.AddDate(0, -v.LeadValue, 0)
				case "季":
					startTimeRealTemp = startDateParse.AddDate(0, -3*v.LeadValue, 0)
				case "周":
					startTimeRealTemp = startDateParse.AddDate(0, 0, -7*v.LeadValue)
				case "年":
					startTimeRealTemp = startDateParse.AddDate(-v.LeadValue, 0, 0)
				}
				if startTimeRealTemp.Before(startDateParse) {
					startDateReal = startTimeRealTemp.Format(utils.FormatDate)
					diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
				} else {
					startDateReal = startDate
					diffSeconds = 0
				}
			} else {
				startDateReal = startDate
			}
		} else {
			startDateReal = startDate
		}
		//fmt.Println("line 1011 chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
		calendarPreYear := 0
		if calendar == "农历" {
			newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
			if err != nil {
				response.FailMsg("获取失败", "农历时间转换有误4001, Err:" + err.Error(), c)
				//fmt.Println("time.Parse:" + err.Error())
				return
			}
			calendarPreYear = newStartDateReal.Year() - 1
			//newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
			startDateReal = newStartDateReal.Format(utils.FormatDate)
		}
		dataList := make([]*edbDataModel.EdbDataList, 0)
		//fmt.Println("chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
		dataList, err = edbDataModel.GetEdbDataList(v.Source, v.EdbInfoId, startDateReal, endDate)
		if err != nil {
			response.FailMsg("获取失败", "获取图表指标信息失败4003, Err:" + err.Error(), c)
			return
		}
		if diffSeconds != 0 && v.EdbInfoType == 0 {
			dataListLen := len(dataList)
			for i := 0; i < dataListLen; i++ {
				dataList[i].DataTimestamp = dataList[i].DataTimestamp - diffSeconds
			}
		}

		if chartType == 2 {
			if calendar == "农历" {
				if len(dataList) <= 0 {
					result := new(edbDataModel.EdbDataResult)
					item.DataList = result
				} else {
					result, err := edbDataService.AddCalculateQuarter(dataList)
					if err != nil {
						response.FailMsg("获取失败", "获取农历数据失败4002, Err:" + err.Error(), c)
						return
					}
					if result.List[0].Year != calendarPreYear {
						itemList := make([]*edbDataModel.EdbDataList, 0)
						items := new(edbDataModel.EdbDataItems)
						//items.Year = calendarPreYear
						items.Items = itemList

						newResult := new(edbDataModel.EdbDataResult)
						newResult.List = append(newResult.List, items)
						newResult.List = append(newResult.List, result.List...)
						item.DataList = newResult
					} else {
						item.DataList = result
					}
				}

			} else {
				currentYear := time.Now().Year()
				quarterDataList := make([]*edbDataModel.QuarterData, 0)
				quarterMap := make(map[int][]*edbDataModel.EdbDataList)
				var quarterArr []int
				for _, v := range dataList {
					if v.DataTime != "" {
						v.DataTime = v.DataTime[:10]
					}
					itemDate, err := time.Parse(utils.FormatDate, v.DataTime)
					if err != nil {
						response.FailMsg("获取失败", "季度指标日期转换失败, Err:" + err.Error() + ";DataTime:" + v.DataTime, c)
						return
					}
					year := itemDate.Year()
					newItemDate := itemDate.AddDate(currentYear-year, 0, 0)
					timestamp := newItemDate.UnixNano() / 1e6
					v.DataTimestamp = timestamp
					if findVal, ok := quarterMap[year]; !ok {
						quarterArr = append(quarterArr, year)
						findVal = append(findVal, v)
						quarterMap[year] = findVal
					} else {
						findVal = append(findVal, v)
						quarterMap[year] = findVal
					}
				}
				for _, v := range quarterArr {
					itemList := quarterMap[v]
					quarterItem := new(edbDataModel.QuarterData)
					quarterItem.Year = v
					quarterItem.DataList = itemList
					quarterDataList = append(quarterDataList, quarterItem)
				}
				item.DataList = quarterDataList
			}
		} else {
			item.DataList = dataList
		}
		edbList = append(edbList, item)
	}

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

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

	resp := new(chart_info.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	response.OkData("获取成功", resp, c)
}

// RefreshChartInfo 刷新图表信息
func RefreshChartInfo(c *gin.Context)  {
	// 参数校验
	reqChartInfoId := c.DefaultQuery("ChartInfoId", "")
	if reqChartInfoId == "" {
		response.Fail("参数有误:图表ID", c)
		return
	}
	chartInfoId, _ := strconv.Atoi(reqChartInfoId)

	// 刷新频率限制
	//userInfo := user.GetInfoByClaims(c)
	//cacheKey := utils.HZ_CHART_LIB_DETAIL + "YB_REFRESH_LIMIT_" + reqChartInfoId + "_" + strconv.Itoa(int(userInfo.UserID))
	//countUserRefresh, _ := global.Redis.Get(context.TODO(), cacheKey).Int()
	//if countUserRefresh > 2 {
	//	response.Ok("刷新成功", c)
	//	return
	//}
	//countUserRefresh += 1
	//_ = global.Redis.SetEX(context.TODO(), cacheKey, 1, 1 *  time.Hour)

	// 图表信息校验
	chartInfo, err := chartInfoModel.GetChartInfoById(chartInfoId)
	if err != nil {
		if err == utils.ErrNoRow {
			response.Fail("图表已被删除，无需刷新", c)
			return
		}
		response.FailMsg("刷新失败", "刷新失败, Err:" + err.Error(), c)
		return
	}

	// 刷新图表
	err = chart.RefreshChartInfo(chartInfo.ChartInfoId)
	if err != nil {
		response.FailMsg("刷新失败", "刷新图表关联指标信息失败, Err:" + err.Error(), c)
		return
	}

	response.OkData("刷新成功", "", c)
}

// EditChartInfo 编辑图表信息
// @Tags 图库模块
// @Summary  编辑图表信息
// @Description 编辑图表信息
// @Security ApiKeyAuth
// @Param Authorization	header string true "Bearer 31a165baebe6dec616b1f8f3207b4273"
// @Accept  json
// @Product json
// @Param data body chartInfoModel.SaveChartInfoReq true "请求参数"
// @Success 200 {string} string "操作成功"
// @failure 400 {string} string "操作失败"
// @Router /my_chart/editChartInfo [post]
func EditChartInfo(c *gin.Context)  {
	// 参数校验
	var req chartInfoModel.SaveChartInfoReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}

	if req.ChartInfoId > 0 && len(req.ChartEdbInfoList) <= 0 {
		response.Fail("参数异常", c)
		return
	}

	// 操作权限校验
	userInfo := user.GetInfoByClaims(c)
	ok, adminInfo, err := user.GetAdminByUserInfo(userInfo)
	if err != nil {
		response.Fail("操作人信息有误", c)
		return
	}
	if !ok {
		response.Fail("非内部人员无权进行操作", c)
		return
	}

	// 图表信息校验
	chartItem, err := chartInfoModel.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if err == utils.ErrNoRow {
			response.Fail("图表已被删除，请刷新页面！", c)
			return
		}
		response.FailMsg("操作失败", "获取图表信息失败, Err:" + err.Error(), c)
		return
	}
	if chartItem.ChartType == 2 && len(req.ChartEdbInfoList) > 1 {
		response.Fail("您选择的图表样式为季节性图表，只支持单指标画图！", c)
		return
	}
	if req.Calendar == "" {
		req.Calendar = "公历"
	}

	// 指标信息
	var edbInfoIdArr []int
	edbList := make([]*edbInfoModel.EdbInfo, 0)

	for _, v := range req.ChartEdbInfoList {
		edbInfo, err := edbInfoModel.GetEdbInfoById(v.EdbInfoId)
		if err != nil {
			if err == utils.ErrNoRow {
				response.FailMsg("操作失败", "图表不存在，ChartInfoId:" + strconv.Itoa(v.EdbInfoId), c)
				return
			}
			response.FailMsg("操作失败", "获取图表的指标信息失败，Err:" + err.Error(), c)
			return
		}
		if edbInfo == nil {
			response.FailMsg("操作失败", "指标不存在，ChartInfoId:" + strconv.Itoa(v.EdbInfoId), c)
			return
		}
		edbInfoIdArr = append(edbInfoIdArr, v.EdbInfoId)
		edbInfo.EdbNameSource = edbInfo.EdbName
		edbList = append(edbList, edbInfo)
	}
	sort.Ints(edbInfoIdArr)
	var edbInfoIdArrStr []string
	for _, v := range edbInfoIdArr {
		edbInfoIdArrStr = append(edbInfoIdArrStr, strconv.Itoa(v))
	}
	edbInfoIdStr := strings.Join(edbInfoIdArrStr, ",")

	err = chart.ModifyChartInfoAndMapping(edbInfoIdStr, &req, chartItem.ChartType)
	if err != nil {
		response.Fail("图表保存失败, Err:" + err.Error(), c)
		return
	}

	// 清除图表缓存
	cacheKey := utils.HZ_CHART_LIB_DETAIL + chartItem.UniqueCode
	_ = global.Redis.Del(context.TODO(), cacheKey)

	// 新增操作日志
	{
		chartLog := new(chart_info_log.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = int(adminInfo.AdminID)
		chartLog.SysUserRealName = adminInfo.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
		chartLog.Content = string(bodyBytes)
		chartLog.Status = "修改配置项"
		chartLog.Method = c.Request.URL.String()
		go chartLog.Create()
	}

	response.OkData("操作成功", "", c)
}