package data_manage

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

// AiPredictModelDashboard AI预测模型-BI看板
type AiPredictModelDashboard struct {
	AiPredictModelDashboardId int       `orm:"column(ai_predict_model_dashboard_id);pk;auto"`
	AiPredictModelIndexId     int       `description:"标的ID"`
	DashboardName             string    `description:"看板名称"`
	Sort                      int       `description:"排序"`
	SysUserId                 int       `description:"创建人ID"`
	SysUserRealName           string    `description:"创建人姓名"`
	CreateTime                time.Time `description:"创建时间"`
	ModifyTime                time.Time `description:"修改时间"`
}

func (m *AiPredictModelDashboard) TableName() string {
	return "ai_predict_model_dashboard"
}

type AiPredictModelDashboardCols struct {
	PrimaryId             string
	AiPredictModelIndexId string
	DashboardName         string
	Sort                  string
	SysUserId             string
	SysUserRealName       string
	CreateTime            string
	ModifyTime            string
}

func (m *AiPredictModelDashboard) Cols() AiPredictModelDashboardCols {
	return AiPredictModelDashboardCols{
		PrimaryId:             "ai_predict_model_dashboard_id",
		AiPredictModelIndexId: "ai_predict_model_index_id",
		DashboardName:         "dashboard_name",
		Sort:                  "sort",
		SysUserId:             "sys_user_id",
		SysUserRealName:       "sys_user_real_name",
		CreateTime:            "create_time",
		ModifyTime:            "modify_time",
	}
}

func (m *AiPredictModelDashboard) Create() (err error) {
	o := orm.NewOrmUsingDB("data")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.AiPredictModelDashboardId = int(id)
	return
}

func (m *AiPredictModelDashboard) CreateMulti(items []*AiPredictModelDashboard) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *AiPredictModelDashboard) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, cols...)
	return
}

func (m *AiPredictModelDashboard) Remove() (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	_, err = o.Raw(sql, m.AiPredictModelDashboardId).Exec()
	return
}

func (m *AiPredictModelDashboard) MultiRemove(ids []int) (err error) {
	if len(ids) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.Cols().PrimaryId, utils.GetOrmInReplace(len(ids)))
	_, err = o.Raw(sql, ids).Exec()
	return
}

func (m *AiPredictModelDashboard) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	_, err = o.Raw(sql, pars).Exec()
	return
}

func (m *AiPredictModelDashboard) GetItemById(id int) (item *AiPredictModelDashboard, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *AiPredictModelDashboard) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *AiPredictModelDashboard, err error) {
	o := orm.NewOrmUsingDB("data")
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *AiPredictModelDashboard) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *AiPredictModelDashboard) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*AiPredictModelDashboard, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *AiPredictModelDashboard) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*AiPredictModelDashboard, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// AiPredictModelDashboardItem AI预测模型-BI看板
type AiPredictModelDashboardItem struct {
	DashboardId     int    `description:"看板ID"`
	IndexId         int    `description:"标的ID"`
	DashboardName   string `description:"看板名称"`
	Sort            int    `description:"排序"`
	SysUserId       int    `description:"创建人ID"`
	SysUserRealName string `description:"创建人姓名"`
	CreateTime      string `description:"创建时间"`
	ModifyTime      string `description:"修改时间"`
}

func (m *AiPredictModelDashboard) Format2Item() (item *AiPredictModelDashboardItem) {
	item = new(AiPredictModelDashboardItem)
	item.DashboardId = m.AiPredictModelDashboardId
	item.IndexId = m.AiPredictModelIndexId
	item.DashboardName = m.DashboardName
	item.Sort = m.Sort
	item.SysUserId = m.SysUserId
	item.SysUserRealName = m.SysUserRealName
	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, m.CreateTime)
	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, m.ModifyTime)
	return
}

// AiPredictModelDashboardDetailResp BI看板详情响应
type AiPredictModelDashboardDetailResp struct {
	*AiPredictModelDashboardItem
	CreateUserId       int    `description:"标的创建人ID"`
	CreateUserRealName string `description:"标的创建人姓名"`
	List               []*AiPredictModelDashboardDetailItem
}

// AiPredictModelDashboardSaveReq BI看板保存请求
type AiPredictModelDashboardSaveReq struct {
	IndexId       int    `description:"标的ID"`
	DashboardName string `description:"看板名称"`
	List          []*AiPredictModelDashboardDetailReq
}

type AiPredictModelDashboardDetailReq struct {
	Type       int
	UniqueCode string
	Sort       int
}

// SaveIndexDashboard 保存标的看板
func (m *AiPredictModelDashboard) SaveIndexDashboard(dashboardItem *AiPredictModelDashboard, dashboardDetails []*AiPredictModelDashboardDetail, isUpdate bool, updateCols []string) (err error) {
	if dashboardItem == nil {
		return
	}
	o := orm.NewOrmUsingDB("data")
	tx, e := o.Begin()
	if e != nil {
		err = fmt.Errorf("trans begin err: %v", e)
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	// 新增/更新看板
	var dashboardId int
	if !isUpdate {
		newId, e := tx.Insert(dashboardItem)
		if e != nil {
			err = fmt.Errorf("insert dashboard err: %v", e)
			return
		}
		dashboardId = int(newId)
	} else {
		_, e = tx.Update(dashboardItem, updateCols...)
		if e != nil {
			err = fmt.Errorf("update dashboard err: %v", e)
			return
		}
		dashboardId = dashboardItem.AiPredictModelDashboardId
	}

	// 清空详情并新增
	if isUpdate {
		sql := `DELETE FROM ai_predict_model_dashboard_detail WHERE ai_predict_model_dashboard_id = ?`
		_, e = tx.Raw(sql, dashboardItem.AiPredictModelDashboardId).Exec()
		if e != nil {
			err = fmt.Errorf("clear dashboard detail err: %v", e)
			return
		}
	}
	if len(dashboardDetails) > 0 {
		for _, v := range dashboardDetails {
			v.AiPredictModelDashboardId = dashboardId
		}
		_, e = tx.InsertMulti(utils.MultiAddNum, dashboardDetails)
		if e != nil {
			err = fmt.Errorf("insert dashboard detail err: %v", e)
			return
		}
	}
	return
}