package data_manage

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

// BaseFromMysteelChemicalClassify 上海钢联分类表
type BaseFromMysteelChemicalClassify struct {
	BaseFromMysteelChemicalClassifyId int       `orm:"column(base_from_mysteel_chemical_classify_id);pk"`
	ClassifyName                      string    `description:"分类名称"`
	ParentId                          int       `description:"父级id"`
	SysUserId                         int       `description:"创建人id"`
	SysUserRealName                   string    `description:"创建人姓名"`
	Level                             int       `description:"层级"`
	Sort                              int       `description:"排序字段，越小越靠前，默认值：10"`
	ModifyTime                        time.Time `description:"修改时间"`
	CreateTime                        time.Time `description:"创建时间"`
}

// AddBaseFromMysteelChemicalClassify 添加上海钢联分类
func AddBaseFromMysteelChemicalClassify(item *BaseFromMysteelChemicalClassify) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("data")
	lastId, err = o.Insert(item)
	return
}

// GetBaseFromMysteelChemicalClassifyCount 获取分类名称的个数
func GetBaseFromMysteelChemicalClassifyCount(classifyName string, parentId int) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT COUNT(1) AS count FROM base_from_mysteel_chemical_classify WHERE classify_name=? AND parent_id=? `
	err = o.Raw(sql, classifyName, parentId).QueryRow(&count)
	return
}

// GetBaseFromMysteelChemicalClassifyById 通过分类id的获取分类信息
func GetBaseFromMysteelChemicalClassifyById(classifyId int) (item *BaseFromMysteelChemicalClassify, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_mysteel_chemical_classify WHERE base_from_mysteel_chemical_classify_id=? `
	err = o.Raw(sql, classifyId).QueryRow(&item)
	return
}

// EditBaseFromMysteelChemicalClassify 修改上海钢联分类
func EditBaseFromMysteelChemicalClassify(classifyId int, classifyName string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `UPDATE base_from_mysteel_chemical_classify SET classify_name=?,modify_time=NOW() WHERE base_from_mysteel_chemical_classify_id=? `
	_, err = o.Raw(sql, classifyName, classifyId).Exec()
	return
}

type BaseFromMysteelChemicalIndexResp struct {
	List []*BaseFromMysteelChemicalClassifyItems
}
type BaseFromMysteelChemicalClassifyItems struct {
	BaseFromMysteelChemicalClassifyId int                                        `orm:"column(base_from_mysteel_chemical_classify_id)"`
	BaseFromMysteelChemicalIndexId    int                                        `orm:"column(base_from_mysteel_chemical_index_id)"`
	IndexCode                         string                                     `description:"指标编码"`
	ClassifyName                      string                                     `description:"分类名称"`
	ParentId                          int                                        `description:"父级id"`
	SysUserId                         int                                        `description:"创建人id"`
	SysUserRealName                   string                                     `description:"创建人姓名"`
	Level                             int                                        `description:"层级"`
	Sort                              int                                        `description:"排序字段，越小越靠前，默认值：10"`
	UniqueCode                        string                                     `description:"唯一编码"`
	ModifyTime                        time.Time                                  `description:"修改时间"`
	CreateTime                        time.Time                                  `description:"创建时间"`
	Button                            BaseFromMysteelChemicalClassifyItemsButton `description:"操作权限"`
	Children                          []*BaseFromMysteelChemicalClassifyItems    `description:"下级"`
}

type BaseFromMysteelChemicalClassifyItemsButton struct {
	AddButton    bool `description:"是否可添加"`
	OpButton     bool `description:"是否可编辑"`
	DeleteButton bool `description:"是否可删除"`
	MoveButton   bool `description:"是否可移动"`
}

// GetBaseFromMysteelChemicalClassifyByParentId 根据上级id获取当下的分类列表数据
func GetBaseFromMysteelChemicalClassifyByParentId(parentId int) (items []*BaseFromMysteelChemicalClassifyItems, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_mysteel_chemical_classify WHERE parent_id=? order by sort asc,base_from_mysteel_chemical_classify_id asc`
	_, err = o.Raw(sql, parentId).QueryRows(&items)
	return
}

// GetBaseFromMysteelChemicalClassifyByIds 根据id获取当下的分类列表数据
func GetBaseFromMysteelChemicalClassifyByIds(classifyIds []int) (items []*BaseFromMysteelChemicalClassifyItems, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_mysteel_chemical_classify WHERE parent_id > 0 and base_from_mysteel_chemical_classify_id IN (` + utils.GetOrmInReplace(len(classifyIds)) + `) order by sort asc,base_from_mysteel_chemical_classify_id asc`
	_, err = o.Raw(sql, classifyIds).QueryRows(&items)
	return
}

// GetAllBaseFromMysteelChemicalClassify 获取所有的分类列表数据
func GetAllBaseFromMysteelChemicalClassify() (items []*BaseFromMysteelChemicalClassifyItems, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_mysteel_chemical_classify WHERE parent_id <> 0 order by sort asc,base_from_mysteel_chemical_classify_id asc`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type DeleteBaseFromMysteelChemicalClassifyReq struct {
	ClassifyId int `description:"分类id"`
	EdbInfoId  int `description:"指标id"`
}

type BaseFromMysteelChemicalClassifyListResp struct {
	AllNodes      []*BaseFromMysteelChemicalClassifyItems
	CanOpClassify bool `description:"是否允许操作分类"`
}

type BaseFromMysteelChemicalClassifySimplify struct {
	ClassifyId   int    `description:"分类id"`
	ClassifyName string `description:"分类名称"`
	ParentId     int
}

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

// UpdateBaseFromMysteelChemicalClassifySortByClassifyId 根据分类id更新排序
func UpdateBaseFromMysteelChemicalClassifySortByClassifyId(parentId, classifyId, nowSort int, updateSort string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` update base_from_mysteel_chemical_classify set sort = ` + updateSort + ` WHERE parent_id=? AND sort > ? `
	if classifyId > 0 {
		sql += ` or ( base_from_mysteel_chemical_classify_id > ` + fmt.Sprint(classifyId) + ` and sort = ` + fmt.Sprint(nowSort) + `)`
	}
	_, err = o.Raw(sql, parentId, nowSort).Exec()
	return
}

// Update 更新分类基础信息
func (BaseFromMysteelChemicalClassify *BaseFromMysteelChemicalClassify) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(BaseFromMysteelChemicalClassify, cols...)
	return
}

// GetBaseFromMysteelChemicalClassifyMaxSort 获取分类下最大的排序数
func GetBaseFromMysteelChemicalClassifyMaxSort(parentId int) (sort int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT Max(sort) AS sort FROM base_from_mysteel_chemical_classify WHERE parent_id=? `
	err = o.Raw(sql, parentId).QueryRow(&sort)
	return
}

// DeleteMysteelChemicalByClassifyId 根据分类id删除对应的指标分类、指标、指标数据
func DeleteMysteelChemicalByClassifyId(classifyIdList []int, mysteelChemicalIndexIdList []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()
		}
	}()
	num := len(classifyIdList)
	if num <= 0 {
		return
	}

	//删除分类
	sql := `DELETE FROM base_from_mysteel_chemical_classify  WHERE base_from_mysteel_chemical_classify_id IN (` + utils.GetOrmInReplace(num) + `) `
	_, err = to.Raw(sql, classifyIdList).Exec()
	if err != nil {
		return
	}

	//删除指标
	sql = `DELETE FROM base_from_mysteel_chemical_index WHERE base_from_mysteel_chemical_classify_id IN (` + utils.GetOrmInReplace(num) + `) `
	_, err = to.Raw(sql, classifyIdList).Exec()
	if err != nil {
		return
	}

	//删除指标数据
	indexNum := len(mysteelChemicalIndexIdList)
	if indexNum > 0 {
		sql = `DELETE FROM base_from_mysteel_chemical_data WHERE base_from_mysteel_chemical_index_id in (` + utils.GetOrmInReplace(indexNum) + `) `
		_, err = to.Raw(sql, mysteelChemicalIndexIdList).Exec()
		if err != nil {
			return
		}
	}

	return
}

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

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

	return
}
