package future_good

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// ChartInfoFutureGoodProfit 商品利润图表-扩展信息
type ChartInfoFutureGoodProfit struct {
	ChartInfoId  int       `orm:"column(chart_info_id);pk" description:"商品利润图表ID(chart_info表source=5的)"`
	ProfitName   string    `description:"利润名称"`
	ProfitNameEn string    `description:"利润英文名称"`
	XValue       string    `description:"X轴数据值"`
	YValue       string    `description:"Y轴数据值"`
	CreateTime   time.Time `description:"创建时间"`
	ModifyTime   time.Time `description:"更新时间"`
}

type CorrelationInfo struct {
	LeadValue       int    `description:"领先值"`
	LeadUnit        string `description:"领先单位"`
	CalculateValue  int    `description:"计算窗口"`
	CalculateUnit   string `description:"计算频度"`
	StartDate       string `description:"开始日期"`
	EndDate         string `description:"结束日期"`
	EdbInfoIdFirst  int    `description:"A指标ID"`
	EdbInfoIdSecond int    `description:"B指标ID"`
	PeriodData      string `description:"X轴-期数数据"`
	CorrelationData string `description:"Y轴-商品利润系数"`
}

func (m *ChartInfoFutureGoodProfit) TableName() string {
	return "chart_info_future_good_profit"
}

func (m *ChartInfoFutureGoodProfit) Create() (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Insert(m)
	if err != nil {
		return
	}
	//m.CorrelationChartInfoId = int(id)
	return
}

func (m *ChartInfoFutureGoodProfit) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, cols...)
	return
}

func (m *ChartInfoFutureGoodProfit) Delete() (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE chart_info_id = ? LIMIT 1`, m.TableName())
	_, err = o.Raw(sql, m.ChartInfoId).Exec()
	return
}

func (m *ChartInfoFutureGoodProfit) GetItemById(id int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE chart_info_id = ? LIMIT 1`, m.TableName())
	err = o.Raw(sql, id).QueryRow(&m)
	return
}

func (m *ChartInfoFutureGoodProfit) GetItemByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s LIMIT 1`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&m)
	return
}

func (m *ChartInfoFutureGoodProfit) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ChartInfoFutureGoodProfit, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// CreateChartInfoFutureGoodProfitAndEdb 新增商品利润图表
func CreateChartInfoFutureGoodProfitAndEdb(chartInfo *data_manage.ChartInfo, edbMappingList []*data_manage.ChartEdbMapping, chartInfoFutureGoodProfit *ChartInfoFutureGoodProfit) (err error) {
	o := orm.NewOrmUsingDB("data")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 新增图表信息
	newId, err := tx.Insert(chartInfo)
	if err != nil {
		return
	}
	// 指标mapping
	chartInfo.ChartInfoId = int(newId)
	chartInfoId := int(newId)
	if len(edbMappingList) > 0 {
		for i := range edbMappingList {
			edbMappingList[i].ChartInfoId = chartInfoId
		}
		_, err = tx.InsertMulti(len(edbMappingList), edbMappingList)
		if err != nil {
			return
		}
	}
	// 商品利润信息
	chartInfoFutureGoodProfit.ChartInfoId = chartInfoId
	if _, err = tx.Insert(chartInfoFutureGoodProfit); err != nil {
		return
	}
	return
}

// EditFutureGoodChartInfoAndMapping 修改商品利润图表
func EditFutureGoodChartInfoAndMapping(chartInfo *data_manage.ChartInfo, newEdbMappingList []*data_manage.ChartEdbMapping, chartInfoFutureGoodProfit *ChartInfoFutureGoodProfit, chartItemUpdateCol, extraUpdateCol []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 更改表信息
	_, err = to.Update(chartInfo, chartItemUpdateCol...)
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}

	// 更改扩展图表信息
	_, err = to.Update(chartInfoFutureGoodProfit, extraUpdateCol...)
	if err != nil {
		fmt.Println("UPDATE  chart_info_future_good_profit Err:", err.Error())
		return err
	}

	// 更改指标关联信息
	chartEdbMappingIdList := make([]string, 0)
	for _, v := range newEdbMappingList {
		// 查询该指标是否存在,如果存在的话,那么就去修改,否则新增
		var tmpChartEdbMapping *data_manage.ChartEdbMapping
		csql := `SELECT *  FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id=? AND source = ? `
		err = to.Raw(csql, chartInfo.ChartInfoId, v.EdbInfoId, v.Source).QueryRow(&tmpChartEdbMapping)
		if err != nil && err.Error() != utils.ErrNoRow() {
			fmt.Println("QueryRow Err:", err.Error())
			return err
		}
		if tmpChartEdbMapping != nil {
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(tmpChartEdbMapping.ChartEdbMappingId))
		} else {
			mapItem := new(data_manage.ChartEdbMapping)
			mapItem.ChartInfoId = chartInfo.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 + "_" + strconv.Itoa(v.EdbInfoId))
			mapItem.IsOrder = true
			mapItem.IsAxis = 1
			mapItem.EdbInfoType = 1
			mapItem.Source = v.Source
			tmpId, err := to.Insert(mapItem)
			if err != nil {
				fmt.Println("AddChartEdbMapping Err:" + err.Error())
				return err
			}
			mapItem.ChartEdbMappingId = int(tmpId)
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(mapItem.ChartEdbMappingId))
		}
	}
	if len(chartEdbMappingIdList) > 0 {
		chartEdbMappingIdStr := strings.Join(chartEdbMappingIdList, ",")
		dsql := `DELETE FROM chart_edb_mapping WHERE chart_info_id=? AND chart_edb_mapping_id NOT IN(` + chartEdbMappingIdStr + `)`
		_, err = to.Raw(dsql, chartInfo.ChartInfoId).Exec()
		if err != nil {
			fmt.Println("delete err:" + err.Error())
			return err
		}
	}
	return
}
