// @Author gmy 2024/9/19 14:53:00
package document_manage_model

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
)

type OutsideReport struct {
	OutsideReportId  int    `orm:"column(outside_report_id);pk" description:"外部报告ID"`
	Source           int    `orm:"column(source)" description:"来源，1：ETA系统录入；2：API接口录入；3：邮件监听录入"`
	Title            string `orm:"column(title)" description:"报告标题"`
	Abstract         string `orm:"column(abstract)" description:"摘要"`
	ClassifyId       int    `orm:"column(classify_id)" description:"所属分类id"`
	ClassifyName     string `orm:"column(classify_name)" description:"所属分类名称（整个分类链条）"`
	Content          string `orm:"column(content)" description:"报告富文本内容"`
	SysUserId        int    `orm:"column(sys_user_id)" description:"创建人id"`
	SysUserName      string `orm:"column(sys_user_name)" description:"创建人姓名"`
	EmailMessageUid  int    `orm:"column(email_message_uid)" description:"该邮件在邮箱中的唯一id"`
	ReportUpdateTime string `orm:"column(report_update_time)" description:"报告更新时间，如果来源于邮件，那么取邮件的收件时间"`
	ModifyTime       string `orm:"column(modify_time)" description:"最近一次修改时间"`
	CreateTime       string `orm:"column(create_time)" description:"创建时间"`
	ReportCode       string `orm:"column(report_code)" description:"报告唯一编码"`
}

type OutsideReportResp struct {
	OutsideReport
	IsCollect int `description:"是否收藏"`
}

type OutsideReportPage struct {
	List   []OutsideReportResp `description:"报告列表"`
	Paging *paging.PagingItem  `description:"分页数据"`
}

type OutsideReportBO struct {
	OutsideReportId int    `orm:"column(outside_report_id);pk" description:"外部报告ID"`
	Source          int    `orm:"column(source)" description:"来源，1：ETA系统录入；2：API接口录入；3：邮件监听录入"`
	Title           string `orm:"column(title)" description:"报告标题"`
	Abstract        string `orm:"column(abstract)" description:"摘要"`
	ClassifyId      int    `orm:"column(classify_id)" description:"所属分类id"`
	ClassifyName    string `orm:"column(classify_name)" description:"所属分类名称（整个分类链条）"`
	Content         string `orm:"column(content)" description:"报告富文本内容"`
	SysUserId       int    `orm:"column(sys_user_id)" description:"创建人id"`
	SysUserName     string `orm:"column(sys_user_name)" description:"创建人姓名"`
	ModifyTime      string `orm:"column(modify_time)" description:"最近一次修改时间"`
	CreateTime      string `orm:"column(create_time)" description:"创建时间"`
	ReportCode      string `orm:"column(report_code)" description:"报告唯一编码"`
	AttachmentList  []*OutsideReportAttachment
}

// 在 init 函数中注册模型
func init() {
	orm.RegisterModel(new(OutsideReport))
}

// GetOutsideReportListByConditionCount 根据条件查询列表条数
func GetOutsideReportListByConditionCount(condition string, pars []interface{}, chartPermissionIdList []string) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	var sql string
	if len(chartPermissionIdList) > 0 {
		sql = `select count(1) from (`
	}
	sql += `SELECT COUNT( DISTINCT t1.outside_report_id ) 
			FROM outside_report t1 
			    LEFT JOIN chart_permission_search_key_word_mapping t2 ON t1.classify_id = t2.classify_id 
			WHERE 1 = 1 `
	sql += condition
	if len(chartPermissionIdList) > 0 {
		sql += ` ) t`
	}

	err = o.Raw(sql, pars).QueryRow(&count)
	if err != nil && err != orm.ErrNoRows {
		return 0, err
	}

	return count, err
}

// GetOutsideReportListByCondition 根据条件查询列表
func GetOutsideReportListByCondition(condition string, pars []interface{}, currentIndex int, pageSize int) (list []OutsideReportResp, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select DISTINCT t1.outside_report_id, t1.source, t1.title, t1.abstract, t1.classify_id, t1.classify_name, t1.sys_user_id, t1.sys_user_name, t1.email_message_uid, t1.report_update_time, t1.modify_time, t1.create_time, t1.report_code  from outside_report t1 left join chart_permission_search_key_word_mapping t2 on t1.classify_id = t2.classify_id  where 1 = 1 `
	sql += condition
	sql += ` limit ?, ?`
	_, err = o.Raw(sql, pars, (currentIndex-1)*pageSize, pageSize).QueryRows(&list)
	if err != nil && err != orm.ErrNoRows {
		return nil, err
	}

	return list, err
}

/*// GetOutsideReportListByDocumentTypeCount 根据文档类型查询列表条数
func GetOutsideReportListByDocumentTypeCount(documentType int, condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	var sql string
	if documentType == 1 {
		sql = `select count(t1.OutsideReportId) from outside_report t1 left join chart_permission_search_key_word_mapping t2 on t1.classify_id = t2.classify_id  where 1 = 1 `
	} else if documentType == 2 {
		sql = `select count(t1.OutsideReportId) from outside_report t1 left join chart_permission_search_key_word_mapping t2  on t1.classify_id = t2.classify_id left join user_collect_classify t3 on t1.classify_id = t3.classify_id where 1 = 1 `
	}

	sql += sql + condition
	err = o.Raw(sql, pars).QueryRow(&count)
	if err != nil {
		return 0, err
	}

	return 0, err
}

// GetOutsideReportListByDocumentType 根据文档类型查询列表
func GetOutsideReportListByDocumentType(documentType int, condition string, pars []interface{}) (list []OutsideReport, err error) {
	o := orm.NewOrmUsingDB("rddp")
	var sql string
	if documentType == 1 {
		sql = `select t1.* from outside_report t1 left join chart_permission_search_key_word_mapping t2 on t1.classify_id = t2.classify_id  where 1 = 1 `
	} else if documentType == 2 {
		sql = `select t1.* from outside_report t1 left join chart_permission_search_key_word_mapping t2  on t1.classify_id = t2.classify_id left join user_collect_classify t3 on t1.classify_id = t3.classify_id where 1 = 1 `
	}

	sql += condition
	_, err = o.Raw(sql, pars).QueryRows(&list)
	if err != nil {
		return nil, err
	}

	return list, err
}*/

// SaveOutsideReport 保存报告
func SaveOutsideReport(outsideReport OutsideReport) (id int64, err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err = o.Insert(&outsideReport)
	return
}

// GetOutsideReportById 根据ID获取报告
func GetOutsideReportById(id int) (outsideReport *OutsideReport, err error) {
	o := orm.NewOrmUsingDB("rddp")

	outsideReport = &OutsideReport{}

	err = o.QueryTable("outside_report").Filter("outside_report_id", id).One(outsideReport)
	return
}

// UpdateOutsideReport 更新报告
func UpdateOutsideReport(outsideReport *OutsideReport) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(&outsideReport)
	return
}

// DeleteOutsideReport 删除报告
func DeleteOutsideReport(id int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.QueryTable("outside_report").Filter("outside_report_id", id).Delete()
	return
}
