package contract

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

//获取审批列表数据数量
func GetCompanyApprovalListCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `
SELECT a.* from contract_approval a
	JOIN company_approval c ON a.contract_id = c.company_approval_id 
			INNER JOIN company AS e ON e.company_id=c.company_id
WHERE
	 a.approval_type = "company" `
	sql += condition
	sql += ` GROUP BY a.contract_id `
	sql = `select count(*) count from (` + sql + `) b`
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

//审批列表
type CompanyApprovalList struct {
	ContractApprovalId       int            `description:"审批单id"`
	ContractId               int            `description:"客户单id"`
	ContractApprovalRecordId int            `description:"审批流id"`
	ContractCode             string         `description:"合同编号"`
	Status                   string         `description:"审批单状态，枚举值：待审批','已审批','已驳回','已撤回'，默认待审批"`
	ApplyContent             string         `description:"待审内容"`
	ContractDetail           string         `json:"-" description:"提交审批时的客户审批信息；客户审批快照"`
	ContractInfo             ContractDetail `description:"提交审批时的合同信息；合同快照"`
	ApproveRemark            string         `description:"审核备注"`
	CompanyName              string         `description:"客户名称"`
	SellerId                 int            `description:"销售id"`
	ApplyUserId              int            `description:"申请人id"`
	CurrNodeId               int            `description:"当前节点"`
	StartNodeId              int            `description:"开始节点"`
	ProductId                int            `description:"产品id，1：ficc；2：权益"`
	SellerName               string         `description:"销售名称"`
	StartDate                time.Time      `description:"合同开始日期"`
	EndDate                  time.Time      `description:"合同结束日期"`
	CreateTime               time.Time      `description:"发起审批的时间"`
	ModifyTime               time.Time      `description:"最后一次修改的时间"`
	ApproveTime              time.Time      `description:"审批时间"`
	StartDateStr             string         `description:"合同开始日期(字符串类型)"`
	EndDateStr               string         `description:"合同结束日期(字符串类型)"`
	CreateTimeStr            string         `description:"发起审批的时间(字符串类型)"`
	ModifyTimeStr            string         `description:"最后一次修改的时间(字符串类型)"`
	ApproveTimeStr           string         `description:"审批时间（字符串类型）"`

	CompanyId            int
	CreditCode           string `description:"社会统一信用码"`
	CompanyType          string `description:"客户类型"`
	IndustryName         string `description:"行业名称"`
	ApprovalTime         string `description:"提交申请时间"`
	CompanyProductStatus string `description:"客户状态"`
	ApproveContent       string `description:"待审内容"`
	ApproveStatus        string `description:"当前状态"`
	ApplyMethod          int    `description:"申请类型：1:试用->正式,2:冻结—>试用,3:流失—>正式,4:试用延期,5:原销售申请领取流失客户，6:正式客户申请服务更新"`
	ApplyReasons         string `description:"申请理由"`
	FreezeStartDate      string `description:"冻结开始日期"`
	FreezeEndDate        string `description:"冻结结束日期"`
	FreezeExpireDays     int    `description:"冻结到期天数"`
	Address              string `description:"地址"`
	Source               string `description:"客户来源"`
	ExpireDay            int    `description:"服务到期天数"`
	CompanyApprovalId    int    `description:"审批记录ID"`
	ApprovalCount        int    `description:"已延期审批次数"`
	CompanyContractId    int    `description:"合同id"`
	DelayPermission      string `description:"延期申请品种"`
	ApplyRealName        string `description:"申请人姓名"`
}

//获取审批列表数据
func GetCompanyApprovalList(childCondition, condition string, childPars, pars []interface{}, startSize, pageSize int) (list []*CompanyApprovalList, err error) {
	o := orm.NewOrm()
	sql := `
SELECT
a.contract_approval_id,a.contract_id,a.apply_content,a.contract_detail,a.approve_remark,a.create_time,a.modify_time,a.status,a.curr_node_id,a.start_node_id,a.apply_user_id,c.approve_time,c.company_approval_id,c.approve_status,c.company_id,c.product_id,c.apply_real_name,d.company_type,d.industry_name,d.seller_name,d.status company_product_status,c.approve_status,c.apply_method,c.apply_reasons,d.freeze_start_date,d.freeze_end_date,e.address,d.source,c.approve_remark,d.start_date,d.end_date,c.company_contract_id,e.company_name,e.credit_code
from contract_approval a
	join  ( SELECT max( contract_approval_id ) max_id,contract_id FROM contract_approval where 1=1 and approval_type="company" `
	sql += childCondition
	sql += `  GROUP BY contract_id ) b on a.contract_approval_id=b.max_id
			INNER JOIN company_approval AS c ON a.contract_id=c.company_approval_id
			INNER JOIN company_product AS d ON d.company_id=c.company_id AND d.product_id=c.product_id
			INNER JOIN company AS e ON e.company_id=d.company_id
 			WHERE 1=1 and  a.approval_type="company" `
	sql += condition
	sql += ` group by contract_id order by modify_time desc LIMIT ?,? `
	_, err = o.Raw(sql, childPars, pars, startSize, pageSize).QueryRows(&list)
	return
}

// GetContractApprovalIdList 根据客户申请单id获取
func GetContractApprovalIdList(companyApprovalIds string, approveUserId int) (list []*ContractApproval, err error) {
	o := orm.NewOrm()
	sql := `
SELECT
a.* from contract_approval a
	where  contract_approval_id in  ( SELECT max( contract_approval_id ) max_id FROM contract_approval where 1=1 and a.approval_type="company"  and contract_id in (` + companyApprovalIds + `)
`
	sql += ` order by modify_time desc `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}
