package models

import (
	"encoding/json"
	"errors"
	"eta/eta_index_lib/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/shopspring/decimal"
	"strconv"
	"strings"
	"time"
)

// AddCalculateKszs 扩散指数
func AddCalculateKszs(req *EdbInfoCalculateBatchSaveReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("AddCalculateKszs,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	if req.EdbInfoId > 0 {
		err = errors.New("无法新增")
		return
	}

	edbInfo = new(EdbInfo)
	edbInfo.Source = utils.DATA_SOURCE_CALCULATE_KSZS
	edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_KSZS
	edbInfo.EdbCode = edbCode
	edbInfo.EdbName = req.EdbName
	edbInfo.EdbNameSource = req.EdbName
	edbInfo.Frequency = req.Frequency
	edbInfo.Unit = req.Unit
	edbInfo.ClassifyId = req.ClassifyId
	edbInfo.SysUserId = sysUserId
	edbInfo.SysUserRealName = sysUserRealName
	edbInfo.CreateTime = time.Now()
	edbInfo.ModifyTime = time.Now()
	edbInfo.UniqueCode = uniqueCode
	edbInfo.CalculateFormula = req.Formula
	edbInfo.EdbNameEn = req.EdbName
	edbInfo.UnitEn = req.Unit
	edbInfo.EdbType = 2
	newEdbInfoId, tmpErr := to.Insert(edbInfo)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	edbInfo.EdbInfoId = int(newEdbInfoId)

	//关联关系
	tagMap := make(map[string]int)
	relationEdbInfoList := make([]*EdbInfo, 0)
	calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
	for _, v := range req.EdbInfoIdArr {
		tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)

		calculateMappingItem := new(EdbInfoCalculateMapping)
		calculateMappingItem.CreateTime = time.Now()
		calculateMappingItem.ModifyTime = time.Now()
		calculateMappingItem.Sort = 1
		calculateMappingItem.EdbCode = edbCode
		calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
		calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
		calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
		calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
		calculateMappingItem.FromSource = tmpEdbInfo.Source
		calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
		calculateMappingItem.FromTag = v.FromTag
		calculateMappingItem.Source = edbInfo.Source
		calculateMappingItem.SourceName = edbInfo.SourceName
		calculateMappingItem.FromSubSource = edbInfo.SubSource
		calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)

		tagMap[v.FromTag] = v.EdbInfoId
	}
	_, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
	if err != nil {
		return
	}

	//计算数据
	err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)

	return
}

// EditCalculateKszs 修改扩散指数数据
func EditCalculateKszs(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("EditCalculateKszs,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	//修改指标信息
	edbInfo.EdbName = req.EdbName
	edbInfo.EdbNameSource = req.EdbName
	edbInfo.Frequency = req.Frequency
	edbInfo.Unit = req.Unit
	edbInfo.ClassifyId = req.ClassifyId
	edbInfo.CalculateFormula = req.Formula
	edbInfo.EdbNameEn = req.EdbNameEn
	edbInfo.UnitEn = req.UnitEn
	edbInfo.ModifyTime = time.Now()
	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
	if err != nil {
		return
	}

	//删除，计算指标关联的，基础指标的关联关系
	sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
	if err != nil {
		err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
		return
	}
	//清空原有数据
	tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
	sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
	if err != nil {
		return
	}

	//关联关系
	tagMap := make(map[string]int)
	relationEdbInfoList := make([]*EdbInfo, 0)
	calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
	for _, v := range req.EdbInfoIdArr {
		tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)

		calculateMappingItem := new(EdbInfoCalculateMapping)
		calculateMappingItem.CreateTime = time.Now()
		calculateMappingItem.ModifyTime = time.Now()
		calculateMappingItem.Sort = 1
		calculateMappingItem.EdbCode = edbInfo.EdbCode
		calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
		calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
		calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
		calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
		calculateMappingItem.FromSource = tmpEdbInfo.Source
		calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
		calculateMappingItem.FromTag = v.FromTag
		calculateMappingItem.Source = edbInfo.Source
		calculateMappingItem.SourceName = edbInfo.SourceName
		calculateMappingItem.FromSubSource = edbInfo.SubSource
		calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)

		tagMap[v.FromTag] = v.EdbInfoId
	}
	_, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
	if err != nil {
		return
	}

	//计算数据
	err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)

	return
}

func RefreshAllCalculateKszs(edbInfo *EdbInfo) (err error) {
	edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
	if err != nil {
		return
	}
	tagMap := make(map[string]int)
	relationEdbInfoList := make([]*EdbInfo, 0)
	for _, v := range edbInfoCalculateDetailList {
		tagMap[v.FromTag] = v.FromEdbInfoId
		fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
		relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
	}
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("RefreshAllCalculateKszs,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 计算数据
	err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)

	return
}

// KszsConfig 扩散指数配置
type KszsConfig struct {
	DateType  int      `description:"扩散指标日期；1：全部指标日期并集;2:部分指标日期并集"`
	CheckList []string `description:"选中的数据,A,B,C"`
}

// refreshAllCalculateKszs 刷新扩散指数数据
func refreshAllCalculateKszs(to orm.TxOrmer, edbInfoId, source, subSource int, relationEdbInfoList []*EdbInfo, edbCode, calculateFormula string, tagMap map[string]int) (err error) {
	edbInfoIdStr := strconv.Itoa(edbInfoId)
	tableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_KSZS, utils.DATA_SUB_SOURCE_EDB)

	// 获取扩散指标关联的指标id
	checkEdbInfoIdMap := make(map[int]int)
	{
		var config KszsConfig
		err = json.Unmarshal([]byte(calculateFormula), &config)
		if err != nil {
			return
		}
		if config.DateType == 1 {
			for _, tmpEdbInfoId := range tagMap {
				checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
			}
		} else {
			for _, v := range config.CheckList {
				if tmpEdbInfoId, ok := tagMap[v]; ok {
					checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
				}
			}
		}
	}

	//获取扩散指数指标所有数据
	existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
	if err != nil {
		return
	}
	//计算指标的map
	existDataMap := make(map[string]*EdbData, 0)
	removeDateMap := make(map[string]string)
	for _, v := range existDataList {
		existDataMap[v.DataTime] = v
		removeDateMap[v.DataTime] = ``
	}

	//获取来源指标的数据
	relationEdbDataMap := make(map[int]map[string]float64)
	// 获取选择指标的 需要数据的 开始日期和结束日期
	var startDate, endDate time.Time
	for _, v := range relationEdbInfoList {
		tmpDataList, tmpErr := GetEdbDataListAllByTo(to, v.Source, v.SubSource, FindEdbDataListAllCond{
			EdbInfoId: v.EdbInfoId,
		}, 1)
		if tmpErr != nil {
			err = tmpErr
			return err
		}
		if tmpDataList != nil {
			if _, ok2 := checkEdbInfoIdMap[v.EdbInfoId]; ok2 {
				lenTmpDataList := len(tmpDataList)
				if lenTmpDataList > 0 {
					tmpStartTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[0].DataTime, time.Local)
					tmpEndTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[lenTmpDataList-1].DataTime, time.Local)

					if startDate.IsZero() || tmpStartTime.Before(startDate) {
						startDate = tmpStartTime
					}

					if tmpEndTime.IsZero() || tmpEndTime.After(endDate) {
						endDate = tmpEndTime
					}
				}
			}
			// 用上期的数据补充当期的数据处理
			handleDataMap := make(map[string]float64)
			err = HandleDataByPreviousData(tmpDataList, handleDataMap)
			if err != nil {
				return
			}
			relationEdbDataMap[v.EdbInfoId] = handleDataMap
		}
	}

	addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	var isAdd bool

	for currDate := startDate.AddDate(0, 0, 1); !currDate.After(endDate); currDate = currDate.AddDate(0, 0, 1) {
		currDateStr := currDate.Format(utils.FormatDate)

		//环差指数列表
		tmpValList := make([]float64, 0)
		for _, dataMap := range relationEdbDataMap {
			currVal, ok := dataMap[currDateStr]
			if !ok {
				continue
			}

			perVal, ok := dataMap[currDate.AddDate(0, 0, -1).Format(utils.FormatDate)]
			if !ok {
				continue
			}

			var tmpVal float64
			if currVal > perVal {
				tmpVal = 1
			} else if currVal == perVal {
				tmpVal = 0.5
			} else {
				tmpVal = 0
			}
			tmpValList = append(tmpValList, tmpVal)
		}

		lenTmpValList := len(tmpValList)
		if lenTmpValList <= 0 {
			continue
		}

		currValDeci := decimal.NewFromFloat(0)
		for _, tmpVal := range tmpValList {
			currValDeci = currValDeci.Add(decimal.NewFromFloat(tmpVal))
		}
		currVal, _ := currValDeci.Div(decimal.NewFromInt(int64(lenTmpValList))).Round(4).Float64()

		// 判断扩散指数指标是否存在数据
		if existData, ok := existDataMap[currDateStr]; ok {
			// 处理扩散指数数据的值
			existValStr := existData.Value
			existValDeci, tmpErr := decimal.NewFromString(existValStr)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existVal, _ := existValDeci.Round(4).Float64()
			// 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
			if existVal != currVal {
				err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
				if err != nil {
					return err
				}
			}
		} else {
			// 直接入库
			timestamp := currDate.UnixNano() / 1e6
			timestampStr := fmt.Sprintf("%d", timestamp)
			addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
			isAdd = true
		}

		delete(removeDateMap, currDateStr)
	}

	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		_, err = to.Raw(addSql).Exec()
	}

	// 移除不存在的日期数据
	if len(removeDateMap) > 0 {
		removeDateList := make([]string, 0) //需要移除的日期
		for k := range removeDateMap {
			removeDateList = append(removeDateList, k)
		}
		removeDateStr := strings.Join(removeDateList, `","`)
		removeDateStr = `"` + removeDateStr + `"`
		sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
		_, err = to.Raw(sql, edbInfoId).Exec()
		if err != nil {
			err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
			return
		}
	}

	return
}
