package data_manage

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

// BaseFromBusinessData
// @Description: 外部指标（商家系统）原始数据表
type BaseFromBusinessData struct {
	BusinessDataId          int       `orm:"column(business_data_id);pk" json:"business_data_id"`
	BaseFromBusinessIndexId int       `json:"base_from_business_index_id"` // 指标id
	IndexCode               string    `json:"index_code"`                  // 指标编码
	DataTime                time.Time `json:"data_time"`                   // 数据日期
	Value                   float64   `json:"value"`                       // 数据值
	CreateTime              time.Time `json:"create_time"`                 // 创建时间
	ModifyTime              time.Time `json:"modify_time"`                 // 修改时间
}

// TableName
// @Description:  获取表名
// @author: Roc
// @receiver m
// @datetime 2024-04-26 13:41:36
// @return string
func (m *BaseFromBusinessData) TableName() string {
	return "base_from_business_data"
}

// CollectionName
// @Description:  获取集合名称
// @author: Roc
// @receiver m
// @datetime 2024-04-26 13:41:36
// @return string
func (m *BaseFromBusinessData) CollectionName() string {
	return "base_from_business_data"
}

// DataBaseName
// @Description: 获取数据库名称
// @author: Roc
// @receiver m
// @datetime 2024-04-26 13:41:33
// @return string
func (m *BaseFromBusinessData) DataBaseName() string {
	return utils.MgoDataDbName
}

type WhereParams struct {
	Condition string
	Pars      []interface{}
	Order     string `description:"排序字段"`
}

// GetAllDataList
// @Description: 根据条件获取所有数据
// @author: Roc
// @receiver m
// @datetime 2024-04-26 13:42:19
// @param sort []string
// @param whereParams interface{}
// @return result []BaseFromBusinessData
// @return err error
func (m *BaseFromBusinessData) GetAllDataList(condition string, pars []interface{}, order string) (result []*BaseFromBusinessData, err error) {
	o := orm.NewOrmUsingDB("data")

	sql := `SELECT * FROM base_from_business_data WHERE 1=1 `
	if condition != `` {
		sql += ` ` + condition
	}

	if order != `` {
		sql += ` ORDER BY ` + order
	}

	_, err = o.Raw(sql, pars).QueryRows(&result)

	return
}

// GetLimitDataList
// @Description: 根据条件获取指定数量数据列表
// @author: Roc
// @receiver m
// @datetime 2024-05-06 17:08:32
// @param whereParams interface{}
// @param size int64
// @return result []*BaseFromBusinessData
// @return err error
func (m *BaseFromBusinessData) GetLimitDataList(condition string, pars []interface{}, order string, size int64) (result []*BaseFromBusinessData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_business_data WHERE 1=1 `
	if condition != `` {
		sql += ` ` + condition
	}

	if order != `` {
		sql += ` ORDER BY ` + order
	}

	sql += fmt.Sprintf(` LIMIT %d`, size)

	_, err = o.Raw(sql, pars).QueryRows(&result)

	return
}

// GetPageDataList
// @Description: 根据条件获取分页数据列表
// @author: Roc
// @receiver m
// @datetime 2024-05-07 10:21:07
// @param whereParams interface{}
// @param startSize int64
// @param size int64
// @param sort []string
// @return result []*BaseFromBusinessData
// @return err error
func (m *BaseFromBusinessData) GetPageDataList(condition []string, pars []interface{}, order string, startSize, size int64) (result []*BaseFromBusinessData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_business_data `
	if len(condition) > 0 {
		sql += ` WHERE ` + strings.Join(condition, " AND ")
	}

	if order != `` {
		sql += ` ORDER BY ` + order
	}

	sql += fmt.Sprintf(` LIMIT %d,%d`, startSize, size)

	_, err = o.Raw(sql, pars).QueryRows(&result)

	return
}

// GetCountDataList
// @Description:  根据条件获取数据列表总数
// @author: Roc
// @receiver m
// @datetime 2024-05-07 10:29:00
// @param whereParams interface{}
// @return count int64
// @return err error
func (m *BaseFromBusinessData) GetCountDataList(condition []string, pars []interface{}) (count int64, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT COUNT(1) FROM base_from_business_data `
	if len(condition) > 0 {
		sql += ` WHERE ` + strings.Join(condition, " AND ")
	}
	err = o.Raw(sql, pars).QueryRow(&count)

	return
}

// InsertDataByColl
// @Description: 写入单条数据（外部传入集合）
// @author: Roc
// @receiver m
// @datetime 2024-04-26 14:22:18
// @param addData interface{}
// @return err error
func (m *BaseFromBusinessData) InsertDataByColl(addData interface{}) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Insert(addData)

	return
}

// BatchInsertData
// @Description: 批量写入数据
// @author: Roc
// @receiver m
// @datetime 2024-04-26 14:22:18
// @param bulk int 每次请求保存的数据量
// @param dataList []interface{}
// @return err error
func (m *BaseFromBusinessData) BatchInsertData(bulk int, dataList []interface{}) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.InsertMulti(bulk, dataList)

	return
}

// UpdateData
// @Description: 单条数据修改
// @author: Roc
// @receiver m
// @datetime 2024-04-26 15:01:51
// @param whereParams interface{}
// @param updateParams interface{}
// @return err error
func (m *BaseFromBusinessData) UpdateData(updateCols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, updateCols...)
	if err != nil {
		fmt.Println("UpdateDataByColl:Err:" + err.Error())
		return
	}

	return
}

// GetEdbInfoMaxAndMinInfo
// @Description: 获取当前指标的最大最小值
// @author: Roc
// @receiver m
// @datetime 2024-04-30 17:15:39
// @param whereParams interface{}
// @return result EdbInfoMaxAndMinInfo
// @return err error
func (m *BaseFromBusinessData) GetEdbInfoMaxAndMinInfo(indexCode string) (result EdbInfoMaxAndMinInfo, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ``
	sql = ` SELECT MIN(data_time) AS min_date,MAX(data_time) AS max_date,MIN(value) AS min_value,MAX(value) AS max_value FROM base_from_business_data WHERE index_code = ? `
	err = o.Raw(sql, indexCode).QueryRow(&result)
	if err != nil {
		return
	}

	var latestValue float64
	sql = ` SELECT value AS latest_value FROM base_from_business_data WHERE index_code = ? ORDER BY data_time DESC LIMIT 1 `
	err = o.Raw(sql, indexCode).QueryRow(&latestValue)
	result.LatestValue = latestValue

	return
}
