package data_manage

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

// EditFutureGoodChartEnInfoAndEdbEnInfo 更改商品价格曲线英文信息
func EditFutureGoodChartEnInfoAndEdbEnInfo(chartInfoId int, chartNameEn string, edbInfoId int, edbNameEn, edbUnitEn 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()
		}
	}()

	sql := ` UPDATE  chart_info
			SET
			  chart_name_en =?,
			  modify_time = NOW()
			WHERE chart_info_id = ?`

	_, err = to.Raw(sql, chartNameEn, chartInfoId).Exec()
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}
	var count int
	csql := `SELECT COUNT(1) AS count FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id=? AND source = 1 `
	err = to.Raw(csql, chartInfoId, edbInfoId).QueryRow(&count)
	if err != nil {
		fmt.Println("QueryRow Err:", err.Error())
		return err
	}
	if count > 0 {
		msql := ` UPDATE  edb_info
			SET edb_name_en = ?,
			  unit_en = ?,
			  modify_time = NOW()
			WHERE edb_info_id = ? `
		_, err = to.Raw(msql, edbNameEn, edbUnitEn, edbInfoId).Exec()
		if err != nil {
			fmt.Println("edb_info Err:" + err.Error())
			return err
		}
	}

	return
}

// EditFutureGoodProfitChartEnInfoAndEdbEnInfo 更改商品利润曲线英文信息
func EditFutureGoodProfitChartEnInfoAndEdbEnInfo(chartInfoId int, chartNameEn string, edbInfoId int, edbNameEn, edbUnitEn, profitNameEn 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()
		}
	}()

	sql := ` UPDATE  chart_info
			SET chart_name_en =?,modify_time = NOW()
			WHERE chart_info_id = ?`

	_, err = to.Raw(sql, chartNameEn, chartInfoId).Exec()
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return
	}

	// 更改指标英文信息
	sql = ` UPDATE  edb_info
			SET edb_name_en = ?,unit_en = ?,modify_time = NOW()
			WHERE edb_info_id = ? `
	_, err = to.Raw(sql, edbNameEn, edbUnitEn, edbInfoId).Exec()
	if err != nil {
		fmt.Println("edb_info Err:" + err.Error())
		return
	}

	// 更改指标英文信息
	sql = ` UPDATE  chart_info_future_good_profit
			SET profit_name_en = ?,modify_time = NOW()
			WHERE chart_info_id = ? `
	_, err = to.Raw(sql, profitNameEn, chartInfoId).Exec()
	if err != nil {
		fmt.Println("chart_info_future_good_profit Err:" + err.Error())
		return
	}

	return
}
