package chart

import (
	"errors"
	"fmt"
	"hongze/hongze_yb/global"
	chartEdbMappingModel "hongze/hongze_yb/models/tables/chart_edb_mapping"
	chartInfoModel "hongze/hongze_yb/models/tables/chart_info"
	company2 "hongze/hongze_yb/models/tables/company"
	edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
	"hongze/hongze_yb/models/tables/my_chart_classify"
	"hongze/hongze_yb/models/tables/yb_chart_daily_visit_log"
	"hongze/hongze_yb/models/tables/yb_chart_visit_log"
	"hongze/hongze_yb/services/alarm_msg"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"sort"
	"strconv"
	"strings"
	"time"
)

// ModifyChartInfoAndMapping 修改图表信息
func ModifyChartInfoAndMapping(edbInfoIdStr string, req *chartInfoModel.SaveChartInfoReq, chartType int) (err error) {
	// 开启事务
	tx := global.MYSQL["data"].Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	// 更新图表信息
	if chartType == 1 {
		sql := ` UPDATE chart_info
			SET
            	edb_info_ids = ?,
				modify_time = NOW(),
            	date_type = ?,
				start_date = ?,
				end_date = ?,
 				left_min = ?,
				left_max = ?,
				right_min = ?,
				right_max = ?
			WHERE chart_info_id = ?`
		err = tx.Exec(sql, edbInfoIdStr, req.DateType, req.StartDate, req.EndDate, req.LeftMin, req.LeftMax, req.RightMin, req.RightMax, req.ChartInfoId).Error
	} else {
		sql := ` UPDATE chart_info
			SET
            	edb_info_ids = ?,
				modify_time = NOW(),
				calendar = ?,
				season_start_date = ?,
				season_end_date = ?,
				left_min = ?,
				left_max = ?,
				right_min = ?,
				right_max = ?
			WHERE chart_info_id = ?`
		err = tx.Exec(sql, edbInfoIdStr, req.Calendar, req.SeasonStartDate, req.SeasonEndDate, req.LeftMin, req.LeftMax, req.RightMin, req.RightMax, req.ChartInfoId).Error
	}
	if err != nil {
		fmt.Println("UPDATE chart_info Err:", err.Error())
		return
	}

	var edbInfoIdArr []string
	mapList := make([]*chartEdbMappingModel.ChartEdbMapping, 0)
	for _, v := range req.ChartEdbInfoList {
		edbInfoIdArr = append(edbInfoIdArr, strconv.Itoa(v.EdbInfoId))
		var count int
		csql := ` SELECT COUNT(1) AS count FROM chart_edb_mapping WHERE chart_info_id = ? AND edb_info_id = ? `
		err = tx.Raw(csql, req.ChartInfoId, v.EdbInfoId).Scan(&count).Error
		if err != nil {
			fmt.Println("QueryRow Err:", err.Error())
			return err
		}
		if count > 0 {
			// 更新指标
			msql := `UPDATE chart_edb_mapping
				SET
                 	modify_time = NOW(),
				 	max_data = ?,
				 	min_data = ?,
				 	is_order = ?,
				 	is_axis = ?,
				 	edb_info_type = ?,
				 	lead_value = ?,
				 	lead_unit = ?,
				 	chart_style = ?,
				 	chart_color = ?,
				 	chart_width = ? 
				WHERE chart_info_id =? AND edb_info_id=? `

			err = tx.Exec(msql, v.MaxData, v.MinData, v.IsOrder, v.IsAxis, v.EdbInfoType, v.LeadValue, v.LeadUnit, v.ChartStyle, v.ChartColor, v.ChartWidth, req.ChartInfoId, v.EdbInfoId).Error
			if err != nil {
				fmt.Println("chart_edb_mapping Err:" + err.Error())
				return err
			}
		} else {
			mapItem := new(chartEdbMappingModel.ChartEdbMapping)
			mapItem.ChartInfoId = req.ChartInfoId
			mapItem.EdbInfoId = v.EdbInfoId
			mapItem.CreateTime = time.Now()
			mapItem.ModifyTime = time.Now()
			timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
			mapItem.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp)
			mapItem.MaxData = v.MaxData
			mapItem.MinData = v.MinData
			mapItem.IsOrder = 0
			if v.IsOrder {
				mapItem.IsOrder = 1
			}
			mapItem.IsAxis = v.IsAxis
			mapItem.EdbInfoType = v.EdbInfoType
			mapItem.LeadValue = v.LeadValue
			mapItem.LeadUnit = v.LeadUnit
			mapItem.ChartStyle = v.ChartStyle
			mapItem.ChartColor = v.ChartColor
			mapItem.ChartWidth = v.ChartWidth
			mapList = append(mapList, mapItem)
		}
	}

	// 批量新增指标
	if len(mapList) > 0 {
		err = tx.Create(mapList).Error
		if err != nil {
			fmt.Println("AddChartEdbMapping Err:" + err.Error())
			return err
		}
	}

	// 清除原图表指标
	if len(edbInfoIdArr) > 0 {
		edbInfoIdStr := strings.Join(edbInfoIdArr, ",")
		if edbInfoIdStr != "" {
			dsql := `DELETE FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id NOT IN(` + edbInfoIdStr + `)`
			err = tx.Exec(dsql, req.ChartInfoId).Error
			if err != nil {
				fmt.Println("delete err:" + err.Error())
				return err
			}
		}
	}

	return
}

// GetChartInfoRefreshData 获取需要刷新的指标
func GetChartInfoRefreshData(chartInfoId int) (baseEdbInfoArr, calculateInfoArr []*edbInfoModel.EdbInfo, err error) {
	sql := ` SELECT b.* FROM chart_edb_mapping AS a
		   INNER JOIN edb_info AS b ON a.edb_info_id=b.edb_info_id 
		   WHERE a.chart_info_id=? `
	edbInfoList := make([]*edbInfoModel.EdbInfo, 0)
	err = global.MYSQL["data"].Raw(sql, chartInfoId).Scan(&edbInfoList).Error
	if err != nil {
		return
	}

	for _, v := range edbInfoList {
		fmt.Println(v.EdbInfoId, v.EdbType)
		if v.EdbType == 1 {
			baseEdbInfoArr = append(baseEdbInfoArr, v)
		} else {
			calculateInfoArr = append(calculateInfoArr, v)
			newBaseEdbInfoArr, newCalculateInfoArr, err := GetChartRefreshEdbInfo(v.EdbInfoId, v.Source, 0)
			if err != nil {
				return baseEdbInfoArr, calculateInfoArr, err
			}
			baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
			calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
		}
	}

	return
}

// GetChartRefreshEdbInfo
func GetChartRefreshEdbInfo(edbInfoId, source, n int) (baseEdbInfoArr, calculateInfoArr []*edbInfoModel.EdbInfo, err error) {
	calculateList, err := GetEdbInfoCalculateMap(edbInfoId, source)
	if err != nil && err != utils.ErrNoRow {
		return
	}
	n++
	for _, item := range calculateList {
		fmt.Println(item.EdbInfoId)
		if item.EdbType == 1 {
			baseEdbInfoArr = append(baseEdbInfoArr, item)
		} else {
			calculateInfoArr = append(calculateInfoArr, item)
			if n > 10 {
				return
			}
			newBaseEdbInfoArr, newCalculateInfoArr, _ := GetChartRefreshEdbInfo(item.EdbInfoId, item.Source, n)
			baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
			calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
		}
	}

	return
}

func GetEdbInfoCalculateMap(edbInfoId, source int) (list []*edbInfoModel.EdbInfo, err error) {
	sql := ` SELECT b.* FROM edb_info_calculate_mapping AS a
			INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
			WHERE a.edb_info_id=? ORDER BY sort ASC `
	err = global.MYSQL["data"].Exec(sql, edbInfoId).Error

	return
}

// SaveChartVisitLog 保存图表访问记录
func SaveChartVisitLog(userInfo user.UserInfo, chartInfo *chartInfoModel.ChartInfoView, myChartClassifyId int) (err error) {
	userId := int(userInfo.UserID)
	companyId := int(userInfo.CompanyID)
	chartInfoId := chartInfo.ChartInfoId
	// 访问记录
	visitLog := new(yb_chart_visit_log.YbChartVisitLog)
	visitLog.CompanyId = companyId
	companyInfo, err := company2.GetByCompanyId(userInfo.CompanyID)
	if err == nil {
		visitLog.CompanyName = companyInfo.CompanyName
	}
	visitLog.UserId = userId
	visitLog.RealName = userInfo.RealName
	visitLog.Mobile = userInfo.Mobile
	visitLog.Email = userInfo.Email
	visitLog.ChartInfoId = chartInfoId
	visitLog.ChartName = chartInfo.ChartName
	visitLog.CreateTime = time.Now().Local()
	visitLog.Create()

	// 每日访问记录,用户/天/图仅记录一次
	if myChartClassifyId > 0 {
		// 今日是否已访问
		nowTime := time.Now().Local()
		startTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)
		endTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 23, 59, 59, 0, time.Local)
		_, tmpErr := yb_chart_daily_visit_log.GetTodayVisitLog(userId, chartInfoId, myChartClassifyId, startTime, endTime)
		if tmpErr == nil {
			return
		}

		myChartClassify, tmpErr := my_chart_classify.GetClassifyById(myChartClassifyId)
		if tmpErr != nil {
			return
		}
		dailyLog := new(yb_chart_daily_visit_log.YbChartDailyVisitLog)
		dailyLog.CompanyId = companyId
		if companyInfo != nil {
			dailyLog.CompanyName = companyInfo.CompanyName
		}
		dailyLog.UserId = userId
		dailyLog.RealName = userInfo.RealName
		dailyLog.Mobile = userInfo.Mobile
		dailyLog.Email = userInfo.Email
		dailyLog.ChartInfoId = chartInfoId
		dailyLog.ChartName = chartInfo.ChartName
		dailyLog.MyChartClassifyId = myChartClassifyId
		dailyLog.MyChartClassifyName = myChartClassify.MyChartClassifyName
		dailyLog.CreateTime = time.Now().Local()
		dailyLog.Create()
	}

	return
}

// RefreshChart 图表刷新
func RefreshChart(chartInfoId int) (err error) {
	var errMsg string
	defer func() {
		if err != nil {
			if global.CONFIG.Serve.RunMode == "release" {
				//go services.SendEmail(utils.APPNAME+"【"+global.CONFIG.Serve.RunMode+"】"+"失败提醒", "RefreshChart:"+errMsg, utils.EmailSendToUsers)
				go alarm_msg.SendAlarmMsg("RefreshChart Err:"+errMsg, 3)
			}
			fmt.Println("RefreshChart Err:" + errMsg)
		}
	}()

	// 获取需要刷新的指标
	baseEdbInfoArr, calculateInfoArr, err := GetChartInfoRefreshData(chartInfoId)
	if err != nil {
		errMsg = "获取需要刷新的指标失败:Err:" + err.Error()
		return
	}

	newBaseEdbInfoArr := make([]*edbInfoModel.EdbInfo, 0)
	baseMap := make(map[int]*edbInfoModel.EdbInfo)
	for _, bv := range baseEdbInfoArr {
		if _, ok := baseMap[bv.EdbInfoId]; !ok {
			newBaseEdbInfoArr = append(newBaseEdbInfoArr, bv)
		}
		baseMap[bv.EdbInfoId] = bv
	}
	newCalculateInfoArr := make([]*edbInfoModel.EdbInfo, 0)
	calculateMap := make(map[int]*edbInfoModel.EdbInfo)
	var calculateArr []int
	for _, bv := range calculateInfoArr {
		if _, ok := calculateMap[bv.EdbInfoId]; !ok {
			newCalculateInfoArr = append(newCalculateInfoArr, bv)
			calculateArr = append(calculateArr, bv.EdbInfoId)
		}
		calculateMap[bv.EdbInfoId] = bv
	}
	sort.Ints(calculateArr)

	// 刷新指标
	var startDate string
	for _, bv := range newBaseEdbInfoArr {
		source := bv.Source
		edbInfoId := bv.EdbInfoId
		edbCode := bv.EdbCode
		startDate = bv.StartDate.Format(utils.FormatDate)
		frequency := bv.Frequency
		if startDate == "0000-00-00" {
			continue
		}
		sTime := bv.EndDate

		var limitDay int
		startDate := ""
		switch frequency {
		case "日度":
			limitDay = utils.DATA_START_REFRESH_LIMIT
		case "周度":
			limitDay = utils.DATA_START_REFRESH_LIMIT * 7
		case "月度":
			limitDay = utils.DATA_START_REFRESH_LIMIT * 30
		case "季度":
			limitDay = utils.DATA_START_REFRESH_LIMIT * 90
		case "年度":
			limitDay = utils.DATA_START_REFRESH_LIMIT * 365
		default:
			limitDay = utils.DATA_START_REFRESH_LIMIT
		}
		startDate = sTime.AddDate(0, 0, -limitDay).Format(utils.FormatDate)

		fmt.Println("source:", source)
		respItem, err := RefreshEdbData(edbInfoId, source, edbCode, startDate)
		if err != nil {
			errMsg = errors.New("RefreshEdbData Err:" + err.Error()).Error()
			return err
		}
		if respItem.Ret != 200 {
			errMsg = errors.New(respItem.ErrMsg + ";EdbCode:" + edbCode).Error()
			return err
		}

		//maxAndMinItem, err := edbDataModel.GetEdbInfoMaxAndMinInfo(source, edbCode)
		//if err != nil {
		//	return err
		//}
		//if maxAndMinItem != nil {
		//	err = edbDataModel.ModifyEdbInfoMaxAndMinInfo(edbInfoId, maxAndMinItem)
		//	if err != nil {
		//		return err
		//	}
		//}
	}

	// 刷新计算指标
	for _, v := range calculateArr {
		edbInfo := calculateMap[v]
		if edbInfo == nil {
			return err
		}
		startDate = edbInfo.StartDate.Format(utils.FormatDate)
		source := edbInfo.Source

		if source == utils.DATA_SOURCE_CALCULATE {
			sTime := edbInfo.EndDate
			startDate = sTime.Format(utils.FormatDate)
		}

		result, err := RefreshEdbCalculateData(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
		if err != nil {
			fmt.Println(v, "RefreshEdbCalculateData err", time.Now())
			errMsg = "RefreshEdbCalculateData Err:" + err.Error()
			return err
		}
		if result.Ret != 200 {
			fmt.Println(v, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
			errMsg = fmt.Sprint(v, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
			return fmt.Errorf("刷新失败")
		}
	}

	return
}
