package trade_analysis

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

// WareHouseProcessClassify 建仓过程分类表
type WareHouseProcessClassify struct {
	WareHouseProcessClassifyId int       `orm:"column(warehouse_process_classify_id);pk"`
	ClassifyName               string    `description:"分类名称"`
	ClassifyNameEn             string    `description:"英文分类名称"`
	ParentId                   int       `description:"父级ID"`
	SysUserId                  int       `description:"创建人ID"`
	SysUserRealName            string    `description:"创建人姓名"`
	Level                      int       `description:"层级"`
	Sort                       int       `description:"排序"`
	RootId                     int       `description:"顶级分类ID"`
	LevelPath                  string    `description:"层级路径"`
	UniqueCode                 string    `description:"唯一编码"`
	CreateTime                 time.Time `description:"创建时间"`
	ModifyTime                 time.Time `description:"修改时间"`
}

func (m *WareHouseProcessClassify) TableName() string {
	return "warehouse_process_classify"
}

type WareHouseProcessClassifyCols struct {
	PrimaryId       string
	ClassifyName    string
	ClassifyNameEn  string
	ParentId        string
	SysUserId       string
	SysUserRealName string
	Level           string
	Sort            string
	RootId          string
	LevelPath       string
	UniqueCode      string
	CreateTime      string
	ModifyTime      string
}

func (m *WareHouseProcessClassify) Cols() WareHouseProcessClassifyCols {
	return WareHouseProcessClassifyCols{
		PrimaryId:       "warehouse_process_classify_id",
		ClassifyName:    "classify_name",
		ClassifyNameEn:  "classify_name_en",
		ParentId:        "parent_id",
		SysUserId:       "sys_user_id",
		SysUserRealName: "sys_user_real_name",
		Level:           "level",
		Sort:            "sort",
		RootId:          "root_id",
		LevelPath:       "level_path",
		UniqueCode:      "unique_code",
		CreateTime:      "create_time",
		ModifyTime:      "modify_time",
	}
}

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

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

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

func (m *WareHouseProcessClassify) 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.WareHouseProcessClassifyId).Exec()
	return
}

func (m *WareHouseProcessClassify) 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 *WareHouseProcessClassify) 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 *WareHouseProcessClassify) GetItemById(id int) (item *WareHouseProcessClassify, 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 *WareHouseProcessClassify) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *WareHouseProcessClassify, 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 *WareHouseProcessClassify) 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 *WareHouseProcessClassify) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*WareHouseProcessClassify, 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 *WareHouseProcessClassify) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*WareHouseProcessClassify, 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
}

// WareHouseProcessClassifyItem 建仓过程分类信息
type WareHouseProcessClassifyItem struct {
	ClassifyId     int                             `description:"分类ID"`
	ClassifyName   string                          `description:"分类名称"`
	ClassifyNameEn string                          `description:"英文分类名称"`
	ParentId       int                             `description:"父级ID"`
	Level          int                             `description:"层级"`
	Sort           int                             `description:"排序"`
	LevelPath      string                          `description:"层级路径"`
	UniqueCode     string                          `description:"唯一编码"`
	Children       []*WareHouseProcessClassifyItem `description:"子分类"`
}

func (m *WareHouseProcessClassify) Format2Item() (item *WareHouseProcessClassifyItem) {
	item = new(WareHouseProcessClassifyItem)
	item.ClassifyId = m.WareHouseProcessClassifyId
	item.ClassifyName = m.ClassifyName
	item.ClassifyNameEn = m.ClassifyNameEn
	item.ParentId = m.ParentId
	item.Level = m.Level
	item.Sort = m.Sort
	item.LevelPath = m.LevelPath
	item.UniqueCode = m.UniqueCode
	item.Children = make([]*WareHouseProcessClassifyItem, 0)
	return
}

// ------------------------------------------------ 通用分类 ------------------------------------------------

// GetCommonClassifyCols 通用分类字段映射
func (m *WareHouseProcessClassify) GetCommonClassifyCols() models.CommonClassifyCols {
	return models.CommonClassifyCols{
		ClassifyId:   m.Cols().PrimaryId,
		ClassifyName: m.Cols().ClassifyName,
		ParentId:     m.Cols().ParentId,
		Sort:         m.Cols().ParentId,
		RootId:       m.Cols().RootId,
		Level:        m.Cols().Level,
		LevelPath:    m.Cols().LevelPath,
		CreateTime:   m.Cols().CreateTime,
		ModifyTime:   m.Cols().ModifyTime,
	}
}

// GetCommonClassifyById 获取通用分类
func (m *WareHouseProcessClassify) GetCommonClassifyById(classifyId int) (commonClassify *models.CommonClassify, err error) {
	item, e := m.GetItemById(classifyId)
	if e != nil {
		err = e
		return
	}
	commonClassify = new(models.CommonClassify)
	commonClassify.ClassifyId = item.WareHouseProcessClassifyId
	commonClassify.ClassifyName = item.ClassifyName
	commonClassify.ParentId = item.ParentId
	commonClassify.RootId = item.RootId
	commonClassify.Level = item.Level
	commonClassify.LevelPath = item.LevelPath
	commonClassify.Sort = item.Sort
	commonClassify.CreateTime = item.CreateTime
	commonClassify.ModifyTime = item.ModifyTime
	return
}

// GetClassifyByParentIdAndName 实现获取分类信息的方法
func (m *WareHouseProcessClassify) GetClassifyByParentIdAndName(parentId int, name string, excludeId int) (*models.CommonClassify, error) {
	// 实现获取分类信息的逻辑
	return nil, nil
}

// UpdateCommonClassify 实现更新分类信息的方法
func (m *WareHouseProcessClassify) UpdateCommonClassify(classify *models.CommonClassify, updateCols []string) (err error) {
	return
}

func (m *WareHouseProcessClassify) UpdateClassifyChildByParentId(classifyIds []int, rootId int, stepLevel int) (err error) {
	//	o := orm.NewOrmUsingDB("data")
	//	var pars []interface{}
	//	pars = append(pars, rootId, levelStep)
	//	pars = append(pars, classifyIds)
	//	// 更新相关联的二级分类的parentId,和classify_name_second
	//	sql := `update edb_classify
	//SET root_id = ?, level = level+?
	//where classify_id IN (` + utils.GetOrmInReplace(len(classifyIds)) + `)`
	//	_, err = o.Raw(sql, pars).Exec()
	//	if err != nil {
	//		return
	//	}
	return
}

// GetClassifySortMaxByParentId 实现获取分类排序的方法
func (m *WareHouseProcessClassify) GetClassifySortMaxByParentId(parentId int) (sortMax int, err error) {
	//	o := orm.NewOrmUsingDB("data")
	//	sql := `SELECT Max(sort) AS sort FROM edb_classify WHERE parent_id=? AND classify_type=? `
	//	err = o.Raw(sql, parentId, classifyType).QueryRow(&sort)
	//	return
	return
}

func (m *WareHouseProcessClassify) GetFirstClassifyByParentId(parentId int) (item *models.CommonClassify, err error) {
	//o := orm.NewOrmUsingDB("data")
	//sql := ` SELECT * FROM edb_classify WHERE parent_id=? order by sort asc,classify_id asc limit 1`
	//err = o.Raw(sql, parentId).QueryRow(&item)
	return
}

// SetClassifySortByParentId 实现设置分类排序的方法
func (m *WareHouseProcessClassify) SetClassifySortByParentId(parentId, classifyId, sort int, sortUpdate string) (err error) {
	//o := orm.NewOrmUsingDB("data")
	//sql := ` update edb_classify set sort = ` + updateSort + ` WHERE parent_id=? AND sort > ? AND classify_type = ? `
	//if classifyId > 0 {
	//	sql += ` or ( classify_id > ` + fmt.Sprint(classifyId) + ` and sort = ` + fmt.Sprint(nowSort) + `)`
	//}
	//_, err = o.Raw(sql, parentId, nowSort, classifyType).Exec()
	return
}

// GetCommonClassifyObjCols 通用分类对象字段映射
func (m *WareHouseProcessClassify) GetCommonClassifyObjCols() models.CommonClassifyObjCols {
	// TODO: 完善
	return models.CommonClassifyObjCols{
		ObjectId:   m.Cols().ClassifyName,
		ClassifyId: m.Cols().PrimaryId,
		Sort:       m.Cols().ParentId,
	}
}

func (m *WareHouseProcessClassify) GetObjectById(objectId int) (*models.CommonClassifyObj, error) {
	// 实现获取分类信息的逻辑
	return nil, nil
}

// GetObjectSortMaxByClassifyId 获取分类下最大排序
func (m *WareHouseProcessClassify) GetObjectSortMaxByClassifyId(classifyId int) (sortMax int, err error) {
	//	o := orm.NewOrmUsingDB("data")
	//	sql := `SELECT Max(sort) AS sort FROM edb_info WHERE classify_id=? `
	//	err = o.Raw(sql, classifyId).QueryRow(&sort)
	//	return
	return
}

func (m *WareHouseProcessClassify) GetFirstObjectByClassifyId(classifyId int) (item *models.CommonClassifyObj, err error) {
	//o := orm.NewOrmUsingDB("data")
	//sql := ` SELECT * FROM edb_info WHERE classify_id=? order by sort asc,edb_info_id asc limit 1`
	//err = o.Raw(sql, classifyId).QueryRow(&item)
	return
}

func (m *WareHouseProcessClassify) SetObjectSortByClassifyId(classifyId, sort, prevObjectId int, sortUpdate string) (err error) {
	//o := orm.NewOrmUsingDB("data")
	//sql := ` update edb_info set sort = ` + updateSort + ` WHERE classify_id=?`
	//if prevEdbInfoId > 0 {
	//	sql += ` AND ( sort > ? or ( edb_info_id > ` + fmt.Sprint(prevEdbInfoId) + ` and sort=` + fmt.Sprint(nowSort) + ` )) `
	//} else {
	//	sql += ` AND ( sort > ? )`
	//}
	//_, err = o.Raw(sql, classifyId, nowSort).Exec()
	return
}

// UpdateCommonClassifyObj 更新通用分类对象
func (m *WareHouseProcessClassify) UpdateCommonClassifyObj(object *models.CommonClassifyObj, updateCols []string) (err error) {
	return
}

// ------------------------------------------------ 通用分类 ------------------------------------------------