package cross_variety

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

// ChartTagVariety
// @Description: chart_tag_variety 图表标签品种关系表
type ChartTagVariety struct {
	Id                        int       `orm:"column(id);pk"`
	ChartTagId                int       `description:"标签id"`
	ChartVarietyId            int       `description:"品种id"`
	EdbInfoId                 int       `description:"指标id"`
	LastUpdateSysUserId       int       `description:"最后一次操作人"`
	LastUpdateSysUserRealName string    `description:"最后一次操作人真实姓名"`
	ModifyTime                time.Time `description:"修改时间"`
	CreateTime                time.Time `description:"创建时间"`
}

// GetChartTagVarietyByTagAndVariety
// @Description: 根据标签id和品种id获取关系
// @author: Roc
// @datetime 2023-11-22 10:42:50
// @param chartTagId int
// @param chartVarietyId int
// @return item *ChartTagVariety
// @return err error
func GetChartTagVarietyByTagAndVariety(chartTagId, chartVarietyId int) (item *ChartTagVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM chart_tag_variety WHERE chart_tag_id = ? AND chart_variety_id = ?`
	err = o.Raw(sql, chartTagId, chartVarietyId).QueryRow(&item)

	return
}

// GetChartTagVarietyListByTag
// @Description: 根据标签id获取所有绑定的品种列表
// @author: Roc
// @datetime 2023-11-22 10:44:35
// @param chartTagId int
// @param chartVarietyId int
// @return items []*ChartTagVariety
// @return err error
func GetChartTagVarietyListByTag(chartTagId int) (items []*ChartTagVariety, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM chart_tag_variety WHERE chart_tag_id = ? `
	_, err = o.Raw(sql, chartTagId).QueryRows(&items)

	return
}

// GetChartTagVarietyListByTagAndVariety
// @Description: 根据标签id和品种id列表获取所绑定的品种列表
// @author: Roc
// @datetime 2023-11-23 15:04:20
// @param chartTagId int
// @param varietyIdList []int
// @return items []*ChartTagVariety
// @return err error
func GetChartTagVarietyListByTagAndVariety(chartTagId int, varietyIdList []int) (items []*ChartTagVariety, err error) {
	num := len(varietyIdList)
	if num <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM chart_tag_variety WHERE chart_tag_id = ? AND chart_variety_id in (` + utils.GetOrmInReplace(num) + `) `
	_, err = o.Raw(sql, chartTagId, varietyIdList).QueryRows(&items)

	return
}

// ChartTagVarietyItem
// @Description: 图表标签/品种/指标数据
type ChartTagVarietyItem struct {
	Id             int     `orm:"column(id);pk"`
	ChartTagId     int     `description:"标签id"`
	ChartVarietyId int     `description:"品种id"`
	EdbInfoId      int     `description:"指标id"`
	EdbCode        string  `description:"指标编码"`
	EdbName        string  `description:"指标名称"`
	EndDate        string  `description:"数据的最晚日期"`
	EndValue       float64 `description:"数据最新值"`
}

// GetChartTagVarietyItemListByTag
// @Description: 根据标签id获取所有绑定的品种列表
// @author: Roc
// @datetime 2023-11-22 10:44:35
// @param chartTagId int
// @param chartVarietyId int
// @return items []*ChartTagVariety
// @return err error
func GetChartTagVarietyItemListByTag(chartTagId int) (items []*ChartTagVarietyItem, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.*,b.edb_code,b.edb_name,b.end_date,b.end_value FROM chart_tag_variety a 
         join edb_info b on a.edb_info_id=b.edb_info_id WHERE chart_tag_id = ? `
	_, err = o.Raw(sql, chartTagId).QueryRows(&items)

	return
}

// ChartTagVarietyCount
// @Description: 签绑定的品种数量
type ChartTagVarietyCount struct {
	ChartTagId int `description:"标签id"`
	Total      int `description:"标签配置的品种数量"`
}

// GetCountChartTagVarietyItemListByTag
// @Description: 获取所有标签绑定的品种数量
// @author: Roc
// @datetime 2023-11-22 10:44:35
// @return items []*ChartTagVarietyCount
// @return err error
func GetCountChartTagVarietyItemListByTag() (items []*ChartTagVarietyCount, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT chart_tag_id,count(1) total FROM chart_tag_variety a 
         join edb_info b on a.edb_info_id=b.edb_info_id  group by chart_tag_id`
	_, err = o.Raw(sql).QueryRows(&items)

	return
}

// SaveVarietyEdb
// @Description: 配置标签中的指标与品种的映射关系
// @author: Roc
// @datetime 2023-11-22 14:26:24
// @param chartTagId int
// @param list []request.VarietyEdbReq
// @param sysUserId int
// @param sysUserName string
// @return err error
func SaveVarietyEdb(chartTagId int, list []request.VarietyEdbReq, sysUserId int, sysUserName string) (err error) {
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 查找现在已经存在的品种和指标的关系
	var items []*ChartTagVariety
	sql := `SELECT * FROM chart_tag_variety WHERE chart_tag_id = ? `
	_, err = o.Raw(sql, chartTagId).QueryRows(&items)
	if err != nil {
		return
	}

	hasMap := make(map[int]*ChartTagVariety)
	existMap := make(map[int]*ChartTagVariety)
	for _, v := range items {
		hasMap[v.ChartVarietyId] = v
		existMap[v.ChartVarietyId] = v
	}

	// 待添加的配置
	addList := make([]*ChartTagVariety, 0)
	for _, v := range list {
		tmpChartTagVariety, ok := hasMap[v.ChartVarietyId]

		// 找不到就插入
		if !ok {
			addList = append(addList, &ChartTagVariety{
				Id:                        0,
				ChartTagId:                chartTagId,
				ChartVarietyId:            v.ChartVarietyId,
				EdbInfoId:                 v.EdbInfoId,
				LastUpdateSysUserId:       sysUserId,
				LastUpdateSysUserRealName: sysUserName,
				ModifyTime:                time.Now(),
				CreateTime:                time.Now(),
			})
			continue
		}

		delete(existMap, v.ChartVarietyId)

		// 找到了，如果指标不一致那就修改
		if tmpChartTagVariety.EdbInfoId != v.EdbInfoId {
			tmpChartTagVariety.EdbInfoId = v.EdbInfoId
			tmpChartTagVariety.LastUpdateSysUserId = sysUserId
			tmpChartTagVariety.LastUpdateSysUserRealName = sysUserName
			tmpChartTagVariety.ModifyTime = time.Now()
			_, err = o.Update(tmpChartTagVariety, "EdbInfoId", "LastUpdateSysUserId", "LastUpdateSysUserRealName", "ModifyTime")
			if err != nil {
				return
			}
		}
	}

	// 删除不要了的
	if len(existMap) > 0 {
		idStrList := make([]string, 0)
		for _, v := range existMap {
			idStrList = append(idStrList, fmt.Sprint(v.Id))
		}
		removeIdStr := strings.Join(idStrList, `,`)
		sql = fmt.Sprintf(` DELETE FROM chart_tag_variety WHERE id in (%s) `, removeIdStr)
		_, err = o.Raw(sql).Exec()
		if err != nil {
			return
		}
	}

	// 添加配置
	if len(addList) > 0 {
		_, err = o.InsertMulti(len(addList), addList)
		if err != nil {
			return
		}
	}
	return
}

// GetCountByEdbInfoId
// @Description: 根据指标id获取其关联的品种数量
// @author: Roc
// @datetime 2023-11-28 19:43:42
// @param edbInfoId int
// @return total int
// @return err error
func GetCountByEdbInfoId(edbInfoId int) (total int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT count(1) total FROM chart_tag_variety a 
            INNER JOIN edb_info b ON a.edb_info_id=b.edb_info_id 
            INNER JOIN chart_tag AS c ON a.chart_tag_id=c.chart_tag_id
            WHERE a.edb_info_id = ?`
	err = o.Raw(sql, edbInfoId).QueryRow(&total)

	return
}

// GetChartTagVarietyListByTagIdList
// @Description: 根据标签id列表获取所有绑定的品种列表
// @author: Roc
// @datetime 2023-11-22 10:44:35
// @param chartTagId int
// @param chartVarietyId int
// @return items []*ChartVariety
// @return err error
func GetChartTagVarietyListByTagIdList(chartTagIdList []int) (items []*ChartTagVariety, err error) {
	num := len(chartTagIdList)
	if num <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.* FROM chart_tag_variety a 
         join chart_variety b on a.chart_variety_id=b.chart_variety_id WHERE chart_tag_id in (` + utils.GetOrmInReplace(num) + `) `
	_, err = o.Raw(sql, chartTagIdList).QueryRows(&items)

	return
}
