package models

import (
	"errors"
	"eta/eta_index_lib/utils"
	"github.com/beego/beego/v2/client/orm"
	"strconv"
	"time"
)

type EdbClassify struct {
	ClassifyId      int       `orm:"column(classify_id);pk"`
	ClassifyType    uint8     `description:"分类类型，0：普通指标分类，1：预测指标分类"`
	ClassifyName    string    `description:"分类名称"`
	ParentId        int       `description:"父级id"`
	RootId          int       `description:"顶级id"`
	HasData         int       `description:"是否含有指标数据"`
	CreateTime      time.Time `description:"创建时间"`
	ModifyTime      time.Time `description:"修改时间"`
	SysUserId       int       `description:"创建人id"`
	SysUserRealName string    `description:"创建人姓名"`
	Level           int       `description:"层级"`
	UniqueCode      string    `description:"唯一编码"`
	Sort            int       `description:"排序字段，越小越靠前，默认值：10"`
}

func AddEdbClassify(item *EdbClassify) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

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

func GetEdbClassifyById(classifyId int) (item *EdbClassify, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM edb_classify WHERE classify_id=? `
	err = o.Raw(sql, classifyId).QueryRow(&item)
	return
}

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

// 递归获取所有目录
func GetClassifyAllByClassifyId(classifyId int) (resultList []*EdbClassifySimplify, err error) {
	o := orm.NewOrm()
	for {
		sql := ` SELECT * FROM edb_classify AS a WHERE a.classify_id=? order by sort asc,classify_id asc`
		item := new(EdbClassifySimplify)
		err = o.Raw(sql, classifyId).QueryRow(&item)
		if err != nil {
			break
		}
		if item.ClassifyId > 0 {
			resultList = append(resultList, item)
			classifyId = item.ParentId
		} else {
			break
		}
	}
	return resultList, err
}

// 判断分类名称是否存在
func GetEdbClassifyCount(classifyName string, parentId int, classifyType uint8) (item *EdbClassify, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM edb_classify WHERE parent_id=? AND classify_name=? AND classify_type = ? `
	err = o.Raw(sql, parentId, classifyName, classifyType).QueryRow(&item)
	return
}

// GetEdbClassifyMaxSort 获取分类下最大的排序数
func GetEdbClassifyMaxSort(parentId int, classifyType uint8) (sort int, err error) {
	o := orm.NewOrm()
	sql := `SELECT Max(sort) AS sort FROM edb_classify WHERE parent_id=? AND classify_type=? `
	err = o.Raw(sql, parentId, classifyType).QueryRow(&sort)
	return
}

type AddEdbClassifyReq struct {
	ClassifyName string `description:"分类名称"`
	ParentId     int    `description:"父级id,第一级传0"`
	Level        int    `description:"层级,第一级传0，其余传上一级的层级"`
	ClassifyType uint8  `description:"分类类型，0：普通指标分类，1：预测指标分类"`
}

// AddEdbClassify 添加指标分类
func SaveEdbClassify(classifyName string, parentId, level int, classifyType uint8, sysUserId, sysUserName string) (classifyInfo *EdbClassify, err error, errMsg string) {
	edbClassify, err := GetEdbClassifyCount(classifyName, parentId, classifyType)

	var isAdd bool
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			isAdd = true
		} else {
			errMsg = `判断名称是否已存在失败`
			return
		}
	}

	if edbClassify != nil && edbClassify.ClassifyId > 0 {
		classifyInfo = edbClassify
		return edbClassify, nil, ""
	} else {
		isAdd = true
	}
	if isAdd {
		sysUserIdInt, _ := strconv.Atoi(sysUserId)
		//获取该层级下最大的排序数
		maxSort, e := GetEdbAndClassifyMaxSort(parentId, classifyType)
		if e != nil {
			errMsg = "查询分类信息出错" + e.Error()
			err = errors.New(errMsg)
			return
		}
		rootId := 0
		if parentId > 0 {
			parentClassify, tErr := GetEdbClassifyById(parentId)
			if tErr != nil {
				if tErr.Error() == utils.ErrNoRow() {
					errMsg = "父级分类不存在"
					err = errors.New(errMsg)
					return
				}
				errMsg = "获取失败"
				err = errors.New("获取分类信息失败，Err:" + tErr.Error())
				return
			}
			rootId = parentClassify.RootId
		}
		timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
		classifyInfo = &EdbClassify{
			//ClassifyId:      0,
			ClassifyType:    classifyType,
			ClassifyName:    classifyName,
			ParentId:        parentId,
			RootId:          rootId,
			HasData:         0,
			CreateTime:      time.Now(),
			ModifyTime:      time.Now(),
			SysUserId:       sysUserIdInt,
			SysUserRealName: sysUserName,
			Level:           level + 1,
			UniqueCode:      utils.MD5(utils.DATA_PREFIX + "_" + timestamp),
			Sort:            maxSort + 1,
		}
		var classifyId int64
		classifyId, err = AddEdbClassify(classifyInfo)
		if err != nil {
			errMsg = "保存分类失败"
			return
		}
		classifyInfo.ClassifyId = int(classifyId)
		if parentId == 0 { //一级目录的rootId等于自己本身
			classifyInfo.RootId = int(classifyId)
			err = classifyInfo.Update([]string{"RootId"})
			if err != nil {
				errMsg = "更新分类失败"
				return
			}
		}
	}
	return
}
