package data_manage

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

type BaseFromSmm struct {
	BaseFromSmmId int `orm:"column(base_from_smm_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 AddBaseFromSmm(item *BaseFromSmm) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("data")
	lastId, err = o.Insert(item)
	return
}

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

func GetBaseFromSmmBySmmCode(smmCode string) (item *BaseFromSmm, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_smm WHERE interface=?`
	err = o.Raw(sql, smmCode).QueryRow(&item)
	return
}

type BaseFromSmmIndex struct {
	BaseFromSmmIndexId int `orm:"column(base_from_smm_index_id);pk"`
	ClassifyId         int
	Interface          string
	Name               string
	IndexCode          string
	IndexName          string
	Type1              string `orm:"column(type_1)"`
	Type2              string `orm:"column(type_2)"`
	Type3              string `orm:"column(type_3)"`
	Frequency          string
	Unit               string
	ApiStartTime       string
	ApiUpdateTime      string
	StartTime          string
	FinishTime         string
	Sort               int
	CreateTime         time.Time
	ModifyTime         time.Time
	DataState          string
	ReleaseTime        string
	StartDate          string
	EndDate            string
}

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

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

type BaseFromSmmData struct {
	SmmDataId          int `orm:"column(smm_data_id);pk"`
	BaseFromSmmIndexId int
	IndexCode          string
	DataTime           string
	Value              string
	CreateTime         time.Time
	ModifyTime         time.Time
	DataTimestamp      int64
}

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

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

func ModifyBaseFromSmmData(smmDataId int, value string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `UPDATE base_from_smm_data SET value=?,modify_time=NOW() WHERE smm_data_id=? `
	_, err = o.Raw(sql, value, smmDataId).Exec()
	return
}

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

func GetBaseFromSmmMaxOrMinDate(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_smm_data WHERE index_code=? `
	err = o.Raw(sql, indexCode).QueryRow(&min_date, &max_date)
	return
}

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

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

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

// GetBaseFromSmmIndexCountByClassifyIds 获取分类下指标的个数
func GetBaseFromSmmIndexCountByClassifyIds(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_smm_index WHERE classify_id IN (` + utils.GetOrmInReplace(num) + `) `
	err = o.Raw(sql, classifyIds).QueryRow(&count)
	return
}

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

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

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

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

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

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

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

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

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

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

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

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

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

// DeleteBaseFromSmmIndexById 根据指标id删除对应的指标、指标数据
func DeleteBaseFromSmmIndexById(smmIndexId 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_smm_index WHERE base_from_smm_index_id = ? `
	_, err = to.Raw(sql, smmIndexId).Exec()
	if err != nil {
		return
	}

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

	return
}

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

type SmmSingleDataResp struct {
	BaseFromSmmIndexId 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               []*SmmIndexData
}

func GetSmmIndexDataList(condition, sortStr string, pars []interface{}, startSize, pageSize int) (items []*BaseFromSmmIndexItem, err error) {
	sql := `select * FROM base_from_smm_index
               WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY ` + sortStr
	sql += `  limit ?,? `
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func GetSmmIndexDataListCount(condition string, pars []interface{}) (total int, err error) {
	sql := `select count(1) FROM base_from_smm_index
               WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	o := orm.NewOrmUsingDB("data")
	err = o.Raw(sql, pars).QueryRow(&total)
	return
}

type BaseFromSmmIndexListResp struct {
	List   []*BaseFromSmmIndexItem
	Paging *paging.PagingItem `description:"分页数据"`
}

type BaseFromSmmIndexItem struct {
	BaseFromSmmIndexId int `orm:"column(base_from_smm_index_id);pk"`
	ClassifyId         int
	Interface          string
	Name               string
	IndexCode          string
	IndexName          string
	Type1              string `orm:"column(type_1)"`
	Type2              string `orm:"column(type_2)"`
	Type3              string `orm:"column(type_3)"`
	Frequency          string
	Unit               string
	ApiStartTime       string
	ApiUpdateTime      string
	StartTime          string
	FinishTime         string
	Sort               int
	CreateTime         string
	ModifyTime         string
	DataState          string
	ReleaseTime        string
	StartDate          string
	EndDate            string
	TypeAll            string
}

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

// GetBaseFromSmmIndexTypeList
func GetBaseFromSmmIndexTypeList() (list []BaseFromSmmIndexTypeList, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT type_1,type_2, type_3 from base_from_smm_index GROUP BY type_1,type_2,type_3 `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

type TypeListRespItem struct {
	Type  string
	Child []TypeListRespItem
}

func GetSmmIndexDataListNoPage(condition string, pars []interface{}) (items []*BaseFromSmmIndexItem, err error) {
	sql := `select * FROM base_from_smm_index
               WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func GetBaseFromSmmIndexByIndexCodes(indexCodes string) (list []*BaseFromSmmIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_smm_index WHERE index_code IN (` + indexCodes + `)`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// SmmIndexListReq
type SmmIndexListReq struct {
	Types        []string `description:"分类"`
	Frequency    string   `description:"频度"`
	DataState    string   `description:"数据状态"`
	Keyword      string   `description:"关键字"`
	IndexCodes   string   `description:"指标代码"`
	SortType     string   `description:"排序类型"`
	SortParam    string   `description:"排序参数"`
	PageSize     int
	CurrentIndex int
}

// SmmIndexExistCheckReq
type SmmIndexExistCheckReq struct {
	Types      []string `description:"分类"`
	Frequency  string   `description:"频度"`
	DataState  string   `description:"数据状态"`
	EdbCode    string   `description:"指标代码"`
	SelectAll  bool     `description:"是否全选"`
	Keyword    string   `description:"关键字"`
}
