package chart

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/request"
	responseModel "hongze/hongze_yb/models/response"
	"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"
	edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
	"hongze/hongze_yb/models/tables/yb_my_chart"
	"hongze/hongze_yb/services/alarm_msg"
	"hongze/hongze_yb/services/chart"
	"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", "")
	// 图表样式类型
	reqChartType := c.DefaultQuery("ChartType", "")
	chartType, _ := strconv.Atoi(reqChartType)
	// 季节性图表时间
	reqSeasonStartDate := c.DefaultQuery("SeasonStartDate", "")
	reqSeasonEndDate := c.DefaultQuery("SeasonEndDate", "")
	// 指标ID
	edbInfoId := c.DefaultQuery("EdbInfoId", "")
	// 公历/农历
	reqCalendar := c.DefaultQuery("Calendar", "")

	// 获取图表信息
	var err error
	chartInfo := new(chartInfoModel.ChartInfoView)
	chartInfo, err = chartInfoModel.GetChartInfoViewById(chartInfoId)
	if err != nil {
		if err == utils.ErrNoRow {
			response.Custom(4003, "图表不存在，请刷新页面", c)
			return
		}
		response.FailMsg("获取失败", "获取图表信息失败, Err:"+err.Error(), c)
		return
	}
	chartType = chartInfo.ChartType
	calendar := chartInfo.Calendar
	if reqCalendar != "" {
		calendar = reqCalendar
	}

	// 时段筛选
	reqDateType := c.DefaultQuery("DateType", "")
	dateType := chartInfo.DateType
	if reqDateType != "" {
		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:
		if startDate == "" && chartInfo.StartDate != "" {
			startDate = chartInfo.StartDate
			endDate = chartInfo.EndDate
		}
	case 6:
		if startDate == "" && chartInfo.StartDate != "" {
			startDate = chartInfo.StartDate
		}
	case 7:
		startDate = "2018-01-01"
	case 8:
		startDate = "2019-01-01"
	case 9:
		startDate = "2020-01-01"
	case 11:
		startDate = "2022-01-01"
	}

	// 兼容日期错误
	{
		if strings.Count(startDate, "-") == 1 {
			startDate = startDate + "-01"
		}
		if strings.Count(endDate, "-") == 1 {
			endDate = endDate + "-01"
		}
	}

	if chartType == 2 {
		// 季节性图表
		var seasonStartDate, seasonEndDate string
		if reqSeasonStartDate == "" {
			seasonStartDate = chartInfo.SeasonStartDate
		} else {
			seasonStartDate = reqSeasonStartDate
		}
		if reqSeasonEndDate == "" {
			seasonEndDate = chartInfo.SeasonEndDate
		} else {
			seasonEndDate = reqSeasonEndDate
		}
		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 = time.Now().Format(utils.FormatDate)
		}
	}

	// 获取图表指标映射
	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
			}
		}
	}

	//fmt.Println("start_date:", startDate)
	//fmt.Println("end_date:", endDate)

	// 柱方图的一些配置
	var barConfig request.BarChartInfoReq
	barChartInfoDateList := make([]request.BarChartInfoDateReq, 0)
	barChartInfoSort := request.BarChartInfoSortReq{}
	if chartInfo != nil && chartInfo.ChartType == 7 {
		if chartInfo.BarConfig == `` {
			response.FailMsg("柱方图未配置", "柱方图未配置", c)
			return
		}

		err := json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
		if err != nil {
			response.FailMsg("柱方图配置异常", "柱方图配置异常", c)
			return
		}

		barChartInfoDateList = barConfig.DateList
		barChartInfoSort = barConfig.Sort

		// 指标别名
		for _, v := range mappingList {
			for _, confEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == confEdb.EdbInfoId {
					v.EdbAliasName = confEdb.Name
				}
			}
		}
	}
	// 获取图表中的指标数据
	edbList, xEdbIdValue, yDataList, sourceArr, err := chart.GetChartEdbData(chartInfoId, chartType, calendar, startDate, endDate, mappingList, barChartInfoDateList, barChartInfoSort)
	if err != nil {
		response.FailMsg("获取失败", "获取图表，指标信息失败, Err:"+err.Error(), c)
		return
	}

	for _, v := range edbList {
		// 指标别名
		if barConfig.EdbInfoIdList != nil && len(barConfig.EdbInfoIdList) > 0 {
			for _, reqEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
				}
			}
		}
	}

	sourceArr = append(sourceArr, "弘则研究")
	chartInfo.ChartSource = strings.Join(sourceArr, ",")

	// 访问记录-仅普通用户记录
	userInfo := user.GetInfoByClaims(c)
	ok, _, _ := user.GetAdminByUserInfo(userInfo)
	if !ok {
		reqMyChartClassifyId := c.DefaultQuery("MyChartClassifyId", "")
		myChartClassifyId, _ := strconv.Atoi(reqMyChartClassifyId)
		go chart.SaveChartVisitLog(userInfo, chartInfo, myChartClassifyId)
	}

	// 用户是否有收藏该图表
	ob := new(yb_my_chart.YbMyChart)
	cond := `user_id = ? AND chart_info_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, userInfo.UserID, chartInfo.ChartInfoId)
	exists, e := ob.FetchByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		response.FailMsg("操作失败", "获取用户图表失败, Err: "+e.Error(), c)
		return
	}
	myChartInfo := new(responseModel.MyChartItem)
	if exists != nil && exists.MyChartID > 0 {
		myChartInfo.MyChartID = exists.MyChartID
		myChartInfo.MyChartClassifyID = exists.MyChartClassifyID
		myChartInfo.ChartInfoID = exists.ChartInfoID
		myChartInfo.ChartName = exists.ChartName
		myChartInfo.UniqueCode = exists.UniqueCode
		myChartInfo.ChartImage = exists.ChartImage
		myChartInfo.UserID = exists.UserID
		myChartInfo.ReportID = exists.ReportID
		myChartInfo.ReportChapterID = exists.ReportChapterID
		myChartInfo.CreateTime = utils.TimeTransferString(utils.FormatDateTime, exists.CreateTime)
	}

	resp := new(chart_info.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.MyChartInfo = myChartInfo

	response.OkData("获取成功", resp, c)
}

func getChartInfoDetail(chartInfo *chartInfoModel.ChartInfoView, myChartClassifyId int, userInfo user.UserInfo) (resp *chart_info.ChartInfoDetailResp, isOk bool, msg, errMsg string) {
	// 获取图表信息
	var err error
	chartType := chartInfo.ChartType
	calendar := chartInfo.Calendar

	// 时段筛选
	dateType := chartInfo.DateType
	if dateType <= 0 {
		dateType = 3 // 默认同后台15年至今
	}
	var startDate, endDate string
	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:
		if startDate == "" && chartInfo.StartDate != "" {
			startDate = chartInfo.StartDate
			endDate = chartInfo.EndDate
		}
	case 6:
		if startDate == "" && chartInfo.StartDate != "" {
			startDate = chartInfo.StartDate
		}
	case 7:
		startDate = "2018-01-01"
	case 8:
		startDate = "2019-01-01"
	case 9:
		startDate = "2020-01-01"
	case 11:
		startDate = "2022-01-01"
	}

	// 兼容日期错误
	{
		if strings.Count(startDate, "-") == 1 {
			startDate = startDate + "-01"
		}
		if strings.Count(endDate, "-") == 1 {
			endDate = endDate + "-01"
		}
	}

	if chartType == 2 {
		// 季节性图表
		var seasonStartDate, seasonEndDate string
		seasonStartDate = chartInfo.SeasonStartDate
		seasonEndDate = chartInfo.SeasonEndDate
		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 = time.Now().Format(utils.FormatDate)
		}
	}

	// 获取图表指标映射
	mappingList := make([]*chartEdbMappingModel.ChartEdbInfoMapping, 0)
	mappingList, err = chartEdbMappingModel.GetMappingListByChartInfoId(chartInfo.ChartInfoId)
	if err != nil {
		msg = `获取失败`
		errMsg = "获取图表指标信息失败4001, Err:" + err.Error()
		return
	}

	//fmt.Println("start_date:", startDate)
	//fmt.Println("end_date:", endDate)

	// 柱方图的一些配置
	var barConfig request.BarChartInfoReq
	barChartInfoDateList := make([]request.BarChartInfoDateReq, 0)
	barChartInfoSort := request.BarChartInfoSortReq{}
	if chartInfo != nil && chartInfo.ChartType == 7 {
		if chartInfo.BarConfig == `` {
			msg = `柱方图未配置`
			errMsg = `柱方图未配置`
			return
		}

		err := json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
		if err != nil {
			msg = `柱方图配置异常`
			errMsg = `柱方图配置异常`
			return
		}

		barChartInfoDateList = barConfig.DateList
		barChartInfoSort = barConfig.Sort

		// 指标别名
		for _, v := range mappingList {
			for _, confEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == confEdb.EdbInfoId {
					v.EdbAliasName = confEdb.Name
				}
			}
		}
	}
	// 获取图表中的指标数据
	edbList, xEdbIdValue, yDataList, sourceArr, err := chart.GetChartEdbData(chartInfo.ChartInfoId, chartType, calendar, startDate, endDate, mappingList, barChartInfoDateList, barChartInfoSort)
	if err != nil {
		msg = `获取失败`
		errMsg = "获取图表，指标信息失败, Err:" + err.Error()
		return
	}

	for _, v := range edbList {
		// 指标别名
		if barConfig.EdbInfoIdList != nil && len(barConfig.EdbInfoIdList) > 0 {
			for _, reqEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
				}
			}
		}
	}

	sourceArr = append(sourceArr, "弘则研究")
	chartInfo.ChartSource = strings.Join(sourceArr, ",")

	// 访问记录-仅普通用户记录
	ok, _, _ := user.GetAdminByUserInfo(userInfo)
	if !ok {
		go chart.SaveChartVisitLog(userInfo, chartInfo, myChartClassifyId)
	}

	// 用户是否有收藏该图表
	ob := new(yb_my_chart.YbMyChart)
	cond := `user_id = ? AND chart_info_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, userInfo.UserID, chartInfo.ChartInfoId)
	exists, e := ob.FetchByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		msg = `操作失败`
		errMsg = "获取用户图表失败, Err: " + e.Error()
		return
	}
	myChartInfo := new(responseModel.MyChartItem)
	if exists != nil && exists.MyChartID > 0 {
		myChartInfo.MyChartID = exists.MyChartID
		myChartInfo.MyChartClassifyID = exists.MyChartClassifyID
		myChartInfo.ChartInfoID = exists.ChartInfoID
		myChartInfo.ChartName = exists.ChartName
		myChartInfo.UniqueCode = exists.UniqueCode
		myChartInfo.ChartImage = exists.ChartImage
		myChartInfo.UserID = exists.UserID
		myChartInfo.ReportID = exists.ReportID
		myChartInfo.ReportChapterID = exists.ReportChapterID
		myChartInfo.CreateTime = utils.TimeTransferString(utils.FormatDateTime, exists.CreateTime)
	}

	resp = new(chart_info.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.MyChartInfo = myChartInfo

	isOk = true

	return
}

// RefreshChartInfo 刷新图表信息
// @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/refreshChartInfo [post]
func RefreshChartInfo(c *gin.Context) {
	// 参数校验
	var req chartInfoModel.RefreshChartInfoReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}
	chartInfoId := req.ChartInfoId
	if chartInfoId == 0 {
		response.Fail("参数有误", c)
		return
	}

	userInfo := user.GetInfoByClaims(c)
	ok, _, err := user.GetAdminByUserInfo(userInfo)
	if err != nil {
		response.FailMsg("刷新失败", "RefreshChartInfo-获取系统用户信息失败"+err.Error(), c)
		return
	}
	if !ok {
		// 普通用户刷新频率限制-每个用户/图/天/2次
		cacheKey := utils.HZ_CHART_LIB_DETAIL + "YB_REFRESH_LIMIT_" + strconv.Itoa(chartInfoId) + "_" + strconv.Itoa(int(userInfo.UserID))
		fmt.Println("refreshCacheKey:", cacheKey)
		countUserRefresh, _ := global.Redis.Get(context.TODO(), cacheKey).Int()
		if countUserRefresh >= 2 {
			response.Ok("目前已是最新数据", c)
			return
		}
		countUserRefresh += 1
		now := time.Now()
		today := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
		sub := today.Sub(now)
		_ = global.Redis.SetEX(context.TODO(), cacheKey, countUserRefresh, sub)
	}

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

	// 刷新图表
	if err = chart.ChartInfoRefreshV2(chartInfo.ChartInfoId); err != nil {
		errContent := fmt.Sprint("ErrMsg: 刷新图表关联指标信息失败, " + err.Error())
		if global.CONFIG.Serve.RunMode == "release" {
			go alarm_msg.SendAlarmMsg("刷新图表报错"+time.Now().Format("2006-01-02 15:04:05")+";Err:"+errContent, 3)
			//go services.SendEmail("弘则研报小程序-release-刷新图表报错", errContent, utils.EmailSendToUsers)
		} else {
			global.LOG.Info(errContent)
		}
	}

	//清除图表缓存
	{
		key := utils.HZ_CHART_LIB_DETAIL + chartInfo.UniqueCode
		_ = global.Redis.Del(context.TODO(), key)
	}

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