package cross_variety

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/cross_variety/request"
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// ChartInfoCrossVariety
// @Description: 跨品种分析配置表
type ChartInfoCrossVariety struct {
	Id             int       `orm:"column(id);pk"`
	ChartInfoId    int       `description:"图表id"`
	ChartXTagId    int       `description:"X轴的标签ID"`
	ChartYTagId    int       `description:"X轴的标签ID"`
	CalculateValue int       `description:"计算窗口"`
	CalculateUnit  string    `description:"计算频度"`
	ModifyTime     time.Time `description:"修改时间"`
	CreateTime     time.Time `description:"创建时间"`
}

// GetCountChartByTagId
// @Description: 根据标签id获取引用该标签的图表数量
// @author: Roc
// @datetime 2023-11-27 10:41:46
// @param tagId int
// @return total int64
// @return err error
func GetCountChartByTagId(tagId int) (total int64, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT count(1) total FROM chart_info AS a JOIN
    chart_info_cross_variety AS b on a.chart_info_id = b.chart_info_id 
    WHERE b.chart_x_tag_id = ? or b.chart_y_tag_id=?`
	err = o.Raw(sql, tagId, tagId).QueryRow(&total)

	return
}

// GeChartInfoCrossVarietyListByTagId
// @Description: 根据标签id获取引用该标签的配置列表
// @author: Roc
// @datetime 2023-12-11 13:13:59
// @param tagId int
// @return items []*ChartInfoCrossVariety
// @return err error
func GeChartInfoCrossVarietyListByTagId(tagId int) (items []*ChartInfoCrossVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT b.* FROM chart_info AS a JOIN
    chart_info_cross_variety AS b on a.chart_info_id = b.chart_info_id 
    WHERE b.chart_x_tag_id = ? or b.chart_y_tag_id=?`
	_, err = o.Raw(sql, tagId, tagId).QueryRows(&items)

	return
}

// GetChartInfoCrossVarietyByChartInfoId
// @Description: 根据图表id获取跨品种分析配置信息
// @author: Roc
// @datetime 2023-11-24 14:34:50
// @param id int
// @return item *ChartInfoCrossVariety
// @return err error
func GetChartInfoCrossVarietyByChartInfoId(id int) (item *ChartInfoCrossVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM chart_info_cross_variety WHERE chart_info_id = ?`
	err = o.Raw(sql, id).QueryRow(&item)

	return
}

func GetChartInfoCrossVarietyByXEdbInfoId(edbInfoId int) (items []*ChartInfoCrossVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.* FROM chart_info_cross_variety a 
         join chart_tag_variety b on a.chart_x_tag_id=b.chart_tag_id WHERE b.edb_info_id = ? `
	_, err = o.Raw(sql, edbInfoId).QueryRows(&items)
	return
}

func GetChartInfoCrossVarietyByYEdbInfoId(edbInfoId int) (items []*ChartInfoCrossVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.* FROM chart_info_cross_variety a 
         join chart_tag_variety b on a.chart_y_tag_id=b.chart_tag_id WHERE b.edb_info_id = ? `
	_, err = o.Raw(sql, edbInfoId).QueryRows(&items)
	return
}

// CreateChart
// @Description: 新增跨品种图表
// @author: Roc
// @datetime 2023-11-24 14:27:31
// @param chartInfo *data_manage.ChartInfo
// @param classify *data_manage.ChartClassify
// @param chartVarietyMappingList []*ChartVarietyMapping
// @param chartInfoCrossVariety *ChartInfoCrossVariety
// @return chartInfoId int
// @return err error
func CreateChart(chartInfo *data_manage.ChartInfo, classify *data_manage.ChartClassify, chartVarietyMappingList []*ChartVarietyMapping, chartInfoCrossVariety *ChartInfoCrossVariety) (chartInfoId int, err error) {
	o := orm.NewOrmUsingDB("data")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 判断是否分类已存在，不存在的话，先添加分类
	if classify.ChartClassifyId <= 0 {
		newId, tmpErr := tx.Insert(classify)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		classify.ChartClassifyId = int(newId)
	}

	// 新增图表信息
	chartInfo.ChartClassifyId = classify.ChartClassifyId
	newId, err := tx.Insert(chartInfo)
	if err != nil {
		return
	}
	// 品种列表
	chartInfo.ChartInfoId = int(newId)
	chartInfoId = int(newId)

	if len(chartVarietyMappingList) > 0 {
		for i := range chartVarietyMappingList {
			chartVarietyMappingList[i].ChartInfoId = chartInfoId
		}
		_, err = tx.InsertMulti(len(chartVarietyMappingList), chartVarietyMappingList)
		if err != nil {
			return
		}
	}

	// 图表配置
	chartInfoCrossVariety.ChartInfoId = chartInfoId
	if _, err = tx.Insert(chartInfoCrossVariety); err != nil {
		return
	}

	return
}

// EditChart 修改相关性图表的 图表与指标 的关系
func EditChart(chartInfo *data_manage.ChartInfo, chartVarietyMappingList []*ChartVarietyMapping, chartInfoCrossVariety *ChartInfoCrossVariety, chartUpdateCols, chartInfoCrossVarietyUpdateCols []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, chartUpdateCols...)
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}

	// 查找现有的品种列表
	currVarietyMappingList := make([]*ChartVarietyMapping, 0)
	sql := `SELECT * FROM chart_variety_mapping WHERE chart_info_id = ? `
	_, err = to.Raw(sql, chartInfo.ChartInfoId).QueryRows(&currVarietyMappingList)
	if err != nil {
		return
	}

	currVarietyMap := make(map[int]*ChartVarietyMapping)
	for _, v := range currVarietyMappingList {
		currVarietyMap[v.ChartVarietyId] = v
	}

	// 待添加的品种列表
	addVarietyMappingList := make([]*ChartVarietyMapping, 0)

	for i := range chartVarietyMappingList {
		_, ok := currVarietyMap[i]
		if !ok {
			// 如果不存在，那么就添加
			chartVarietyMappingList[i].ChartInfoId = chartInfo.ChartInfoId
			addVarietyMappingList = append(addVarietyMappingList, chartVarietyMappingList[i])
		} else {
			// 如果存在那么就移除
			delete(currVarietyMap, i)
		}
	}

	// 添加品种
	if len(addVarietyMappingList) > 0 {
		_, err = to.InsertMulti(len(addVarietyMappingList), addVarietyMappingList)
		if err != nil {
			return
		}
	}

	// 删除不存在的品种
	if len(currVarietyMap) > 0 {
		idStrList := make([]string, 0)
		for id, _ := range currVarietyMap {
			idStrList = append(idStrList, fmt.Sprint(id))
		}
		removeIdStr := strings.Join(idStrList, `,`)
		sql = fmt.Sprintf(` DELETE FROM chart_variety_mapping WHERE id in (%s) `, removeIdStr)
		_, err = to.Raw(sql).Exec()
		if err != nil {
			return
		}
	}

	// 跨品种分析图表配置
	_, err = to.Update(chartInfoCrossVariety, chartInfoCrossVarietyUpdateCols...)

	return
}

// EditChartEn
// @Description: 修改英文名称
// @author: Roc
// @datetime 2023-11-28 21:17:27
// @param chartInfo *data_manage.ChartInfo
// @param req request.EditChartEnInfoReq
// @return err error
func EditChartEn(chartInfo *data_manage.ChartInfo, req request.EditChartEnInfoReq) (err error) {
	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 更新图表信息
	chartInfo.ChartNameEn = req.ChartNameEn
	chartInfo.ModifyTime = time.Now().Local()
	_, err = to.Update(chartInfo, "ChartNameEn", "ModifyTime")
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}

	// 更新标签英文名
	for _, v := range req.TagList {
		sql := `UPDATE chart_tag SET chart_tag_name_en = ?,modify_time= NOW() WHERE chart_tag_id = ? `
		_, err = o.Raw(sql, v.TagNameEn, v.ChartTagId).Exec()
		if err != nil {
			return
		}
	}

	// 更新品种英文名
	for _, v := range req.VarietyList {
		sql := `UPDATE chart_variety SET chart_variety_name_en = ?,modify_time= NOW() WHERE chart_variety_id = ? `
		_, err = o.Raw(sql, v.VarietyNameEn, v.ChartVarietyId).Exec()
		if err != nil {
			return
		}
	}

	return
}

// EditChartBase
// @Description: 修改图表基础信息
// @author: Roc
// @datetime 2023-11-28 21:17:27
// @param chartInfo *data_manage.ChartInfo
// @param req request.EditChartBaseInfoReq
// @param lang string
// @return err error
func EditChartBase(chartInfo *data_manage.ChartInfo, req request.EditChartBaseInfoReq, lang 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()
		}
	}()

	// 更新图表信息
	switch lang {
	case utils.EnLangVersion:
		chartInfo.ChartNameEn = req.ChartName
	default:
		chartInfo.ChartName = req.ChartName
	}
	chartInfo.ModifyTime = time.Now().Local()
	_, err = to.Update(chartInfo, "ChartName", "ChartNameEn", "ModifyTime")
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}

	// 更新标签名
	for _, v := range req.TagList {
		var sql string
		switch lang {
		case utils.EnLangVersion:
			sql = `UPDATE chart_tag SET chart_tag_name_en = ?,modify_time= NOW() WHERE chart_tag_id = ? `
		default:
			sql = `UPDATE chart_tag SET chart_tag_name = ?,modify_time= NOW() WHERE chart_tag_id = ? `
		}
		if sql != `` {
			_, err = o.Raw(sql, v.TagName, v.ChartTagId).Exec()
			if err != nil {
				return
			}
		}
	}

	// 更新品种名
	for _, v := range req.VarietyList {
		var sql string
		switch lang {
		case utils.EnLangVersion:
			sql = `UPDATE chart_variety SET chart_variety_name_en = ?,modify_time= NOW() WHERE chart_variety_id = ? `
		default:
			sql = `UPDATE chart_variety SET chart_variety_name = ?,modify_time= NOW() WHERE chart_variety_id = ? `
		}
		_, err = o.Raw(sql, v.VarietyName, v.ChartVarietyId).Exec()
		if err != nil {
			return
		}
	}

	return
}
