package data_manage

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

type BaseFromBaiinfo struct {
	BaseFromBaiinfoId int `orm:"column(base_from_baiinfo_id);pk"`
	Aid               int
	Name              string
	Interface         string
	ApiUpdate         int
	ApiUpdateType     string
	ApiType           int
	ApiTypeAll        string
	Type1             string `orm:"column(type_1)"`
	Type2             string `orm:"column(type_2)"`
	Type3             string `orm:"column(type_3)"`
	ApiStartTime      string
	ApiUpdateTime     string
	StartTime         string
	FinishTime        string
	AuthModule        string
	AuthLang          string
	ApiLabel          string
	Enable            string
	EditPerson        string
	EditTime          string
	AuthDur           int
	AuthDurType       string
}

func AddBaseFromBaiinfo(item *BaseFromBaiinfo) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("data")
	lastId, err = o.Insert(item)
	return
}

func GetBaseFromBaiinfoList() (list []*BaseFromBaiinfo, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

func GetBaseFromBaiinfoByBaiinfoCode(baiinfoCode string) (item *BaseFromBaiinfo, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo WHERE interface=?`
	err = o.Raw(sql, baiinfoCode).QueryRow(&item)
	return
}

type BaseFromBaiinfoIndex struct {
	BaseFromBaiinfoIndexId int `orm:"column(base_from_baiinfo_index_id);pk"`
	ClassifyId             int
	Interface              string
	IndexCode              string
	IndexName              string
	Frequency              string
	Unit                   string
	Sort                   int
	CreateTime             time.Time
	ModifyTime             time.Time
}

func AddBaseFromBaiinfoIndex(item *BaseFromBaiinfoIndex) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("data")
	lastId, err = o.Insert(item)
	return
}

func GetBaseFromBaiinfoIndex() (list []*BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo_index `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

type BaseFromBaiinfoData struct {
	BaiinfoDataId          int `orm:"column(baiinfo_data_id);pk"`
	BaseFromBaiinfoIndexId int
	IndexCode              string
	DataTime               string
	Value                  string
	CreateTime             time.Time
	ModifyTime             time.Time
	DataTimestamp          int64
}

func AddBaseFromBaiinfoData(item *BaseFromBaiinfoData) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("data")
	lastId, err = o.Insert(item)
	return
}

func GetBaseFromBaiinfoDataAll() (list []*BaseFromBaiinfoData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo_data `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

func ModifyBaseFromBaiinfoData(baiinfoDataId int, value string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `UPDATE base_from_baiinfo_data SET value=?,modify_time=NOW() WHERE baiinfo_data_id=? `
	_, err = o.Raw(sql, value, baiinfoDataId).Exec()
	return
}

func GetBaseFromBaiinfoIndexByBaiinfoCode(baiinfoCode string) (list []*BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_baiinfo_index WHERE interface=? `
	_, err = o.Raw(sql, baiinfoCode).QueryRows(&list)
	return
}

func GetBaseFromBaiinfoMaxOrMinDate(indexCode string) (min_date, max_date string, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT MIN(data_time) AS min_date,MAX(data_time) AS max_date FROM base_from_baiinfo_data WHERE index_code=? `
	err = o.Raw(sql, indexCode).QueryRow(&min_date, &max_date)
	return
}

func ModifyBaseFromBaiinfoMinDateAndMaxDate(baseFromBaiinfoIndexId int, minDate, maxDate string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` UPDATE base_from_baiinfo_index SET start_date=?,end_date=?,modify_time=NOW() WHERE base_from_baiinfo_index_id=? `
	_, err = o.Raw(sql, minDate, maxDate, baseFromBaiinfoIndexId).Exec()
	return
}

func GetBaseFromBaiinfoDataAllByIndexCode(indexCode string) (list []*BaseFromBaiinfoData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo_data WHERE index_code=? `
	_, err = o.Raw(sql, indexCode).QueryRows(&list)
	return
}

func GetBaseFromBaiinfoIndexByIndexCode(indexCode string) (list *BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_baiinfo_index WHERE index_code=? `
	err = o.Raw(sql, indexCode).QueryRow(&list)
	return
}

// GetBaseFromBaiinfoIndexCountByClassifyIds 获取分类下指标的个数
func GetBaseFromBaiinfoIndexCountByClassifyIds(classifyIds []int) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	num := len(classifyIds)
	if num <= 0 {
		return
	}
	sql := `SELECT COUNT(1) AS count FROM base_from_baiinfo_index WHERE classify_id IN (` + utils.GetOrmInReplace(num) + `) `
	err = o.Raw(sql, classifyIds).QueryRow(&count)
	return
}

// GetBaseFromBaiinfoIndexByClassifyId 获取根据分类查询指标
func GetBaseFromBaiinfoIndexByClassifyId(classifyId int) (list []*BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo_index WHERE classify_id =? ORDER BY sort ASC, base_from_baiinfo_index_id ASC `
	_, err = o.Raw(sql, classifyId).QueryRows(&list)
	return
}

// GetBaiinfoIndexAll 用于分类展示
func GetBaiinfoIndexAll() (items []*BaseFromBaiinfoClassifyItems, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT base_from_baiinfo_index_id, classify_id, index_name as classify_name, index_code as base_from_baiinfo_index_code
            FROM base_from_baiinfo_index ORDER BY sort ASC, base_from_baiinfo_index_id ASC `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// GetBaseFromBaiinfoIndexByIndexId 根据指标id获取指标信息
func GetBaseFromBaiinfoIndexByIndexId(indexId int) (item *BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_baiinfo_index WHERE base_from_baiinfo_index_id=? `
	err = o.Raw(sql, indexId).QueryRow(&item)
	return
}

// GetBaseFromBaiinfoIndexMaxSortByClassifyId 根据指标id获取指标信息
func GetBaseFromBaiinfoIndexMaxSortByClassifyId(classifyId int) (sort int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT max(sort) FROM base_from_baiinfo_index WHERE classify_id=? `
	err = o.Raw(sql, classifyId).QueryRow(&sort)
	return
}

// GetBaseFromBaiinfoIndexMinSortByClassifyId 获取最小不等于0的排序
func GetBaseFromBaiinfoIndexMinSortByClassifyId(classifyId int) (sort int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT min(sort) FROM base_from_baiinfo_index WHERE classify_id=? and sort <> 0 `
	err = o.Raw(sql, classifyId).QueryRow(&sort)
	return
}

type BaseFromBaiinfoIndexType struct {
	Type2 string `orm:"column(type_2)"`
	Type3 string `orm:"column(type_3)"`
}

// GetBaseFromBaiinfoIndexType 获取历史指标信息类型
func GetBaseFromBaiinfoIndexType() (list []BaseFromBaiinfoIndexType, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT type_2, type_3 from base_from_baiinfo_index where type_2 <> "" GROUP BY type_2, type_3`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// MoveBaseFromBaiinfoIndex 移动指标分类
func MoveBaseFromBaiinfoIndex(chartInfoId, classifyId int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` UPDATE base_from_baiinfo_index
			SET
			  classify_id = ?, modify_time=NOW() 
			WHERE base_from_baiinfo_index_id = ?`
	_, err = o.Raw(sql, classifyId, chartInfoId).Exec()
	return
}

// UpdateBaseFromBaiinfoIndexByClassifyId 根据指标id更新排序
func UpdateBaseFromBaiinfoIndexByClassifyId(classifyId, nowSort, prevIndexInfoId int, updateSort string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` update base_from_baiinfo_index set sort = ` + updateSort + ` WHERE classify_id=? AND  `
	if prevIndexInfoId > 0 {
		sql += ` ( sort > ? or (base_from_baiinfo_index_id > ` + fmt.Sprint(prevIndexInfoId) + ` and sort = ` + fmt.Sprint(nowSort) + `))`
	}
	_, err = o.Raw(sql, classifyId, nowSort).Exec()
	return
}

// MoveUpBaiinfoIndexBySort 往上移动
func MoveUpBaiinfoIndexBySort(classifyId, nextSort, currentSort int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `update base_from_baiinfo_index set sort = sort + 1 where classify_id=? and sort >= ? and sort< ?`
	_, err = o.Raw(sql, classifyId, nextSort, currentSort).Exec()
	return
}

// MoveDownBaiinfoIndexBySort 往下移动
func MoveDownBaiinfoIndexBySort(classifyId, prevSort, currentSort int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `update base_from_baiinfo_index set sort = sort - 1 where classify_id=? and sort <= ? and sort> ? `
	_, err = o.Raw(sql, classifyId, prevSort, currentSort).Exec()
	return
}

// GetFirstBaseFromBaiinfoIndexByClassifyId 获取当前分类下，且排序数相同 的排序第一条的数据
func GetFirstBaseFromBaiinfoIndexByClassifyId(classifyId int) (item *BaseFromBaiinfoIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_baiinfo_index WHERE classify_id=? order by sort asc,base_from_baiinfo_index_id asc limit 1`
	err = o.Raw(sql, classifyId).QueryRow(&item)
	return
}

// Update 更新Baiinfo指标基础信息
func (item *BaseFromBaiinfoIndex) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(item, cols...)
	return
}

// DeleteBaseFromBaiinfoIndexById 根据指标id删除对应的指标、指标数据
func DeleteBaseFromBaiinfoIndexById(baiinfoIndexId int) (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 := `DELETE FROM base_from_baiinfo_index WHERE base_from_baiinfo_index_id = ? `
	_, err = to.Raw(sql, baiinfoIndexId).Exec()
	if err != nil {
		return
	}

	//删除指标数据
	sql = `DELETE FROM base_from_baiinfo_data WHERE base_from_baiinfo_index_id = ? `
	_, err = to.Raw(sql, baiinfoIndexId).Exec()
	if err != nil {
		return
	}

	return
}

// EditBaiinfoIndexInfoResp 新增指标的返回
type EditBaiinfoIndexInfoResp struct {
	BaseFromBaiinfoIndexId int    `description:"指标ID"`
	IndexCode              string `description:"指标code"`
}

type BaiinfoSingleDataResp struct {
	BaseFromBaiinfoIndexId int
	ClassifyId             int
	Interface              string
	Name                   string
	IndexCode              string
	IndexName              string
	Frequency              string
	Unit                   string
	ApiStartTime           string
	ApiUpdateTime          string
	StartTime              string
	FinishTime             string
	CreateTime             string
	ModifyTime             string
	Data                   []*BaiinfoIndexData
}
