package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/models/system"
)

type AskEmailRep struct {
	Name                string `description:"姓名"`
	Email               string `description:"邮箱"`
	Mobile              string `description:"手机号"`
	ChartPermissionName string `description:"权限名称"`
	AdminId             int
}

func GetAskEmail() (item []*AskEmailRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_ask_email`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 判断研究员是不是策略行业的
func GetAskEmailCountByCelue(adminId string) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity_ask_email  WHERE chart_permission_name  = '策略'  AND admin_id IN (` + adminId + `)  `
	err = o.Raw(sqlCount).QueryRow(&count)
	return
}

func GetAskEmailListByAdminIds(adminId string) (item []*AskEmailRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_ask_email WHERE    chart_permission_name != ''  AND admin_id IN (` + adminId + `)  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetAskEmailList() (item []*AskEmailRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_ask_email WHERE    chart_permission_name != ''  ORDER BY sort  DESC`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 权益自定义派点信息
func GetAskEmailListPoint() (item []*AskEmailRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_ask_email WHERE  chart_permission_name != ''  AND enabled_point = 1 AND admin_id > 0    ORDER BY sort  DESC , id ASC  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 权益自定义研究员信息
func GetAskEmailListResearcher() (item []*AskEmailRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_ask_email WHERE  chart_permission_name != ''  AND enabled_researcher = 1 AND admin_id > 0    ORDER BY sort  DESC , id ASC  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func UpdateAskEmail(item *AskEmailRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_ask_email SET admin_id=? where mobile=?`
	_, err = o.Raw(sql, item.AdminId, item.Mobile).Exec()
	return
}

func InitSyncActivityAskEmailAdminId() {
	list, err := GetAskEmailList()
	if err != nil {
		return
	}
	sysUserList, err := system.GetAdminList()
	if err != nil {
		return
	}
	adminMap := make(map[string]*system.Admin, 0)
	for _, v := range sysUserList {
		adminMap[v.Mobile] = v
	}
	for _, v := range list {
		if admin, ok := adminMap[v.Mobile]; ok {
			v.AdminId = admin.AdminId
			err = UpdateAskEmail(v)
			if err != nil {
				return
			}
		}
	}
}