package models

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

// ChartPermissionSearchKeyWordMapping 权限相关
type ChartPermissionSearchKeyWordMapping struct {
	Id                 int    `description:"id" json:"-"`
	ChartPermissionId  int    `description:"权限id"`
	KeyWord            string `description:"二级分类名称"`
	From               string `description:"类型标识" json:"-"`
	TacticType         string `description:"策略表type字段值" json:"-"`
	TeleconferenceSort int    `description:"电话会类型排序" json:"-"`
	ClassifyId         int    `description:"分类ID"`
}

func GetPermission(classifyNameSecond string) (items []*ChartPermissionSearchKeyWordMapping, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM chart_permission_search_key_word_mapping AS a WHERE a.from='rddp' AND a.key_word=? `
	_, err = o.Raw(sql, classifyNameSecond).QueryRows(&items)
	return
}

// EditChartPermissionSearchKeyWordMappingMulti 修改报告报告权限（先删除原有的权限，再添加新的权限）
func EditChartPermissionSearchKeyWordMappingMulti(keyword string, permissionIdList []int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := "delete from chart_permission_search_key_word_mapping WHERE `from`='rddp' AND key_word=? "
	_, err = to.Raw(sql, keyword).Exec()
	if err != nil {
		return
	}

	if len(permissionIdList) > 0 {
		chartPermissionSearchKeyWordMappingList := make([]*ChartPermissionSearchKeyWordMapping, 0)
		for _, permissionId := range permissionIdList {
			tmpChartPermissionSearchKeyWordMapping := &ChartPermissionSearchKeyWordMapping{
				ChartPermissionId:  permissionId,
				KeyWord:            keyword,
				From:               "rddp",
				TacticType:         "",
				TeleconferenceSort: 0,
			}
			chartPermissionSearchKeyWordMappingList = append(chartPermissionSearchKeyWordMappingList, tmpChartPermissionSearchKeyWordMapping)
		}
		_, err = to.InsertMulti(len(chartPermissionSearchKeyWordMappingList), chartPermissionSearchKeyWordMappingList)
	}
	return
}

// AddChartPermissionSearchKeyWordMappingMulti 批量新增报告权限
func AddChartPermissionSearchKeyWordMappingMulti(chartPermissionSearchKeyWordMappingList []*ChartPermissionSearchKeyWordMapping) (err error) {
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(chartPermissionSearchKeyWordMappingList), chartPermissionSearchKeyWordMappingList)
	return
}

func AddChartPermissionChapterMapping(chartPermissionId int, reportId int64) (err error) {
	sql := `INSERT INTO chart_permission_chapter_mapping (chart_permission_id, report_chapter_type_id,research_type)
          VALUES(?,?,?)`
	o := orm.NewOrm()
	_, err = o.Raw(sql, chartPermissionId, reportId, "rddp").Exec()
	return
}

func RemoveChartPermissionChapterMapping(reportId int64) (err error) {
	sql := ` DELETE FROM chart_permission_chapter_mapping WHERE research_type=? AND report_chapter_type_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, "rddp", reportId).Exec()
	return
}

type ChartPermissionMappingIdName struct {
	PermissionId   int
	PermissionName string
}

func GetChartPermissionNameFromMappingByKeyword(keyword string, source string) (list []*ChartPermissionMappingIdName, err error) {
	o := orm.NewOrm()
	sql := " SELECT b.chart_permission_id AS permission_id,b.permission_name FROM chart_permission_search_key_word_mapping AS a INNER JOIN chart_permission AS b ON a.chart_permission_id = b.chart_permission_id WHERE a.`from` = ? AND a.key_word = ? "
	_, err = o.Raw(sql, source, keyword).QueryRows(&list)

	return
}

// UpdateChartPermissionNameFromMappingByKeyword 根据关键词及来源更新新关键词
func UpdateChartPermissionNameFromMappingByKeyword(newKeyword, keyword, source string) (err error) {
	o := orm.NewOrm()
	sql := " UPDATE chart_permission_search_key_word_mapping SET key_word = ? WHERE key_word = ? AND `from` = ? "
	_, err = o.Raw(sql, newKeyword, keyword, source).Exec()
	return
}

// GetPermissionsByClassifyIds 根据分类IDs获取权限IDs
func GetPermissionsByClassifyIds(classifyIds []int) (items []*ChartPermissionSearchKeyWordMapping, err error) {
	if len(classifyIds) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM chart_permission_search_key_word_mapping AS a WHERE a.from='rddp' AND a.classify_id IN (%s)`, utils.GetOrmInReplace(len(classifyIds)))
	_, err = o.Raw(sql, classifyIds).QueryRows(&items)
	return
}
