package models

import (
	"fmt"
	"hongze/hongze_edb_lib/utils"
	"strconv"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

//钢联

type MysteelChemicalData struct {
	InputValue float64 `orm:"column(value)" description:"值"`
	DataTime   string  `orm:"column(data_time)" description:"日期"`
}

func GetMysteelChemicalDataByCondition(condition string, pars []interface{}) (item []*MysteelChemicalData, err error) {
	sql1 := ` SELECT * FROM base_from_mysteel_chemical_data WHERE 1=1  `
	o := orm.NewOrm()
	if condition != "" {
		sql1 += condition
	}
	sql := `select * from (` + sql1 + ` having 1 order by modify_time DESC ) tmp GROUP BY data_time ORDER BY data_time DESC `
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}

// AddEdbDataFromMysteelChemical 新增钢联指标数据
func AddEdbDataFromMysteelChemical(edbCode string) (err error) {
	o := orm.NewOrm()

	var condition string
	var pars []interface{}

	if edbCode != "" {
		condition += " AND index_code = ? "
		pars = append(pars, edbCode)
	}

	mysteelChemicalDataList, err := GetMysteelChemicalDataByCondition(condition, pars)
	if err != nil {
		return
	}

	dataLen := len(mysteelChemicalDataList)

	existMap := make(map[string]string)
	if dataLen > 0 {
		var isAdd bool
		addSql := ` INSERT INTO edb_data_mysteel_chemical (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
		for i := 0; i < dataLen; i++ {
			item := mysteelChemicalDataList[i]
			eDate := item.DataTime
			sValue := utils.SubFloatToString(item.InputValue, 30)
			if sValue != "" {
				if _, ok := existMap[eDate]; !ok {
					dataTime, err := time.Parse(utils.FormatDate, eDate)
					if err != nil {
						return err
					}
					timestamp := dataTime.UnixNano() / 1e6
					timeStr := fmt.Sprintf("%d", timestamp)
					addSql += GetAddSql("0", edbCode, eDate, timeStr, sValue)
					isAdd = true
				}
			}
			existMap[eDate] = eDate
		}
		if isAdd {
			addSql = strings.TrimRight(addSql, ",")
			utils.FileLog.Info("addSql:" + addSql)
			_, err = o.Raw(addSql).Exec()
			if err != nil {
				return err
			}
		}
	}
	return
}

// RefreshEdbDataFromMysteelChemical 刷新钢联指标数据
func RefreshEdbDataFromMysteelChemical(edbInfoId int, edbCode, startDate string) (err error) {
	source := utils.DATA_SOURCE_MYSTEEL_CHEMICAL
	o := orm.NewOrm()
	if err != nil {
		return
	}
	edbInfoIdStr := strconv.Itoa(edbInfoId)
	//计算数据
	var condition string
	var pars []interface{}

	if edbCode != "" {
		condition += " AND index_code=? "
		pars = append(pars, edbCode)
	}

	if startDate != "" {
		condition += " AND data_time>=? "
		pars = append(pars, startDate)
	}

	mysteelChemicalDataList, err := GetMysteelChemicalDataByCondition(condition, pars)

	var existCondition string
	var existPars []interface{}

	existCondition += " AND edb_info_id=? "
	existPars = append(existPars, edbInfoId)
	if startDate != "" {
		existCondition += " AND data_time>=? "
		existPars = append(existPars, startDate)
	}
	//获取指标所有数据
	existList, err := GetEdbDataByCondition(source, existCondition, existPars)
	if err != nil {
		return err
	}
	existMap := make(map[string]*EdbInfoSearchData)
	for _, v := range existList {
		existMap[v.DataTime] = v
	}

	addSql := ` INSERT INTO edb_data_mysteel_chemical(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	var isAdd bool
	addMap := make(map[string]string)
	for _, v := range mysteelChemicalDataList {
		item := v
		eDate := item.DataTime
		sValue := utils.SubFloatToString(item.InputValue, 30)

		if findItem, ok := existMap[v.DataTime]; !ok {
			if sValue != "" {
				dataTime, err := time.Parse(utils.FormatDate, eDate)
				if err != nil {
					return err
				}
				timestamp := dataTime.UnixNano() / 1e6
				timeStr := fmt.Sprintf("%d", timestamp)
				saveValue := sValue

				if _, addOk := addMap[eDate]; !addOk {
					addSql += GetAddSql(edbInfoIdStr, edbCode, eDate, timeStr, saveValue)
					isAdd = true
				}
			}
		} else {
			if findItem != nil && utils.SubFloatToString(findItem.Value, 30) != sValue {
				err = ModifyEdbDataById(source, findItem.EdbDataId, sValue)
				if err != nil {
					return err
				}
			}
		}
		addMap[v.DataTime] = v.DataTime
	}
	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		_, err = o.Raw(addSql).Exec()
		if err != nil {
			return err
		}
	}
	return
}
