package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/utils"
	"time"
)

// CygxEnterScore 结构体代表了 cygx_enter_score 表格
type CygxEnterScore struct {
	EnterScoreId        int       `orm:"column(enter_score_id);pk";comment:"主键"`
	CompanyId           int       `comment:"公司ID"`
	CompanyName         string    `comment:"客户名称"`
	StartDate           string    `comment:"开始日期"`
	EndDate             string    `comment:"结束日期"`
	Quarter             string    `comment:"季度"`
	QuarterDate         string    `comment:"季度带有年月日的多个数组转成的字符串"`
	EnterScoreType      int       `comment:"录入方式 1:按评分录入、2:按比例录入"`
	Ranking             string    `comment:"排名"`
	IsMergeScoring      int       `comment:"是否合并打分"`
	SecuritiesFirmsName string    `comment:"券商名称"`
	MergeProportion     float64   `comment:"合并占比"`
	RaiProportionTotal  float64   `comment:"权益研究员占比"`
	FiccProportionTotal float64   `comment:"FICC研究员占比"`
	ProportionTotal     float64   `comment:"合计总占比"`
	SellerId            int       `comment:"所属销售id"`
	SellerName          string    `comment:"所属销售名称"`
	AdminId             int       `comment:"操作人ID"`
	AdminName           string    `comment:"操作人姓名"`
	CreateTime          time.Time `comment:"创建时间"`
	ModifyTime          time.Time `comment:"更新时间"`
}

type CygxEnterScoreDetailResp struct {
	EnterScoreId        int               `comment:"录分ID"`
	CompanyId           int               `comment:"公司ID，公司标识符"`
	CompanyName         string            `comment:"公司名称"`
	StartDate           string            `comment:"开始日期"`
	EndDate             string            `comment:"结束日期"`
	Quarter             []string          `comment:"季度，评分季度"`
	EnterScoreType      int               `comment:"录入方式 1:按评分录入、2:按比例录入"`
	Ranking             string            `comment:"排名"`
	IsMergeScoring      int               `comment:"是否合并打分"`
	SecuritiesFirmsName string            `comment:"券商名称"`
	MergeProportion     float64           `comment:"合并占比"`
	ProportionTotal     float64           `comment:"合计总占比"`
	RaiProportionTotal  float64           `comment:"权益研究员占比"`
	FiccProportionTotal float64           `comment:"FICC研究员占比"`
	EnterScoreObj       EnterScoreDateObj `comment:"按评分录入"`
	PercentageObj       EnterScoreDateObj `comment:"按比例录入"`
}

// 行业
type EnterScoreDateObj struct {
	ListRai   []*EnterScorePermissionListResp //权益列表
	ListFicc  []*EnterScorePermissionListResp //FICC列表
	ListGroup []*EnterScoreGroupListResp      //其他配置信息
}

// 行业
type EnterScorePermissionListResp struct {
	ChartPermissionName string   `description:"行业名称"`
	Proportion          float64  `description:"占比"`
	ProportionListText  []string `description:"占比列表"`
	EnterScoreId        int      `comment:"录分ID"`
	List                []*EnterScoreRealNameListResp
}

// 占比描述
type EnterScoreProportionTextResp struct {
	ProportionText string
}

// 研究员
type EnterScoreRealNameListResp struct {
	RealName            string   `comment:"研究员姓名"`
	Proportion          float64  `comment:"占比"`
	ProportionListText  []string `description:"占比列表"`
	ChartPermissionName string   `comment:"行业名称"`
}

// 其他分组
type EnterScoreGroupListResp struct {
	GroupName          string   `description:"组名"`
	Proportion         float64  `description:"占比"`
	ProportionListText []string `description:"占比列表"`
}

// 添加或修改录分时的入参结构体
type UpdateEnterScoreReq struct {
	EnterScoreId        int                             `comment:"录分ID"`
	CompanyId           int                             `comment:"公司ID"`
	CompanyName         string                          `comment:"客户名称"`
	StartDate           string                          `comment:"开始日期"`
	EndDate             string                          `comment:"结束日期"`
	Quarter             []string                        `comment:"季度"`
	EnterScoreType      int                             `comment:"录入方式 1:按评分录入、2:按比例录入"`
	Ranking             string                          `comment:"排名"`
	IsMergeScoring      int                             `comment:"是否合并打分"`
	SecuritiesFirmsName string                          `comment:"券商名称"`
	MergeProportion     float64                         `comment:"合并占比"`
	RaiProportionTotal  float64                         `comment:"权益研究员占比"`
	FiccProportionTotal float64                         `comment:"FICC研究员占比"`
	ProportionTotal     float64                         `comment:"合计总占比"`
	ListRai             []*EnterScorePermissionListResp //权益列表
	ListFicc            []*EnterScorePermissionListResp //FICC列表
	ListGroup           []*EnterScoreGroupListResp      //其他配置信息
}

type EnterScoreIdReq struct {
	EnterScoreId int `comment:"录分ID"`
}

// CygxEnterScoreGroup 结构体代表 cygx_enter_score_group 表
type CygxEnterScoreGroup struct {
	EnterScoreGroupId int       `orm:"column(enter_score_group_id);pk";comment:"主键"`
	EnterScoreId      int       `comment:"cygx_enter_score主键"`
	CompanyId         int       `comment:"公司ID"`
	GroupName         string    `comment:"名称"`
	Proportion        float64   `comment:"占比"`
	AdminId           int       `comment:"操作人ID"`
	AdminName         string    `comment:"操作人姓名"`
	CreateTime        time.Time `comment:"创建时间"`
	ModifyTime        time.Time `comment:"更新时间"`
}

// CygxEnterScorePermission 结构体代表 cygx_enter_score_permission 表
type CygxEnterScorePermission struct {
	EnterScorePermissionId int       `orm:"column(enter_score_permission_id);pk";comment:"主键"`
	EnterScoreId           int       `comment:"cygx_enter_score主键"`
	CompanyId              int       `comment:"公司ID"`
	ChartPermissionName    string    `comment:"名称"`
	Proportion             float64   `comment:"占比"`
	ProductId              float64   `comment:"产品id,1:FICC、2:权益"`
	AdminId                int       `comment:"操作人ID"`
	AdminName              string    `comment:"操作人姓名"`
	CreateTime             time.Time `comment:"创建时间"`
	ModifyTime             time.Time `comment:"更新时间"`
}

// CygxEnterScoreResearcher 结构体代表 cygx_enter_score_researcher 表
type CygxEnterScoreResearcher struct {
	EnterScoreDataId    int       `orm:"column(enter_score_data_id);pk";comment:"主键"`
	EnterScoreId        int       `comment:"cygx_enter_score主键"`
	CompanyId           int       `comment:"公司ID"`
	Proportion          float64   `comment:"占比"`
	RealName            string    `comment:"研究员姓名"`
	ChartPermissionName string    `comment:"名称"`
	ProductId           float64   `comment:"产品id,1:FICC、2:权益"`
	AdminId             int       `comment:"操作人ID"`
	AdminName           string    `comment:"操作人姓名"`
	CreateTime          time.Time `comment:"创建时间"`
	ModifyTime          time.Time `comment:"更新时间"`
}

// 更新派点信息
func AddCygxEnterScore(item *CygxEnterScore, itemsPermission []*CygxEnterScorePermission, itemsResearcher []*CygxEnterScoreResearcher, itemsGroup []*CygxEnterScoreGroup) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	newId, err := to.Insert(item)
	if err != nil {
		return
	}
	enterScoreId := int(newId)

	for _, v := range itemsPermission {
		v.EnterScoreId = enterScoreId
	}

	for _, v := range itemsResearcher {
		v.EnterScoreId = enterScoreId
	}

	for _, v := range itemsGroup {
		v.EnterScoreId = enterScoreId
	}

	//批量添加行业信息
	_, err = to.InsertMulti(len(itemsPermission), itemsPermission)
	if err != nil {
		return
	}

	//批量添加研究员信息
	_, err = to.InsertMulti(len(itemsResearcher), itemsResearcher)
	if err != nil {
		return
	}

	//批量添加自定义分组信息
	_, err = to.InsertMulti(len(itemsGroup), itemsGroup)
	if err != nil {
		return
	}
	return
}

// 更新派点信息
func UpdateCygxEnterScore(item *CygxEnterScore, itemsPermission []*CygxEnterScorePermission, itemsResearcher []*CygxEnterScoreResearcher, itemsGroup []*CygxEnterScoreGroup) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	_, err = to.Update(item, "CompanyId", "CompanyName", "StartDate", "EndDate", "Quarter", "QuarterDate", "EnterScoreType", "Ranking", "IsMergeScoring", "SecuritiesFirmsName", "MergeProportion", "RaiProportionTotal", "FiccProportionTotal", "ProportionTotal", "SellerId", "SellerName", "AdminId", "AdminName", "ModifyTime")
	if err != nil {
		return
	}
	enterScoreId := item.EnterScoreId

	//批量删除行业信息
	sql := `DELETE FROM cygx_enter_score_permission WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	//批量删除研究员信息
	sql = `	DELETE FROM cygx_enter_score_researcher WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	//批量删除自定义分组信息
	sql = `	DELETE FROM cygx_enter_score_group WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	for _, v := range itemsPermission {
		v.EnterScoreId = enterScoreId
	}

	for _, v := range itemsResearcher {
		v.EnterScoreId = enterScoreId
	}

	for _, v := range itemsGroup {
		v.EnterScoreId = enterScoreId
	}

	//批量添加行业信息
	_, err = to.InsertMulti(len(itemsPermission), itemsPermission)
	if err != nil {
		return
	}

	//批量添加研究员信息
	_, err = to.InsertMulti(len(itemsResearcher), itemsResearcher)
	if err != nil {
		return
	}

	//批量添加自定义分组信息
	_, err = to.InsertMulti(len(itemsGroup), itemsGroup)
	if err != nil {
		return
	}
	return
}

// 通过ID获取详情
func GetCygxEnterScoreInfoById(id int) (item *CygxEnterScore, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score  WHERE enter_score_id = ? `
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// 行业列表
func GetCygxEnterScorePermissionListById(enterScoreId int) (items []*CygxEnterScorePermission, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_permission WHERE enter_score_id = ? `
	_, err = o.Raw(sql, enterScoreId).QueryRows(&items)
	return
}

// 根据多个录分ID获取行业列表
func GetCygxEnterScorePermissionListByIds(enterScoreIds []int) (items []*CygxEnterScorePermission, err error) {
	lenArr := len(enterScoreIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_permission  WHERE  enter_score_id IN  (` + utils.GetOrmInReplace(lenArr) + `) `
	_, err = o.Raw(sql, enterScoreIds).QueryRows(&items)
	return
}

// 研究员列表
func GeCygxEnterScoreResearcherListById(enterScoreId int) (items []*CygxEnterScoreResearcher, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_researcher WHERE enter_score_id = ? `
	_, err = o.Raw(sql, enterScoreId).QueryRows(&items)
	return
}

// 根据多个录分ID获取研究员列表
func GeCygxEnterScoreResearcherListByIds(enterScoreIds, newcompanyIds []int) (items []*CygxEnterScoreResearcher, err error) {
	lenArr := len(enterScoreIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_researcher  WHERE  enter_score_id IN  (` + utils.GetOrmInReplace(lenArr) + `)  AND  proportion > 0  `

	//过滤销售可见的公司与研究员
	lenCompany := len(newcompanyIds)
	if lenCompany > 0 {
		sql += ` AND  company_id IN  (` + utils.GetOrmInReplace(lenCompany) + `) `
		_, err = o.Raw(sql, enterScoreIds, newcompanyIds).QueryRows(&items)
	} else {
		_, err = o.Raw(sql, enterScoreIds).QueryRows(&items)
	}
	return
}

// 自定义分组列表
func GeCygxEnterScoreGroupListById(enterScoreId int) (items []*CygxEnterScoreGroup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_group WHERE enter_score_id = ? `
	_, err = o.Raw(sql, enterScoreId).QueryRows(&items)
	return
}

// 根据多个录分ID获取自定义分组列表
func GeCygxEnterScoreGroupListByIds(enterScoreIds []int) (items []*CygxEnterScoreGroup, err error) {
	lenArr := len(enterScoreIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score_group  WHERE  enter_score_id IN  (` + utils.GetOrmInReplace(lenArr) + `) `
	_, err = o.Raw(sql, enterScoreIds).QueryRows(&items)
	return
}

// 获取列表
func GetCygxEnterScoreList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxEnterScore, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_enter_score  WHERE 1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 根据券商名称获取列表
func GetCygxEnterScoreListBySecuritiesFirmsName(keyWord string) (items []*CygxEnterScore, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT company_id  FROM cygx_enter_score  WHERE 1 = 1  `
	sql += ` AND securities_firms_name LIKE '%` + keyWord + `%' `
	sql += ` GROUP  BY company_id `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取数量
func GetCygxEnterScoreCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_enter_score  WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

type EnterScoreListResp struct {
	EnterScoreId        int      `comment:"录分ID"`
	CompanyId           int      `comment:"公司ID，公司标识符"`
	CompanyName         string   `comment:"公司名称"`
	Quarter             []string `comment:"季度，评分季度"`
	EnterScoreType      int      `comment:"录入方式 1:按评分录入、2:按比例录入"`
	Ranking             string   `comment:"排名"`
	IsMergeScoring      int      `comment:"是否合并打分"`
	SecuritiesFirmsName string   `comment:"券商名称"`
	ProportionTotal     float64  `comment:"合计总占比"`
	SellerId            int      `comment:"所属销售id"`
	SellerName          string   `comment:"所属销售名称"`
	CreateTime          string   `comment:"创建时间"`
	ModifyTime          string   `comment:"更新时间"`
}

type GetCygxEnterScoreListRep struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*EnterScoreListResp
}

// 删除
func DeleteEnterScore(enterScoreId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	//删除单条录分信息
	sql := `DELETE FROM cygx_enter_score WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	//批量删除行业信息
	sql = `DELETE FROM cygx_enter_score_permission WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	//批量删除研究员信息
	sql = `	DELETE FROM cygx_enter_score_researcher WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	//批量删除自定义分组信息
	sql = `	DELETE FROM cygx_enter_score_group WHERE enter_score_id = ?`
	_, err = to.Raw(sql, enterScoreId).Exec()
	if err != nil {
		return
	}

	return
}

type ScoreOverviewListResp struct {
	ListCompany    []*company.CompanyNameAndId
	ListPermission []*EnterScorePermissionListResp
	ListGroup      []*EnterScoreGroupListResp
}

type RankingOverviewListResp struct {
	ListCompany     []*company.CompanyNameAndId
	ListQuarterDate []*QuarterDateListResp
}

// 排名总览
type QuarterDateListResp struct {
	Quarter            string   `description:"季度"`
	ProportionListText []string `description:"占比列表"`
}
