package data_manage

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"time"
)

type BaseFromBaiinfo struct {
	BaseFromBaiinfoId int `orm:"column(base_from_baiinfo_id);pk" gorm:"primaryKey" `
	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
}

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

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

func GetBaseFromBaiinfoIndexByIndexCode(indexCode string) (item *BaseFromBaiinfoIndex, err error) {
	sql := ` SELECT * FROM base_from_baiinfo_index WHERE index_code=? `
	err = global.DmSQL["data"].Raw(sql, indexCode).First(&item).Error

	return
}

// GetBaseFromBaiinfoIndexCountByClassifyIds 获取分类下指标的个数
func GetBaseFromBaiinfoIndexCountByClassifyIds(classifyIds []int) (count int, err error) {
	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 = global.DmSQL["data"].Raw(sql, classifyIds).Scan(&count).Error

	return
}

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

	return
}

// GetBaiinfoIndexAll 用于分类展示
func GetBaiinfoIndexAll() (items []*BaseFromBaiinfoClassifyItems, err error) {
	o := global.DmSQL["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).Scan(&items).Error

	return
}

// GetBaseFromBaiinfoIndexByIndexId 根据指标id获取指标信息
func GetBaseFromBaiinfoIndexByIndexId(indexId int) (item *BaseFromBaiinfoIndex, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM base_from_baiinfo_index WHERE base_from_baiinfo_index_id=? `
	err = o.Raw(sql, indexId).First(&item).Error

	return
}

// GetBaseFromBaiinfoIndexMaxSortByClassifyId 根据指标id获取指标信息
func GetBaseFromBaiinfoIndexMaxSortByClassifyId(classifyId int) (sort int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT max(sort) FROM base_from_baiinfo_index WHERE classify_id=? `
	err = o.Raw(sql, classifyId).Scan(&sort).Error

	return
}

// GetBaseFromBaiinfoIndexMinSortByClassifyId 获取最小不等于0的排序
func GetBaseFromBaiinfoIndexMinSortByClassifyId(classifyId int) (sort int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT min(sort) FROM base_from_baiinfo_index WHERE classify_id=? and sort <> 0 `
	err = o.Raw(sql, classifyId).Scan(&sort).Error

	return
}

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

// GetBaseFromBaiinfoIndexType 获取历史指标信息类型
func GetBaseFromBaiinfoIndexType() (list []BaseFromBaiinfoIndexType, err error) {
	o := global.DmSQL["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).Scan(&list).Error

	return
}

// MoveBaseFromBaiinfoIndex 移动指标分类
func MoveBaseFromBaiinfoIndex(chartInfoId, classifyId int) (err error) {
	o := global.DmSQL["data"]
	sql := ` UPDATE base_from_baiinfo_index
			SET
			  classify_id = ?, modify_time=NOW() 
			WHERE base_from_baiinfo_index_id = ?`
	err = o.Exec(sql, classifyId, chartInfoId).Error

	return
}

// UpdateBaseFromBaiinfoIndexByClassifyId 根据指标id更新排序
func UpdateBaseFromBaiinfoIndexByClassifyId(classifyId, nowSort, prevIndexInfoId int, updateSort string) (err error) {
	o := global.DmSQL["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.Exec(sql, classifyId, nowSort).Error

	return
}

// MoveUpBaiinfoIndexBySort 往上移动
func MoveUpBaiinfoIndexBySort(classifyId, nextSort, currentSort int) (err error) {
	o := global.DmSQL["data"]
	sql := `update base_from_baiinfo_index set sort = sort + 1 where classify_id=? and sort >= ? and sort< ?`
	err = o.Exec(sql, classifyId, nextSort, currentSort).Error

	return
}

// MoveDownBaiinfoIndexBySort 往下移动
func MoveDownBaiinfoIndexBySort(classifyId, prevSort, currentSort int) (err error) {
	o := global.DmSQL["data"]
	sql := `update base_from_baiinfo_index set sort = sort - 1 where classify_id=? and sort <= ? and sort> ? `
	err = o.Exec(sql, classifyId, prevSort, currentSort).Error

	return
}

// GetFirstBaseFromBaiinfoIndexByClassifyId 获取当前分类下,且排序数相同 的排序第一条的数据
func GetFirstBaseFromBaiinfoIndexByClassifyId(classifyId int) (item *BaseFromBaiinfoIndex, err error) {
	o := global.DmSQL["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).First(&item).Error

	return
}

// Update 更新Baiinfo指标基础信息
func (item *BaseFromBaiinfoIndex) Update(cols []string) (err error) {
	err = global.DmSQL["data"].Select(cols).Updates(item).Error

	return
}

// DeleteBaseFromBaiinfoIndexById 根据指标id删除对应的指标、指标数据
func DeleteBaseFromBaiinfoIndexById(baiinfoIndexId int) (err error) {
	o := global.DmSQL["data"]
	to := o.Begin()
	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.Exec(sql, baiinfoIndexId).Error
	if err != nil {
		return
	}

	//删除指标数据
	sql = `DELETE FROM base_from_baiinfo_data WHERE base_from_baiinfo_index_id = ? `
	err = to.Exec(sql, baiinfoIndexId).Error
	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
}