package company

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/utils"
	"time"
)

// 申请服务更新请求参数
type CompanyApplyServiceUpdateReq struct {
	CompanyId         int     `description:"客户id"`
	CompanyApprovalId int     `description:"申请单id，没有传0"`
	ContractType      string  `description:"合同类型，枚举值：'新签合同','续约合同','补充协议'"`
	CompanyType       string  `description:"客户类型，ficc/权益"`
	StartDate         string  `description:"合同开始日期"`
	EndDate           string  `description:"合同结束日期"`
	Money             float64 `description:"合同金额"`
	PayMethod         string  `description:"付款方式"`
	PayChannel        string  `description:"付款渠道"`
	PermissionIds     string  `description:"权限id，多个用英文逗号隔开"`
	ImgUrl            string  `description:"合同图片，多个用英文#隔开"`
	PackageType       int     `description:"套餐类型，0：无，1：大套餐，2：小套餐"`
	RaiPackageType    int     `description:"权益套餐类型: 0-无; 1-70w套餐; 2-45w套餐"`
	Points            float64 `description:"研选扣点包点数"`
}

type ApproveUser struct {
	AdminId  int
	RealName string
	Mobile   string
}

// 获取审批人
func GetApproveUser(roleTypeCode string) (items []*ApproveUser, err error) {
	o := orm.NewOrm()
	sql := `SELECT admin_id,real_name,mobile FROM admin WHERE role_type_code=? AND admin_name<>'qshi' `
	_, err = o.Raw(sql, roleTypeCode).QueryRows(&items)
	return
}

type CompanyContractHistory struct {
	CompanyContractId int       `json:"-" description:"合同id"`
	CompanyId         int       `description:"客户id"`
	ContractCode      string    `description:"合同编码"`
	ContractType      string    `description:"合同类型，枚举值：'新签合同','续约合同','补充协议'"`
	StartDate         string    `description:"合同开始时间"`
	EndDate           string    `description:"合同结束时间"`
	Money             float64   `description:"合同金额"`
	PayMethod         string    `description:"支付方式"`
	PayChannel        string    `description:"支付渠道"`
	ImgUrl            string    `description:"合同图片，多个用#隔开"`
	CreateTime        time.Time `description:"合同创建时间"`
	ModifyTime        time.Time `description:"合同修改时间";json:"-"`
	ModifyTimeStr     string    `description:"合同修改时间"`
	Status            int       `description:"状态"`
	ProductId         int       `description:"产品id"`
	ContractId        int       `description:"合同ID"`
	RaiPackageType    int       `description:"权益套餐类型: 0-无; 1-70w套餐; 2-45w套餐"`
	PermissionList    []*ContractPermissionList
}

type CompanyContractHistoryResp struct {
	List []*CompanyContractHistory
}

func GetCompanyContractHistoryList(companyId int, productId string) (items []*CompanyContractHistory, err error) {
	o := orm.NewOrm()
	//sql := `SELECT * FROM company_contract WHERE company_id=? AND product_id IN(` + productId + `) AND status="1" ORDER BY modify_time DESC `
	sql := `SELECT
				a.*,
				b.contract_id
			FROM
				company_contract AS a
			LEFT JOIN contract AS b ON a.contract_code = b.contract_code
			WHERE
				a.company_id = ? AND a.product_id IN (` + productId + `) AND a.status = 1
			ORDER BY
				a.modify_time DESC`
	_, err = o.Raw(sql, companyId).QueryRows(&items)
	return
}

func GetCompanyContractHistoryListByContractCode(contractCode string) (items []*CompanyContractHistory, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.*,
				b.contract_id
			FROM
				company_contract AS a
			LEFT JOIN contract AS b ON a.contract_code = b.contract_code
			WHERE
				a.contract_code = ?  AND a.status = 1
			ORDER BY
				a.modify_time DESC`
	_, err = o.Raw(sql, contractCode).QueryRows(&items)
	return
}

type CompanyContractDetail struct {
	CompanyContractId int
	CompanyId         int       `description:"客户id"`
	ProductId         int       `description:"产品id"`
	ContractCode      string    `description:"合同编码"`
	ContractType      string    `description:"合同类型：枚举值：'新签合同','续约合同','补充协议'"`
	StartDate         string    `description:"合同开始时间"`
	EndDate           string    `description:"合同结束时间"`
	Quarter           string    `description:"季度(X类试用客户使用)"`
	Money             float64   `description:"合同金额"`
	PayMethod         string    `description:"支付方式"`
	PayChannel        string    `description:"支付渠道"`
	ImgUrl            string    `description:"合同图片，多个用#隔开"`
	CreateTime        time.Time `description:"合同创建时间"`
	ModifyTime        time.Time `description:"合同修改时间"`
	Status            int       `description:"状态"`
	PackageType       int       `description:"套餐类型，0：无，1：大套餐，2：小套餐"`
	RaiPackageType    int       `description:"权益套餐类型: 0-无; 1-70w套餐; 2-45w套餐"`
	Source            string    `description:"合同来源：上传附件, 系统合同"`
	SourceTag         string    `description:"合同来源标签：非标合同，标准合同"`
	AllocationType    int       `description:"分配方式，0手动分配，1X录分之后自动分配，默认0"`
	PermissionList    []*PermissionLookList
}

type CompanyContractDetailResp struct {
	Item *CompanyContractDetail
}

func GetCompanyContractDetail(companyId, productId, companyContractId int) (item *CompanyContractDetail, err error) {
	o := orm.NewOrm()
	if companyContractId == 0 {
		if productId <= 0 {
			err = errors.New("客户类型异常")
		}
		sql := `SELECT * FROM company_contract WHERE company_id=? AND product_id=? AND status=0 `
		err = o.Raw(sql, companyId, productId).QueryRow(&item)
	} else {
		sql := `SELECT * FROM company_contract WHERE company_contract_id=? `
		err = o.Raw(sql, companyContractId).QueryRow(&item)
	}
	return
}

// 获取客户大于今天的最后一份有效合同
func GetCompanyLastContractDetail(companyId, productId int) (item *CompanyContractDetail, err error) {
	o := orm.NewOrm()
	endDate := utils.GetToday(utils.FormatDate)
	sql := `SELECT * FROM company_contract WHERE company_id=? AND product_id=? AND status=1 AND end_date >= ? AND contract_type in ("新签合同","续约合同") order by end_date desc limit 1`
	err = o.Raw(sql, companyId, productId, endDate).QueryRow(&item)
	return
}

// 最后一次
type ContractPermissionLookItemRes struct {
	ChartPermissionId int       `description:"权限id"`
	PermissionName    string    `description:"权限名称"`
	StartDate         time.Time `description:"权限开始日期"`
	EndDate           time.Time `description:"权限结束日期"`
	//Status            string `description:"'正式','试用','关闭'"`
	//ExpireDay         string `description:"到期天数"`
	ClassifyName string `description:"分类"`
}

// 获取客户大于今天的所有有效合同
func GetCompanyWillContractList(companyId, productId int) (list []*CompanyContractDetail, err error) {
	o := orm.NewOrm()
	endDate := utils.GetToday(utils.FormatDate)
	sql := `SELECT * FROM company_contract WHERE company_id=? AND product_id=? AND status=1 AND end_date >= ? AND contract_type in ("新签合同","续约合同") order by end_date desc`
	_, err = o.Raw(sql, companyId, productId, endDate).QueryRows(&list)
	return
}

func GetCompanyContractApproveCount(companyId, productId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM company_contract WHERE company_id=? AND product_id=? AND status=0 `
	err = o.Raw(sql, companyId, productId).QueryRow(&count)
	return
}

type CompanyApplyApproveReq struct {
	CompanyId         int    `description:"客户id"`
	Status            int    `description:"审批状态，1:通过，2：拒绝"`
	Remark            string `description:"审批理由"`
	CompanyContractId int    `description:"合同id"`
	ProductId         int    `description:"客户产品id"`
}

// 审批通过
func ApproveAgree(companyId, productId int, approveStatus, approveRemark, startDate, endDate string, applyMethod int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE  company_product
			SET
			  approve_status = ?,
			  approve_time = NOW(),
			  approve_remark = ?,
			  start_date=?,
			  end_date=?,
			  modify_time=NOW()
			WHERE company_id = ? AND product_id=? `
	_, err = to.Raw(sql, approveStatus, approveRemark, startDate, endDate, companyId, productId).Exec()
	if err != nil {
		return
	}
	if applyMethod == 6 {
		sql := `UPDATE  company_contract
			SET
			  status = 1,
			  modify_time=NOW()
			WHERE company_id = ? AND product_id=? `
		_, err = to.Raw(sql, companyId, productId).Exec()
	}
	return
}

// 审批拒绝
func ApproveRefuse(companyId, productId int, approveStatus, approveRemark string) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE  company_product
			SET
			  approve_status = '驳回',
			  modify_time=NOW()
			WHERE company_id = ? AND product_id=? `
	_, err = to.Raw(sql, companyId, productId).Exec()
	if err != nil {
		return
	}
	sql = ` UPDATE  company_approval
			SET
			  approve_status = '驳回',
			  approve_remark=?,
			  approve_time=NOW(),
			  modify_time=NOW()
			WHERE company_id = ? AND product_id=? AND approve_status='待审批' `
	_, err = to.Raw(sql, approveRemark, companyId, productId).Exec()
	return
}

// 申请转正请求参数
type CompanyApplyTurnPositiveReq struct {
	CompanyId         int
	CompanyApprovalId int     `description:"申请单id，没有传0"`
	ContractType      string  `description:"合同类型，枚举值：'新签合同','续约合同','补充协议'"`
	StartDate         string  `description:"合同开始日期"`
	EndDate           string  `description:"合同结束日期"`
	Money             float64 `description:"合同金额"`
	PayMethod         string  `description:"付款方式"`
	PayChannel        string  `description:"付款渠道"`
	PermissionIds     string  `description:"权限id，多个用英文逗号隔开"`
	PermissionNames   string  `description:"权限名称，多个用英文逗号隔开"`
	ImgUrl            string  `description:"合同图片，多个用英文#隔开"`
	PackageType       int     `description:"套餐类型，0：无，1：大套餐，2：小套餐"`
	RaiPackageType    int     `description:"权益套餐类型: 0-无; 1-70w大套餐; 2-45w大套餐"`
	Points            float64 `description:"研选扣点包点数"`
}

// 申请转正请求参数
type CompanyApplyBySystemContractReq struct {
	CompanyId         int
	CompanyApprovalId int `description:"申请单id，没有传0"`
	ContractId        int `description:"合同id，没有传0"`
}

// 申请解冻参数
type CompanyApplyThawReq struct {
	CompanyId         int    `description:"客户id"`
	CompanyApprovalId int    `description:"申请单id，没有传0"`
	ApplyRemark       string `description:"申请解冻理由"`
	PermissionIds     string `description:"权限id，多个用英文逗号隔开"`
}

// 申请延期参数
type CompanyApplyDelayReq struct {
	CompanyId         int    `description:"客户id"`
	CompanyApprovalId int    `description:"申请单id，没有传0"`
	ApplyRemark       string `description:"申请解冻理由"`
	PermissionIds     string `description:"权限id，多个用英文逗号隔开"`
}

// 申请领取参数
type CompanyApplyReceiveReq struct {
	CompanyId         int    `description:"客户id"`
	CompanyApprovalId int    `description:"申请单id，没有传0"`
	ApplyRemark       string `description:"申请解冻理由"`
	PermissionIds     string `description:"权限id，多个用英文逗号隔开"`
}

type CompanyApplyDetailResp struct {
	Item        *CompanyDetail        `description:"客户信息"`
	FiccItem    *CompanyProductDetail `description:"Ficc客户产品详情"`
	RaiItem     *CompanyProductDetail `description:"权益客户产品详情"`
	ProductName string                `description:"部门名称：ficc/权益/admin"`
	Approval    *CompanyApproval      `description:"审批详情"`
}

type CompanyApplyRevokeReq struct {
	CompanyId int `description:"客户id"`
}

func ApplyRevoke(companyApprovalId, companyId, productId int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE company_approval SET approve_status='已撤回' WHERE company_approval_id=? `
	_, err = to.Raw(sql, companyApprovalId).Exec()
	sql = `UPDATE company_product SET approve_status='已撤回' WHERE company_id=? AND product_id=? `
	_, err = to.Raw(sql, companyId, productId).Exec()
	sql = `UPDATE company_approval_message SET operation_status=2 WHERE company_approval_id=? AND operation_status=1 `
	_, err = to.Raw(sql, companyApprovalId).Exec()

	return
}

func GetCompanyApprovalByCompanyApprovalId(companyApprovalId int) (item *CompanyApproval, err error) {
	sql := `SELECT * FROM company_approval WHERE company_approval_id=? `
	o := orm.NewOrm()
	err = o.Raw(sql, companyApprovalId).QueryRow(&item)
	return
}

func GetCompanyContractById(companyContractId int) (item *CompanyContractDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM company_contract WHERE company_contract_id=? `
	err = o.Raw(sql, companyContractId).QueryRow(&item)
	return
}

type ApplyContractResp struct {
	Item *CompanyContractDetail
}

// 获取申请转正时的合同类型
type ApplyContractTypeResp struct {
	ContractType string
}
