package data_manage

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/nosixtools/solarlunar"
)

func GetEdbDataQuarterCount(edbInfoId int) (count int, err error) {
	hsql := `SELECT COUNT(1) AS count FROM edb_data_quarter WHERE edb_info_id=? `
	err = global.DmSQL["data"].Raw(hsql, edbInfoId).Scan(&count).Error

	return
}

// 指标季度数据计算
func AddCalculateQuarter(edbInfoId, source int, edbCode string) (err error) {
	to := global.DmSQL["data"].Begin()
	defer func() {
		if err != nil {
			fmt.Println("Err:", err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	edbInfoIdStr := strconv.Itoa(edbInfoId)
	fmt.Println(edbInfoIdStr)
	//计算数据
	var condition string
	var pars []interface{}
	condition += " AND edb_info_id=? "
	pars = append(pars, edbInfoId)
	dataList, err := GetAllEdbDataListData(edbInfoId, source, utils.DATA_SUB_SOURCE_EDB, "")
	if err != nil {
		return err
	}

	var yearArr []int
	yearMap := make(map[int]int)
	dataMap := make(map[string]*EdbData)
	for _, v := range dataList {
		//日其中获取年
		itemDate, err := time.Parse(utils.FormatDate, v.DataTime)
		if err != nil {
			return err
		}
		year := itemDate.Year()
		if _, ok := yearMap[year]; !ok {
			yearArr = append(yearArr, year)
			yearMap[year] = year
		}
		dataMap[v.DataTime] = v
	}
	sort.Sort(sort.Reverse(sort.IntSlice(yearArr)))
	addSql := ` INSERT INTO edb_data_quarter(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
	var isAdd bool
	fmt.Println(yearArr)

	for _, yv := range yearArr {
		currentYear := yv
		hsql := `SELECT * FROM holiday WHERE year=? `
		currentHolidayObj := new(Holiday)
		err = to.Raw(hsql, currentYear).Scan(&currentHolidayObj).Error
		if err != nil {
			fmt.Println("get holiday err:" + err.Error())
			return err
		}
		cjDate := currentHolidayObj.HolidayDate
		fmt.Println("year:", yv, "cjDate:", cjDate)
		existMap := make(map[string]string)

		for i := 1; i <= 70; i++ {
			preDate := cjDate.Format(utils.FormatDate)
			fmt.Println("year:", yv, "preDate:", preDate, "i:", i)
			if findItem, ok := dataMap[preDate]; ok {
				timestamp := currentHolidayObj.HolidayDate.UnixNano() / 1e6
				timestampStr := fmt.Sprintf("%d", timestamp)
				if _, exist := existMap[preDate]; !exist {
					valStr := utils.SubFloatToString(findItem.Value, 4)
					addSql += GetAddSql(edbInfoIdStr, edbCode, preDate, timestampStr, valStr)
					isAdd = true
				}
			}
			cjDate = cjDate.AddDate(0, 0, -1)
		}
		cjDate = currentHolidayObj.HolidayDate
		for i := 1; i <= 70; i++ {
			nextDate := cjDate.Format(utils.FormatDate)
			fmt.Println("year:", yv, "nextDate:", nextDate, "i:", i)
			if findItem, ok := dataMap[nextDate]; ok {
				timestamp := currentHolidayObj.HolidayDate.UnixNano() / 1e6
				timestampStr := fmt.Sprintf("%d", timestamp)
				if _, exist := existMap[nextDate]; !exist {
					valStr := utils.SubFloatToString(findItem.Value, 4)
					addSql += GetAddSql(edbInfoIdStr, edbCode, nextDate, timestampStr, valStr)
					isAdd = true
				}
			}
			cjDate = cjDate.AddDate(0, 0, +1)
		}
	}
	fmt.Println("isAdd", isAdd)
	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		utils.FileLog.Info(addSql)
		err = to.Exec(addSql).Error
		fmt.Println("err:", err)
		if err != nil {
			return err
		}
	}
	return
}

// 指标季度数据计算(公历转农历)
func AddCalculateQuarterV4(dataList []*EdbDataList) (result *EdbDataResult, err error) {
	var errMsg string
	defer func() {
		if errMsg != "" {
			fmt.Println("errMsg:", errMsg)
		}
	}()

	endDate := dataList[len(dataList)-1].DataTime
	endDateForm, err := time.Parse(utils.FormatDate, endDate)
	if err != nil {
		return result, err
	}
	thisMonth := int(endDateForm.Month())

	result = new(EdbDataResult)
	var yearArr []int
	yearMap := make(map[int]int)
	var cureentDate time.Time
	if thisMonth < 11 {
		for k, v := range dataList {
			dateTime, err := time.Parse(utils.FormatDate, v.DataTime)
			if err != nil {
				errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
				return result, err
			}
			if k == len(dataList)-1 {
				cureentDate = dateTime
			}
			year := dateTime.Year()
			if _, ok := yearMap[year]; !ok {
				yearArr = append(yearArr, year)
			}
			yearMap[year] = year
		}
	} else {
		for k, v := range dataList {
			dateTime, err := time.Parse(utils.FormatDate, v.DataTime)
			if err != nil {
				errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
				return result, err
			}
			if k == len(dataList)-1 {
				cureentDate = dateTime
			}
			year := dateTime.Year() + 1
			if _, ok := yearMap[year]; !ok {
				yearArr = append(yearArr, year)
			}
			yearMap[year] = year
		}
	}
	//排序
	fmt.Println("yearArr:", yearArr)
	thisYear := cureentDate.Year()
	//thisMonth := int(cureentDate.Month())

	fmt.Println("thisMonth:", thisMonth)
	for ky, vy := range yearArr {
		fmt.Println("line 432:", ky, vy, thisYear, thisMonth)
		if thisMonth < 11 {
			currentYearCjnl := strconv.Itoa(thisYear) + "-01-01"               //当前年份春节农历
			currentYearCjgl := solarlunar.LunarToSolar(currentYearCjnl, false) //当前年份春节公历
			currentYearCjglDate, err := time.Parse(utils.FormatDate, currentYearCjgl)
			if err != nil {
				errMsg = "生成当前春节失败,Err:" + err.Error()
				return result, err
			}

			preYear := vy
			preYearCjnl := strconv.Itoa(preYear) + "-01-01"            //之前年份春节农历
			preYearCjgl := solarlunar.LunarToSolar(preYearCjnl, false) //之前年份春节公历
			preYearCjglDate, err := time.Parse(utils.FormatDate, preYearCjgl)
			if err != nil {
				errMsg = "生成历史年份春节失败,Err:" + err.Error()
				return result, err
			}
			day := currentYearCjglDate.Sub(preYearCjglDate).Hours() / float64(24)

			fmt.Println("day:", day, currentYearCjglDate, preYearCjglDate)

			items := new(EdbDataItems)
			items.BetweenDay = int(day) //公历日期换算成农历,需要减除的天数
			items.Year = preYear
			for _, v := range dataList {
				dateTime, err := time.Parse(utils.FormatDate, v.DataTime)
				if err != nil {
					errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
					return result, err
				}
				newDate := dateTime.AddDate(0, 0, int(day))
				selectDateStr := strconv.Itoa(thisYear) + "-11" + "-30"
				selectDate, _ := time.Parse(utils.FormatDate, selectDateStr)
				if newDate.Before(selectDate) || newDate == selectDate {
					timestamp := newDate.UnixNano() / 1e6
					item := new(EdbDataList)
					item.DataTime = newDate.Format(utils.FormatDate)
					item.EdbInfoId = v.EdbInfoId
					item.Value = v.Value
					item.EdbDataId = v.EdbDataId
					item.DataTimestamp = timestamp
					items.Items = append(items.Items, item)
				}
			}
			result.List = append(result.List, items)
		} else {
			nextYear := thisYear + 1
			nextYearCjnl := strconv.Itoa(nextYear) + "-01-01"            //当前年份春节农历
			nextYearCjgl := solarlunar.LunarToSolar(nextYearCjnl, false) //当前年份春节公历

			nextYearCjglDate, err := time.Parse(utils.FormatDate, nextYearCjgl)
			if err != nil {
				errMsg = "生成当前春节失败,Err:" + err.Error()
				return result, err
			}
			preYear := vy
			preYearCjnl := strconv.Itoa(preYear) + "-01-01"            //之前年份春节农历
			preYearCjgl := solarlunar.LunarToSolar(preYearCjnl, false) //之前年份春节公历
			preYearCjglDate, err := time.Parse(utils.FormatDate, preYearCjgl)
			if err != nil {
				errMsg = "生成历史年份春节失败,Err:" + err.Error()
				return result, err
			}
			day := nextYearCjglDate.Sub(preYearCjglDate).Hours() / float64(24)

			fmt.Println("day:", day, nextYearCjglDate, preYearCjglDate)

			items := new(EdbDataItems)
			items.BetweenDay = int(day) //公历日期换算成农历,需要减除的天数
			items.Year = preYear - 1
			fmt.Println("preYear:", preYear, "ky:", ky, "yearArrLen:", len(yearArr))
			if ky+1 < len(yearArr) {
				for _, v := range dataList {
					dateTime, err := time.Parse(utils.FormatDate, v.DataTime)
					if err != nil {
						errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
						return result, err
					}
					newDate := dateTime.AddDate(0, 0, int(day))
					selectDateStr := strconv.Itoa(nextYear) + "-05" + "-31"
					selectDate, _ := time.Parse(utils.FormatDate, selectDateStr)

					if newDate.Before(selectDate) || newDate == selectDate {
						timestamp := newDate.UnixNano() / 1e6
						item := new(EdbDataList)
						item.DataTime = newDate.Format(utils.FormatDate)
						item.EdbInfoId = v.EdbInfoId
						item.Value = v.Value
						item.EdbDataId = v.EdbDataId
						item.DataTimestamp = timestamp
						items.Items = append(items.Items, item)
					}
				}
				result.List = append(result.List, items)
			} else {
				for _, v := range dataList {
					dateTime, err := time.Parse(utils.FormatDate, v.DataTime)
					if err != nil {
						errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
						return result, err
					}
					timestamp := dateTime.UnixNano() / 1e6
					item := new(EdbDataList)
					item.DataTime = dateTime.Format(utils.FormatDate)
					item.EdbInfoId = v.EdbInfoId
					item.Value = v.Value
					item.EdbDataId = v.EdbDataId
					item.DataTimestamp = timestamp
					items.Items = append(items.Items, item)
				}
				result.List = append(result.List, items)
			}
		}
	}
	return
}

// AddCalculateQuarterV6 指标季度数据计算(季节性图表)
func AddCalculateQuarterV6(dataList []*EdbDataList) (result *EdbDataResult, err error) {
	var errMsg string
	defer func() {
		if errMsg != "" {
			fmt.Println("errMsg:", errMsg)
		}
	}()

	endDate := dataList[len(dataList)-1].DataTime
	endDateForm, err := time.Parse(utils.FormatDate, endDate)
	if err != nil {
		return result, err
	}
	thisMonth := int(endDateForm.Month())

	result = new(EdbDataResult)
	var yearArr []int
	yearMap := make(map[int]int)
	var cureentDate time.Time
	if thisMonth < 11 {
		for k, v := range dataList {
			dateTime, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
			if err != nil {
				errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
				return result, err
			}
			if k == len(dataList)-1 {
				cureentDate = dateTime
			}
			year := dateTime.Year()
			if _, ok := yearMap[year]; !ok {
				yearArr = append(yearArr, year)
			}
			yearMap[year] = year
		}
	} else {
		for k, v := range dataList {
			dateTime, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
			if err != nil {
				errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
				return result, err
			}
			if k == len(dataList)-1 {
				cureentDate = dateTime
			}
			year := dateTime.Year() + 1
			if _, ok := yearMap[year]; !ok {
				yearArr = append(yearArr, year)
			}
			yearMap[year] = year
		}
	}
	//排序
	thisYear := cureentDate.Year()
	for _, vy := range yearArr {
		if thisMonth < 11 {
			currentYearCjnl := strconv.Itoa(thisYear) + "-01-01"               //当前年份春节农历
			currentYearCjgl := solarlunar.LunarToSolar(currentYearCjnl, false) //当前年份春节公历
			currentYearCjglDate, err := time.ParseInLocation(utils.FormatDate, currentYearCjgl, time.Local)
			if err != nil {
				errMsg = "生成当前春节失败,Err:" + err.Error()
				return result, err
			}

			preYear := vy
			preYearCjnl := strconv.Itoa(preYear) + "-01-01"            //之前年份春节农历
			preYearCjgl := solarlunar.LunarToSolar(preYearCjnl, false) //之前年份春节公历
			preYearCjglDate, err := time.ParseInLocation(utils.FormatDate, preYearCjgl, time.Local)
			if err != nil {
				errMsg = "生成历史年份春节失败,Err:" + err.Error()
				return result, err
			}
			day := currentYearCjglDate.Sub(preYearCjglDate).Hours() / float64(24)

			fmt.Println("day:", day, currentYearCjglDate, preYearCjglDate)

			items := new(EdbDataItems)
			items.BetweenDay = int(day) //公历日期换算成农历,需要减除的天数
			items.Year = preYear
			for _, v := range dataList {
				dateTime, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
				if err != nil {
					errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
					return result, err
				}
				newDate := dateTime.AddDate(0, 0, int(day))
				timestamp := newDate.UnixNano() / 1e6
				item := new(EdbDataList)
				item.DataTime = newDate.Format(utils.FormatDate)
				item.EdbInfoId = v.EdbInfoId
				item.Value = v.Value
				item.EdbDataId = v.EdbDataId
				item.DataTimestamp = timestamp
				items.Items = append(items.Items, item)
			}
			result.List = append(result.List, items)
		} else {
			nextYear := thisYear + 1
			nextYearCjnl := strconv.Itoa(nextYear) + "-01-01"            //当前年份春节农历
			nextYearCjgl := solarlunar.LunarToSolar(nextYearCjnl, false) //当前年份春节公历

			nextYearCjglDate, err := time.ParseInLocation(utils.FormatDate, nextYearCjgl, time.Local)
			if err != nil {
				errMsg = "生成当前春节失败,Err:" + err.Error()
				return result, err
			}
			preYear := vy
			preYearCjnl := strconv.Itoa(preYear) + "-01-01"            //之前年份春节农历
			preYearCjgl := solarlunar.LunarToSolar(preYearCjnl, false) //之前年份春节公历
			preYearCjglDate, err := time.ParseInLocation(utils.FormatDate, preYearCjgl, time.Local)
			if err != nil {
				errMsg = "生成历史年份春节失败,Err:" + err.Error()
				return result, err
			}
			day := nextYearCjglDate.Sub(preYearCjglDate).Hours() / float64(24)

			items := new(EdbDataItems)
			items.BetweenDay = int(day) //公历日期换算成农历,需要减除的天数
			items.Year = preYear
			for _, v := range dataList {
				dateTime, err := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
				if err != nil {
					errMsg = "time.Parse Err:" + err.Error() + ";DataTime:" + v.DataTime
					return result, err
				}
				newDate := dateTime.AddDate(0, 0, int(day))
				timestamp := newDate.UnixNano() / 1e6
				item := new(EdbDataList)
				item.DataTime = newDate.Format(utils.FormatDate)
				item.EdbInfoId = v.EdbInfoId
				item.Value = v.Value
				item.EdbDataId = v.EdbDataId
				item.DataTimestamp = timestamp
				items.Items = append(items.Items, item)
			}
			result.List = append(result.List, items)
		}
	}
	return
}

type EdbDataItems struct {
	Items                []*EdbDataList
	Year                 int
	BetweenDay           int   `json:"-" description:"公历与农历之间相差的天数"`
	CuttingDataTimestamp int64 `description:"切割的时间戳"`
}

type EdbDataResult struct {
	List []*EdbDataItems
}