package crm

import (
	"hongze/fms_api/global"
	"hongze/fms_api/models/base"
	"time"
)

// Contract CRM系统合同
type Contract struct {
	ContractId           int       `gorm:"primaryKey;column:contract_id"`
	ContractCode         string    `description:"合同编号,长度32位"`
	SellerId             int       `description:"所属销售id"`
	SellerName           string    `description:"所属销售名称"`
	ProductId            int       `description:"产品id,1:ficc;2:权益"`
	ContractBusinessType string    `description:"合同业务类型,枚举值:'业务合同','代付合同'"`
	ContractType         string    `description:"合同类型,枚举值:'新签合同','续约合同','补充协议'"`
	Status               string    `description:"合同状态,枚举值:'待提交','待审批','已撤回','已审批','已驳回','已作废','已解约'"`
	StartDate            time.Time `description:"合同开始日期"`
	EndDate              time.Time `description:"合同结束日期"`
	OriginalPrice        float64   `description:"合同原金额,优惠前的金额"`
	Price                float64   `description:"实际金额,优惠后的金额"`
	PayRemark            string    `description:"付款方式说明,长度255位"`
	PayChannel           string    `description:"付款渠道,长度255位"`
	CompanyName          string    `description:"客户名称,甲方名称,长度32位"`
	CreditCode           string    `description:"社会统一信用代码,长度64位"`
	ProvinceId           int       `description:"省级id"`
	Province             string    `description:"省级名称,长度16位"`
	CityId               int       `description:"市级id"`
	City                 string    `description:"市级名称,长度32位"`
	Address              string    `description:"详细地址"`
	Fax                  string    `description:"传真,长度32位"`
	Phone                string    `description:"电话,长度32位"`
	Postcode             string    `description:"邮编,长度16位"`
	Remark               string    `description:"补充内容,长度255位"`
	SellerRemark         string    `description:"销售备注,长度255位"`
	ModifyContent        string    `description:"修改内容"`
	ApprovalRemark       string    `description:"审核备注"`
	FileUrl              string    `description:"合同文件地址"`
	CheckBackFileUrl     string    `description:"签回合同文件地址"`
	RescindFileUrl       string    `description:"解约合同文件地址"`
	TemplateId           int       `description:"模板id"`
	SourceId             int       `description:"来源合同id,默认是0;如果是通过其他合同复制过来的,那么就是原合同的id"`
	IsDelete             int       `description:"是否已经删除,0:未删除,1:已删除" json:"-"`
	ApproveTime          time.Time `description:"审批时间"`
	InvalidTime          time.Time `description:"作废时间"`
	CheckBackFileTime    time.Time `description:"合同签回时间"`
	RescindTime          time.Time `description:"解约时间"`
	ModifyTime           time.Time `description:"合同最近一次修改时间"`
	CreateTime           time.Time `description:"合同添加时间"`
}

func (c *Contract) TableName() string {
	return "contract"
}

func (c *Contract) PageList(page base.IPage, condition string, pars []interface{}) (count int64, results []*Contract, err error) {
	results = make([]*Contract, 0)
	query := global.MYSQL["report"].Model(Contract{}).
		Where("is_delete = 0").
		Where(condition, pars...)
	query.Count(&count)
	if len(page.GetOrderItemsString()) > 0 {
		query = query.Order(page.GetOrderItemsString())
	}
	err = query.Limit(int(page.GetPageSize())).Offset(int(page.Offset())).Find(&results).Error
	return
}

// ContractSearchListReq CRM系统合同-搜索列表请求体
type ContractSearchListReq struct {
	Keyword   string `json:"keyword" form:"keyword" binding:"omitempty" description:"关键词"`
	ProductId int    `json:"product_id" form:"product_id" description:"产品: 0-全部; 1-FICC; 2-权益"`
	base.PageReq
}

// ContractSearchListResp CRM系统合同-搜索列表响应体
type ContractSearchListResp struct {
	ContractId         int     `json:"contract_id" description:"合同ID"`
	ContractCode       string  `json:"contract_code" description:"合同编号"`
	ProductId          int     `json:"product_id" description:"产品ID"`
	CompanyName        string  `json:"company_name" description:"客户名称"`
	RelateContractCode string  `json:"relate_contract_code" description:"代付合同关联的实际使用方合同编号"`
	ActualCompanyName  string  `json:"actual_company_name" description:"实际使用方"`
	SellerId           int     `json:"seller_id" description:"销售ID"`
	SellerName         string  `json:"seller_name" description:"销售名称"`
	ContractTypeKey    int     `json:"contract_type_key" description:"FMS合同类型: 1-新签; 2-续约; 3-代付; 4-补充协议;"`
	ContractType       string  `json:"contract_type" description:"CRM合同类型: 新签合同; 续约合同; 补充协议;"`
	Price              float64 `json:"price" description:"合同金额"`
	StartDate          string  `json:"start_date" description:"合同开始日期"`
	EndDate            string  `json:"end_date" description:"合同结束日期"`
	ActualPayCompanies string  `json:"actual_pay_companies" description:"该合同关联的所有代付方, 英文逗号拼接"`
	ContractTypeInt    int  `json:"contract_type_int" description:"CRM合同类型: 1新签合同; 2续约合同; 3补充协议;"`
	ContractBusinessTypeInt    int  `json:"contract_business_type_int" description:"合同业务类型,1'业务合同', 2'代付合同;"`
	
}

// PayCompanyRelation 代付合同
type PayCompanyRelation struct {
	ContractId                int    `description:"代付合同ID"`
	ContractCode              string `description:"代付合同编号"`
	CompanyName               string `description:"代付方名称"`
	PaymentOnBehalfContractId int    `description:"实际使用方合同ID"`
}

// GetPayCompanyByContractIds 通过代付合同IDs获取关联客户信息
func GetPayCompanyByContractIds(condition string, pars []interface{}) (results []*PayCompanyRelation, err error) {
	results = make([]*PayCompanyRelation, 0)
	query := global.MYSQL["report"].
		Table("contract as a").
		Select("a.contract_id, a.contract_code, a.company_name, b.payment_on_behalf_contract_id").
		Joins("JOIN contract_relation b ON a.contract_id = b.contract_id").
		Where("a.is_delete = 0").
		Where(condition, pars...)
	err = query.Find(&results).Error
	return
}

// ContractActualPayCompanies 代付合同信息
type ContractActualPayCompanies struct {
	ContractId         int    `json:"contract_id" description:"业务合同ID"`
	ActualPayCompanies string `json:"actual_pay_companies" description:"关联的代付方名称, 英文逗号拼接"`
}

// GetContractActualPayCompaniesByContractIds 通过合同IDs获取代付客户信息
func GetContractActualPayCompaniesByContractIds(condition string, pars []interface{}) (results []*ContractActualPayCompanies, err error) {
	results = make([]*ContractActualPayCompanies, 0)
	query := global.MYSQL["report"].
		Table("contract_relation AS a").
		Select("a.contract_id, GROUP_CONCAT(DISTINCT b.company_name) AS actual_pay_companies").
		Joins("JOIN contract AS b ON a.payment_on_behalf_contract_id = b.contract_id").
		Where("b.is_delete = 0").
		Where(condition, pars...).
		Group("a.contract_id")
	err = query.Find(&results).Error
	return
}

// ContractDetail 合同详情信息(包含服务信息等)
type ContractDetail struct {
	Contract
	StartDateStr               string `description:"合同起始时间(字符串形式)"`
	EndDateStr                 string `description:"合同结束时间(字符串形式)"`
	ApproveTimeStr             string `description:"审批时间(字符串形式)"`
	InvalidTimeStr             string `description:"作废时间(字符串形式)"`
	CheckBackFileTimeStr       string `description:"合同签回时间(字符串形式)"`
	RescindTimeStr             string `description:"解约时间(字符串形式)"`
	ModifyTimeStr              string `description:"最近一次更新时间(字符串形式)"`
	CreateTimeStr              string `description:"合同添加时间(字符串形式)"`
	Service                    []*ContractServiceAndDetailRespItem
	RelationContractDetailList []*ContractDetail     `description:"关联合同详情"`
	PermissionLookList         []*PermissionLookList `description:"合同里面的权限列表"`
}

type PermissionLookList struct {
	ClassifyName string `description:"分类"`
	Items        []*PermissionLookItem
}

type PermissionLookItem struct {
	ChartPermissionId int    `description:"权限id"`
	PermissionName    string `description:"权限名称"`
	ClassifyName      string `description:"分类"`
}

// GetContractDetailById 根据合同ID获取合同详情信息
func GetContractDetailById(contractId int) (detail *ContractDetail, err error) {
	detail = new(ContractDetail)
	item := new(Contract)
	query := global.MYSQL["report"].
		Model(Contract{}).
		Where("contract_id = ?", contractId)
	err = query.Find(&item).Error
	if err != nil {
		return
	}
	detail.Contract = *item
	return
}

// ContractServiceDetailReq CRM系统合同-合同套餐及品种权限详情请求体
type ContractServiceDetailReq struct {
	ContractId int `json:"contract_id" form:"contract_id" binding:"required,gte=1" description:"合同ID"`
}