package edb_refresh

import (
	"errors"
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// EdbRefreshConfig
// @Description: 指标的刷新时间配置表
type EdbRefreshConfig struct {
	EdbRefreshConfigId  int       `orm:"column(edb_refresh_config_id);pk"`
	RefreshFrequency    string    `description:"刷新频率"`
	RefreshFrequencyDay int       `description:"具体刷新的日期"`
	RefreshTime         string    `description:"刷新时间"`
	RefreshAllData      int       `description:"是否刷新所有数据,0:否,1:刷新所有数据"`
	RefreshDataNum      int       `description:"刷新单元格数"`
	ModifyTime          time.Time `description:"最晚一次的更新时间"`
	CreateTime          time.Time `description:"添加时间"`
}

// Add
// @Description: 添加
// @author: Roc
// @receiver m
// @datetime 2023-12-14 16:11:10
// @param cols []string
// @return err error
func (m *EdbRefreshConfig) Add() (err error) {
	if m.EdbRefreshConfigId > 0 {
		err = errors.New("该配置已存在")
		return
	}
	o := orm.NewOrmUsingDB("data")
	lastId, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EdbRefreshConfigId = int(lastId)

	return
}

// Update
// @Description: 更新
// @author: Roc
// @receiver m
// @datetime 2023-12-14 16:11:10
// @param cols []string
// @return err error
func (m *EdbRefreshConfig) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, cols...)
	return
}

// Delete
// @Description: 删除
// @author: Roc
// @receiver m
// @datetime 2023-12-14 16:11:10
// @return err error
func (m *EdbRefreshConfig) Delete() (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Delete(m)
	return
}

// GetEdbRefreshConfigListByCondition
// @Description: 根据条件获取刷新配置列表
// @author: Roc
// @datetime 2024-01-08 14:07:10
// @param refreshFrequency string
// @param refreshTime string
// @param refreshFrequencyDay int
// @param refreshAllData int
// @param refreshDataNum int
// @return item *EdbRefreshConfig
// @return err error
func GetEdbRefreshConfigListByCondition(refreshFrequency, refreshTime string, refreshFrequencyDay, refreshAllData, refreshDataNum int) (item *EdbRefreshConfig, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM edb_refresh_config
         WHERE refresh_frequency = ? AND refresh_frequency_day = ? AND refresh_time = ? AND refresh_all_data = ? AND refresh_data_num = ? ORDER BY edb_refresh_config_id ASC `
	err = o.Raw(sql, refreshFrequency, refreshFrequencyDay, refreshTime, refreshAllData, refreshDataNum).QueryRow(&item)

	return
}

// SaveEdbRefreshConfig
// @Description:  保存刷新配置
// @author: Roc
// @datetime 2024-01-08 15:13:23
// @param source int
// @param subSource int
// @param sysUserId int
// @param sysUserRealName string
// @param newConfigList []*EdbRefreshConfig
// @param addMapping []*EdbRefreshMapping
// @param edbIdList []int
// @return err error
func SaveEdbRefreshConfig(source, subSource, sysUserId int, sysUserRealName string, newConfigList []*EdbRefreshConfig, addMapping []*EdbRefreshMapping, edbIdList []int) (err error) {
	num := len(edbIdList)
	if num <= 0 {
		return
	}
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
			return
		}
		_ = o.Commit()
	}()

	for _, v := range newConfigList {
		lastId, tmpErr := o.Insert(v)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		v.EdbRefreshConfigId = int(lastId)

		for _, edbId := range edbIdList {
			addMapping = append(addMapping, &EdbRefreshMapping{
				EdbRefreshMappingId: 0,
				Source:              source,
				SubSource:           subSource,
				EdbInfoId:           edbId,
				EdbRefreshConfigId:  v.EdbRefreshConfigId,
				SysUserId:           sysUserId,
				SysUserRealName:     sysUserRealName,
				ModifyTime:          time.Now(),
				CreateTime:          time.Now(),
			})
		}
	}

	// 先删除
	sql := `DELETE FROM edb_refresh_mapping WHERE source =? AND sub_source =? AND edb_info_id in (` + utils.GetOrmInReplace(num) + `)`
	_, err = o.Raw(sql, source, subSource, edbIdList).Exec()

	// 再写入
	if len(addMapping) > 0 {
		tmpAddDataList := make([]*EdbRefreshMapping, 0)
		i := 0
		for _, v := range addMapping {
			tmpAddDataList = append(tmpAddDataList, v)
			i++
			if i >= 500 {
				_, err = o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
				if err != nil {
					return
				}
				i = 0
				tmpAddDataList = make([]*EdbRefreshMapping, 0)
			}
		}

		if len(tmpAddDataList) > 0 {
			_, err = o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
			if err != nil {
				return
			}
		}
	}

	return

}

// EdbRefreshConfigItem
// @Description: 指标的刷新时间配置项
type EdbRefreshConfigItem struct {
	RefreshFrequency    string `description:"刷新频率"`
	RefreshFrequencyDay int    `description:"具体刷新的日期"`
	RefreshTime         string `description:"刷新时间"`
	RefreshAllData      int    `description:"是否刷新所有数据,0:否,1:刷新所有数据"`
	RefreshDataNum      int    `description:"刷新单元格数"`
}

// GetEdbRefreshConfigListBySourceAndeEdbInfoId
// @Description: 根据来源和指标获取其配置列表
// @author: Roc
// @datetime 2024-01-10 14:18:21
// @param source int
// @param subSource int
// @param edbInfoId int
// @return list []*EdbRefreshDefaultConfig
// @return err error
func GetEdbRefreshConfigListBySourceAndeEdbInfoId(source, subSource, edbInfoId int) (list []*EdbRefreshConfigItem, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.* FROM edb_refresh_config a 
         JOIN  edb_refresh_mapping b ON a.edb_refresh_config_id = b.edb_refresh_config_id
         WHERE b.source = ? AND b.sub_source = ? AND b.edb_info_id = ? ORDER BY a.edb_refresh_config_id ASC `
	_, err = o.Raw(sql, source, subSource, edbInfoId).QueryRows(&list)

	return
}

// EdbRefreshConfigAndEdbItem
// @Description: 指标的刷新时间配置项
type EdbRefreshConfigAndEdbItem struct {
	RefreshFrequency    string `description:"刷新频率"`
	RefreshFrequencyDay int    `description:"具体刷新的日期"`
	RefreshTime         string `description:"刷新时间"`
	RefreshAllData      int    `description:"是否刷新所有数据,0:否,1:刷新所有数据"`
	RefreshDataNum      int    `description:"刷新单元格数"`
	EdbInfoId           int    `description:"指标id,如果是数据源(钢联、有色金属)的,那么就是数据源里面的id"`
	Source              int    `description:"来源"`
	SubSource           int    `description:"子来源"`
}

// GetEdbRefreshConfigAndEdbListBySourceAndeEdbInfoId
// @Description: 根据来源和指标获取其配置列表
// @author: Roc
// @datetime 2024-01-10 14:18:21
// @param source int
// @param subSource int
// @param edbInfoId int
// @return list []*EdbRefreshDefaultConfig
// @return err error
func GetEdbRefreshConfigAndEdbListBySourceAndeEdbInfoId(source, subSource int, edbInfoIdList []int) (list []*EdbRefreshConfigAndEdbItem, err error) {
	num := len(edbInfoIdList)
	if num <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT a.*,b.source,b.sub_source,b.edb_info_id FROM edb_refresh_config a 
         JOIN  edb_refresh_mapping b ON a.edb_refresh_config_id = b.edb_refresh_config_id
         WHERE b.source = ? AND b.sub_source = ? AND b.edb_info_id in (` + utils.GetOrmInReplace(num) + `)  ORDER BY a.edb_refresh_config_id ASC `
	_, err = o.Raw(sql, source, subSource, edbInfoIdList).QueryRows(&list)

	return
}