package eta_trial

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

// ETATrialManualClassify ETA试用-手工数据分类
type ETATrialManualClassify struct {
	ClassifyId   int    `description:"分类ID"`
	ClassifyName string `description:"分类名称"`
	ParentId     int    `description:"父级ID"`
}

// GetETATrialManualClassify 获取ETA试用手工数据分类
func GetETATrialManualClassify() (items []*ETATrialManualClassify, err error) {
	o := orm.NewOrmUsingDB("weekly_trial")
	sql := `SELECT classify_id, classify_name, parent_id FROM edb_trial_new.edbdata_classify WHERE is_show=1 ORDER BY sort ASC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// ETATrialUserAdmin ETA试用-试用客户
type ETATrialUserAdmin struct {
	AdminId  int    `description:"用户ID"`
	RealName string `description:"用户姓名"`
}

// GetNoAuthTrialUserIds 查询未分配手工权限的试用客户
func GetNoAuthTrialUserIds() (items []*ETATrialUserAdmin, err error) {
	o := orm.NewOrmUsingDB("weekly_trial")
	sql := `SELECT a.admin_id, a.real_name FROM weekly_report_trial.admin AS a
			WHERE a.admin_id NOT IN (
				SELECT DISTINCT b.admin_id FROM hz_data_trial_new.manual_user_classify AS b
			)
			AND a.department_id = 12 AND a.department_name = "ETA试用客户"`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// InsertTrialUserManualAuth 新增试用客户手工录入权限
func InsertTrialUserManualAuth(adminId int, adminRealName string, classifyIds []int) (err error) {
	o := orm.NewOrmUsingDB("weekly_trial")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 新增权限用户
	sql := `INSERT INTO hz_data_trial_new.manual_user (admin_id, admin_real_name, sys_user_id, sys_user_real_name, create_time) VALUES ("%d", "%s", 0, "", NOW())`
	sql = fmt.Sprintf(sql, adminId, adminRealName)
	if _, err = tx.Raw(sql).Exec(); err != nil {
		return
	}
	// 新增权限分类
	for i := range classifyIds {
		sql = `INSERT INTO hz_data_trial_new.manual_user_classify (admin_id, classify_id, create_time) VALUES ("%d", "%d", NOW())`
		sql = fmt.Sprintf(sql, adminId, classifyIds[i])
		if _, err = tx.Raw(sql).Exec(); err != nil {
			return
		}
	}
	return
}
