package models

import (
	"eta/eta_index_lib/models/supply_analysis"
	"eta/eta_index_lib/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strconv"
	"strings"
	"time"
)

// StockPlantEdbdata 存量装置数据
type StockPlantEdbdata struct {
	VarietyEdbId string    `orm:"column(variety_edb_id);pk" description:"指标编码"`
	DataTime     string    `orm:"column(data_time)" description:"日期"`
	Value        string    `orm:"column(value)" description:"值"`
	ModifyTime   time.Time `orm:"column(modify_time)" description:"修改时间"`
}

func GetStockPlantEdbDataByCondition(condition string, pars []interface{}) (item []*StockPlantEdbdata, err error) {
	sql := ` SELECT  * FROM base_from_stock_plant_data WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY data_time DESC `
	o := orm.NewOrm()
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}

// RefreshEdbDataFromStockPlant 刷新存量装置数据
func RefreshEdbDataFromStockPlant(edbInfoId int, edbCode, startDate string) (err error) {
	source := utils.DATA_SOURCE_STOCK_PLANT
	subSource := utils.DATA_SUB_SOURCE_EDB

	o := orm.NewOrm()
	if err != nil {
		return
	}
	edbInfoIdStr := strconv.Itoa(edbInfoId)
	//计算数据
	var condition string
	var pars []interface{}

	// 获取供应分析的指标信息
	varietyEdbInfo, err := supply_analysis.GetVarietyEdbInfoByEdbInfoId(edbInfoId)
	if err != nil {
		return
	}

	// 获取基础库的指标数据
	condition += " AND variety_edb_id=? "
	pars = append(pars, varietyEdbInfo.VarietyEdbId)

	if startDate != "" {
		condition += " AND data_time >=? "
		pars = append(pars, startDate)
	} else {
		condition += " AND data_time != ? "
		pars = append(pars, `0000-00-00`)
	}

	baseDataList, err := GetStockPlantEdbDataByCondition(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, subSource, 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_stock_plant (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	var isAdd bool
	manualMap := make(map[string]*StockPlantEdbdata)
	for _, v := range baseDataList {
		item := v
		//fmt.Println("Item:", item.Dt, item.Close, item.TradeCode, item.ModifyTime)
		if findItem, ok := existMap[v.DataTime]; !ok {
			eDate := item.DataTime
			sValue := item.Value

			dataTime, err := time.Parse(utils.FormatDate, eDate)
			if err != nil {
				return err
			}
			timestamp := dataTime.UnixNano() / 1e6
			timeStr := fmt.Sprintf("%d", timestamp)

			addSql += GetAddSql(edbInfoIdStr, edbCode, eDate, timeStr, sValue)
			isAdd = true
		} else {
			if findItem != nil && utils.SubFloatToString(findItem.Value, 4) != item.Value {
				err = ModifyEdbDataById(source, subSource, findItem.EdbDataId, item.Value)
				if err != nil {
					return err
				}
			}
		}
		manualMap[v.DataTime] = v
	}
	// 删除不存在的日期数据
	for _, v := range existList {
		if _, ok := manualMap[v.DataTime]; !ok {
			go DeleteEdbDataById(source, subSource, v.EdbDataId)
		}
	}

	// 将数据入库
	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		_, err = o.Raw(addSql).Exec()
		if err != nil {
			fmt.Println("RefreshAllEdbDataByStockPlant add Err", err.Error())
			return
		}
	}
	return
}
