package cygx

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

// 研究员派点
type CygxAllocationCompanyContract struct {
	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
	CompanyContractId           int       `description:"合同id"`
	CreateTime                  time.Time `description:"创建时间"`
	ModifyTime                  time.Time `description:"更新时间"`
	AdminId                     int       `description:"操作人ID"`
	AdminName                   string    `description:"内容"`
	Proportion                  float64   `description:"占比"`
	Money                       float64   `description:"金额"`
	RealName                    string    `description:"研究员姓名"`
	ChartPermissionName         string    `description:"行业名称"`
}

// 研究员派点日志
type CygxAllocationCompanyContractLog struct {
	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
	CompanyContractId           int       `description:"合同id"`
	CreateTime                  time.Time `description:"创建时间"`
	ModifyTime                  time.Time `description:"更新时间"`
	AdminId                     int       `description:"操作人ID"`
	AdminName                   string    `description:"内容"`
	Proportion                  float64   `description:"占比"`
	Money                       float64   `description:"金额"`
	RealName                    string    `description:"研究员姓名"`
	ChartPermissionName         string    `description:"行业名称"`
}

// 行业派点
type CygxAllocationCompanyContractPermission struct {
	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
	CompanyContractId           int       `description:"合同id"`
	CreateTime                  time.Time `description:"创建时间"`
	ModifyTime                  time.Time `description:"更新时间"`
	AdminId                     int       `description:"操作人ID"`
	AdminName                   string    `description:"内容"`
	Proportion                  float64   `description:"占比"`
	Money                       float64   `description:"金额"`
	MoneyAvg                    float64   `description:"行业所占合同的平均金额"`
	ChartPermissionName         string    `description:"行业名称"`
}

// 行业派点日志
type CygxAllocationCompanyContractPermissionLog struct {
	AllocationCompanyContractId int       `orm:"column(allocation_company_contract_id);pk"`
	CompanyContractId           int       `description:"合同id"`
	CreateTime                  time.Time `description:"创建时间"`
	ModifyTime                  time.Time `description:"更新时间"`
	AdminId                     int       `description:"操作人ID"`
	AdminName                   string    `description:"内容"`
	Proportion                  float64   `description:"占比"`
	Money                       float64   `description:"金额"`
	MoneyAvg                    float64   `description:"行业所占合同的平均金额"`
	ChartPermissionName         string    `description:"行业名称"`
}

// 更新派点信息
func AddAndUpdateCygxAllocationCompanyContract(items []*CygxAllocationCompanyContract, itemsPermission []*CygxAllocationCompanyContractPermission, companyContractId 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()
		}
	}()

	//组合研究员派点日志结构体
	var itemsLog []*CygxAllocationCompanyContractLog
	for _, v := range items {
		item := new(CygxAllocationCompanyContractLog)
		item.CompanyContractId = v.CompanyContractId
		item.AdminId = v.AdminId
		item.CompanyContractId = v.CompanyContractId
		item.AdminName = v.AdminName
		item.RealName = v.RealName
		item.ChartPermissionName = v.ChartPermissionName
		item.Proportion = v.Proportion
		item.Money = v.Money
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		itemsLog = append(itemsLog, item)
	}

	//组合行业派点日志结构体
	var itemsPermissionLog []*CygxAllocationCompanyContractPermissionLog
	for _, v := range itemsPermission {
		item := new(CygxAllocationCompanyContractPermissionLog)
		item.CompanyContractId = v.CompanyContractId
		item.AdminId = v.AdminId
		item.CompanyContractId = v.CompanyContractId
		item.AdminName = v.AdminName
		item.ChartPermissionName = v.ChartPermissionName
		item.Proportion = v.Proportion
		item.Money = v.Money
		item.MoneyAvg = v.MoneyAvg
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		itemsPermissionLog = append(itemsPermissionLog, item)
	}

	//删除原有的研究员派点信息
	sql := `DELETE FROM cygx_allocation_company_contract WHERE company_contract_id = ?`
	_, err = to.Raw(sql, companyContractId).Exec()
	if err != nil {
		return
	}
	//删除原有的行业派点信息
	sql = `	DELETE FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ?`
	_, err = to.Raw(sql, companyContractId).Exec()
	if err != nil {
		return
	}

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

	_, err = to.InsertMulti(len(itemsLog), itemsLog)
	if err != nil {
		return
	}

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

	_, err = to.InsertMulti(len(itemsPermissionLog), itemsPermissionLog)
	if err != nil {
		return
	}

	ow := orm.NewOrm()
	sqlW := `UPDATE company_contract SET is_allocation=1   WHERE company_contract_id=? `
	_, err = ow.Raw(sqlW, companyContractId).Exec()

	return
}

type UpdateAllocationCompanyContractReq struct {
	CompanyContractId int `description:"合同ID"`
	List              []*AllocationPermissionListResp
}

type CygxAllocationCompanyContractDetailResp struct {
	CompanyContractId  int     `description:"合同ID"`
	Money              float64 `description:"金额(单位万)"`
	TotalPointsContent string  `description:"总点数描述"`
	IsGray             bool    `description:"是否置灰"`
	IsXClass           bool    `description:"是否是X类试用客户"`
	List               []*AllocationPermissionListResp
}

// 行业
type AllocationPermissionListResp struct {
	ChartPermissionName string  `description:"行业名称"`
	ChartPermissionId   int     `description:"行业id"`
	Proportion          float64 `description:"占比"`
	Money               float64 `description:"金额(单位万)"`
	MoneyAvg            float64 `description:"行业所占合同的平均金额"`
	CompanyContractId   int     `description:"合同ID"`
	List                []*AllocationRealNameListResp
}

// 行业
type AllocationRealNameListResp struct {
	RealName          string  `description:"研究员姓名"`
	Proportion        float64 `description:"占比"`
	Money             float64 `description:"金额(单位万)"`
	ChartPermissionId int     `description:"行业id"`
}

// 获取数量
func GetCygxAllocationCompanyContractCountByCompanyContractId(companyContractId int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_allocation_company_contract WHERE company_contract_id = ? `
	err = o.Raw(sqlCount, companyContractId).QueryRow(&count)
	return
}

// 研究员列表
func GetCygxAllocationCompanyContractListById(companyContractId int) (items []*CygxAllocationCompanyContract, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_allocation_company_contract WHERE company_contract_id = ? `
	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
	return
}

// 研究员列表
func GetCygxAllocationCompanyContractList(condition string, pars []interface{}) (items []*CygxAllocationCompanyContract, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_allocation_company_contract as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 行业列表
func GetCygxAllocationCompanyContractPermissionListById(companyContractId int) (items []*AllocationPermissionListResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ? `
	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
	return
}

// 行业列表
func GetCygxAllocationCompanyContractPermissionList(condition string, pars []interface{}) (items []*AllocationPermissionListResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_allocation_company_contract_permission  as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

type CygxAllocationCompanyContractDetailStatisticsResp struct {
	List          []*AllocationPermissionStatisticsListResp
	TotalContract int     `description:"关联合同总计"`
	TotalMoney    float64 `description:"总派点总计"`
}

// 行业
type AllocationPermissionStatisticsListResp struct {
	ChartPermissionName string `description:"行业名称"`
	List                []*AllocationRealNameStatisticsListResp
}

// 行业
type AllocationRealNameStatisticsListResp struct {
	RealName             string  `description:"研究员姓名"`
	TotalRelatedContract float64 `description:"关联合同"`
	TotalDispatchPoint   string  `description:"总派点"`
	GroupProportion      string  `description:"组内占比"`
	DepartmentProportion string  `description:"部门占比"`
}

// 行业列表
func GetCygxAllocationCompanyContractPermissionListByIdInitYx(companyContractId int) (items []*CygxAllocationCompanyContractPermission, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ? AND  chart_permission_name  IN ('研选扣点包','研选订阅','买方研选')  `
	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
	return
}

// 行业列表
func GetCygxAllocationCompanyContractPermissionListByIdInit(companyContractId int) (items []*CygxAllocationCompanyContractPermission, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ?  `
	_, err = o.Raw(sql, companyContractId).QueryRows(&items)
	return
}

// 更新派点信息
func AddAndUpdateCygxAllocationCompanyContractInit(items []*CygxAllocationCompanyContract, itemsPermission []*CygxAllocationCompanyContractPermission, companyContractId 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_allocation_company_contract WHERE company_contract_id = ? AND  chart_permission_name  IN ('研选扣点包','研选订阅','买方研选') `
	_, err = to.Raw(sql, companyContractId).Exec()
	if err != nil {
		return
	}
	//删除原有的行业派点信息
	sql = `	DELETE FROM cygx_allocation_company_contract_permission WHERE company_contract_id = ? AND  chart_permission_name  IN ('研选扣点包','研选订阅','买方研选') `
	_, err = to.Raw(sql, companyContractId).Exec()
	if err != nil {
		return
	}

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

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

	return
}

// 修改
func Cygx_allocation_company_contractEdit(proportion float64, allocation_company_contract_id int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_allocation_company_contract SET proportion =?  WHERE allocation_company_contract_id=? `
	_, err = o.Raw(sql, proportion, allocation_company_contract_id).Exec()
	return
}

// 修改
func Cygx_allocation_company_contract_permissionEdit(proportion, moneyAvg float64, allocation_company_contract_id int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_allocation_company_contract_permission SET proportion =?,money_avg = ?  WHERE allocation_company_contract_id=? `
	_, err = o.Raw(sql, proportion, moneyAvg, allocation_company_contract_id).Exec()
	return
}