package models

import (
	"context"
	"eta/eta_mini_crm_ht/utils"
	"fmt"

	"github.com/beego/beego/v2/client/orm"
)

type SysDepartment struct {
	SysDepartmentId   int    `orm:"pk" description:"部门id"`
	SysDepartmentName string `description:"部门名称"`
	Sort              int    `description:"排序"`
	Level             int    `description:"层级"`
	ParentId          int    `description:"父目录id"`
}

func (s *SysDepartment) Add() (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(s)
	return
}

func (s *SysDepartment) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(s, cols...)
	return
}

type SysDepartmentList struct {
	SysDepartmentId   int                  `description:"部门id"`
	SysDepartmentName string               `description:"部门名称"`
	Child             []*SysDepartmentList `description:"分组"`
	Level             int                  `description:"1:部门, 2|3:分组"`
	ParentId          int                  `description:"父目录id"`
}

func DeleteSysDepartmentById(sysDepartmentIds []string, level int) (err error) {
	o := orm.NewOrm()
	err = o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
		sql := `DELETE FROM sys_department WHERE sys_department_id IN (?) `
		_, e := txOrm.QueryTable(&SysDepartment{}).
			Filter("sys_department_id__in", sysDepartmentIds).
			Delete()
		if e != nil {
			return e
		}
		if level == 1 {
			sql = `DELETE FROM sys_user_department_mapping WHERE sys_department_id1=?`
			_, e = txOrm.Raw(sql, sysDepartmentIds[0]).Exec()
			if e != nil {
				return e
			}
		} else {
			sql = `UPDATE sys_user_department_mapping SET `
			for i := level; i <= utils.MaxDepartmentLevel; i++ {
				sql += fmt.Sprintf("sys_department_id%d=0 ", i)
				if i != utils.MaxDepartmentLevel {
					sql += ","
				}
			}
			sql += fmt.Sprintf("WHERE sys_department_id%d=?", level)
			_, e = txOrm.Raw(sql, sysDepartmentIds[0]).Exec()
			if e != nil {
				return e
			}
		}
		return nil
	})
	return
}

func DeleteSysDepartmentByIdV2(sysDepartmentIds []string, level int) (err error) {
	o := orm.NewOrm()
	err = o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
		// sql := `DELETE FROM sys_department WHERE sys_department_id IN (?) `
		_, e := txOrm.QueryTable(&SysDepartment{}).
			Filter("sys_department_id__in", sysDepartmentIds).
			Delete()
		if e != nil {
			return e
		}
		sql := `UPDATE sys_user SET `
		for i := level; i <= utils.MaxDepartmentLevel; i++ {
			sql += fmt.Sprintf("sys_department_id%d=0 ", i)
			if i != utils.MaxDepartmentLevel {
				sql += ","
			}
		}
		sql += fmt.Sprintf("WHERE sys_department_id%d=?", level)
		_, e = txOrm.Raw(sql, sysDepartmentIds[0]).Exec()
		if e != nil {
			return e
		}
		return nil
	})
	return
}

func UpdateDepartmentSortByIds(sysDepartmentIds []int) (err error) {
	o := orm.NewOrm()
	err = o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
		sql := `UPDATE sys_department SET sort=? WHERE sys_department_id=?`
		for i, depId := range sysDepartmentIds {
			_, e := txOrm.Raw(sql, i+1, depId).Exec()
			if e != nil {
				return e
			}
		}
		return nil
	})
	return
}

func GetSysDepartmentById(sysDepartmentId int) (item *SysDepartment, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department WHERE sys_department_id=? `
	err = o.Raw(sql, sysDepartmentId).QueryRow(&item)
	return
}

func GetSysDepartments() (items []*SysDepartment, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetSysDepartmentList() (items []*SysDepartmentList, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department ORDER BY sort`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetSysDepartmentCountById(sysDepartmentId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_department WHERE sys_department_id=?`
	err = o.Raw(sql, sysDepartmentId).QueryRow(&count)
	return
}

func GetSysDepartmentCountByParentId(parentId int, sysDepartmentName string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_department WHERE parent_id=? AND sys_department_name=?`
	err = o.Raw(sql, parentId, sysDepartmentName).QueryRow(&count)
	return
}

func GetSysDepartmentCountByName(sysDepartmentName string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_department WHERE sys_department_name=?`
	err = o.Raw(sql, sysDepartmentName).QueryRow(&count)
	return
}

func GetSysDepartmentByName(sysDepartmentName string) (item *SysDepartment, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department WHERE sys_department_name=?`
	err = o.Raw(sql, sysDepartmentName).QueryRow(&item)
	return
}

func GetSysDepartmentListByParentId(parentId int) (item SysDepartmentList, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department WHERE sys_department_id=? `
	err = o.Raw(sql, parentId).QueryRow(&item)
	return
}

func GetChildSysDepartmentListById(sysDepartmentId int) (items []*SysDepartmentList, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department WHERE parent_id=? `
	_, err = o.Raw(sql, sysDepartmentId).QueryRows(&items)
	return
}

func GetChildSysDepartmentListByIds(sysDepartmentIds string) (items []*SysDepartmentList, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_department WHERE parent_id in (?) `
	_, err = o.Raw(sql, sysDepartmentIds).QueryRows(&items)
	return
}
