package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_cygx/utils"
	"time"
)

type Company struct {
	CompanyId             int       `orm:"column(company_id);pk"`
	CompanyName           string    `description:"客户名称"`
	CompanyType           int       `orm:"column(type)"`
	CreditCode            string    `description:"社会统一信用码"`
	CompanyCode           string    `description:"客户编码"`
	Sort                  int       `description:"优先级"`
	IsFeeCustomer         int       `description:"是否付费用户"`
	Country               string    `description:"国家编码"`
	Province              string    `description:"省"`
	City                  string    `description:"市"`
	Address               string    `description:"详细地址"`
	Enabled               int       `description:"用户状态"`
	CreatedTime           time.Time `description:"创建时间"`
	LastUpdatedTime       time.Time `description:"最后一次阅读时间"`
	Seller                string    `description:"销售员"`
	SellsId               int       `description:"销售员id"`
	CompanyBelong         string    `description:"客户所属，ficc：ficc客户，public_offering：公募客户，partner：合作伙伴"`
	StartDate             string    `description:"合同开始日期"`
	EndDate               string    `description:"合同结束日期"`
	LastType              int       `description:"原客户标签"`
	IsVip                 int       `description:"0:普通用户,1:大客户"`
	FirstStartDate        string    `description:"首次设置为试用客户开始时间"`
	FirstEndDate          string    `description:"首次设置为试用客户结束时间"`
	DateType              int       `description:"设置流失类型，1：1个月，2：2个月，3：3个月"`
	Remark                string    `description:"备注信息"`
	RegionType            string    `description:"地区类型，国内，国外"`
	OpenCompanyCode       string    `description:"开放给第三方的客户编码，不让第三方定位我们的客户信息"`
	TripartiteCompanyCode string    `description:"第三方给过来的客户编码，判断客户是否存在"`
	InteractionNum        int       `description:"互动总量"`
	InteractionNumSeller  int       `description:"销售可以查看的互动总量"`
}

type CompanyLog struct {
	Id              int       `orm:"column(id);pk"`
	CompanyId       int       `description:"客户id"`
	CompanyName     string    `description:"客户名称"`
	CreditCode      string    `description:"统一社会信用码"`
	CompanyCode     string    `description:"客户编码"`
	Sort            int       `description:"优先级"`
	IsFeeCustomer   int       `description:"是否付费用户"`
	Country         string    `description:"国家编码"`
	ProvinceId      int       `description:"省id"`
	CityId          int       `description:"市id"`
	Address         string    `description:"详细地址"`
	Ctype           int       `orm:"column(type)" description:"客户标签,1：付费客户，2：试用客户，3：流失客户，4：潜在客户" `
	Enabled         int       `description:"用户状态"`
	CreatedTime     time.Time `description:"创建时间"`
	LastUpdatedTime time.Time `description:"最后修改时间"`
	Seller          string    `description:"销售员"`
	SellsId         int       `description:"销售员ID"`
	CompanyBelong   string    `description:"客户所属，ficc：ficc客户，public_offering：公募客户，partner：合作伙伴"`
	StartDate       string    `description:"合同开始日期"`
	EndDate         string    `description:"合同结束日期"`
	LoseReason      string    `description:"流失原因"`
	LastType        int       `description:"原客户标签"`
	FirstStartDate  string    `description:"首次设置为试用客户开始时间"`
	FirstEndDate    string    `description:"首次设置为试用客户结束时间"`
	DateType        int       `description:"日期类型"`
	AdminId         int       `description:"操作人id"`
	LogType         string    `description:"日志类型"`
	LogCreateTime   time.Time `description:"日志创建时间"`
	Province        string    `description:"省"`
	City            string    `description:"市"`
}

type CompanyOperationRecord struct {
	Id              int       `orm:"column(id);pk"`
	CompanyId       int       `description:"客户id"`
	CompanyName     string    `description:"客户名称"`
	SellerId        int       `description:"销售员id"`
	SysUserId       int       `description:"操作者id"`
	SysRealName     string    `description:"操作者名称"`
	Remark          string    `description:"备注"`
	Operation       string    `description:"操作"`
	CreateTime      time.Time `description:"操作时间"`
	ProductId       int       `description:"产品id"`
	ProductName     string    `description:"产品名称"`
	ApproveUserId   int       `description:"审批人id"`
	ApproveRealName string    `description:"审批人姓名"`
	ApproveContent  string    `description:"审批人内容"`
	ApproveRemark   string    `description:"审批人内容"`
	Status          string    `description:"状态"`
}

type CompanyPermissionLog struct {
	Id                int `orm:"column(id);pk"`
	CompanyId         int
	ChartPermissionId int
	CreateTime        time.Time
	SysUserId         int
	SysUserName       string
	StartDate         string
	EndDate           string
	ProductId         int
	ProductName       string
}

type CompanyProduct struct {
	CompanyProductId    int       `orm:"column(company_product_id);pk" description:"客户产品id"`
	CompanyId           int       `description:"客户id"`
	ProductId           int       `description:"产品id"`
	ProductName         string    `description:"产品名称"`
	CompanyName         string    `description:"客户名称"`
	Source              string    `description:"来源"`
	Reasons             string    `description:"新增理由"`
	Status              string    `description:"客户状态"`
	IndustryId          int       `description:"行业id"`
	IndustryName        string    `description:"行业名称"`
	SellerId            int       `description:"销售id"`
	SellerName          string    `description:"销售名称"`
	GroupId             int       `description:"销售分组id"`
	DepartmentId        int       `description:"销售部门id"`
	IsSuspend           int       `description:"1:暂停,0:启用"`
	SuspendTime         time.Time `description:"暂停启用时间"`
	TryOutTime          time.Time `description:"正式转试用时间"`
	RenewalReason       string    `description:"正式转试用后的续约情况说明"`
	LastDescriptionTime time.Time `description:"上次添加说明时间"`
	RenewalIntention    int       `description:"是否勾选无续约意向,1:确认,0:未确认"`
	ApproveStatus       string    `description:"审批状态:'审批中','通过','驳回'"`
	FreezeTime          time.Time `description:"冻结时间"`
	FreezeReason        time.Time `description:"冻结理由"`
	Remark              string    `description:"备注信息"`
	CreateTime          time.Time `description:"创建时间"`
	ModifyTime          time.Time `description:"修改时间"`
	StartDate           string    `description:"开始日期"`
	EndDate             string    `description:"结束日期"`
	ContractEndDate     time.Time `description:"合同结束日期"`
	LoseReason          string    `description:"流失原因"`
	LossTime            time.Time `description:"流失时间"`
	CompanyType         string    `description:"客户类型"`
	OpenCode            string    `description:"开放给第三方的编码，不让第三方定位我们的客户信息"`
}

type CompanyProductLog struct {
	Id               int       `orm:"column(id);pk"`
	CompanyProductId int       `description:"产品id"`
	CompanyId        int       `description:"客户id"`
	ProductId        int       `description:"产品id"`
	ProductName      string    `description:"产品名称"`
	CompanyName      string    `description:"客户名称"`
	Source           string    `description:"来源"`
	Reasons          string    `description:"新增理由"`
	Status           string    `description:"客户状态"`
	IndustryId       int       `description:"行业id"`
	IndustryName     string    `description:"行业名称"`
	SellerId         int       `description:"所属销售id"`
	SellerName       string    `description:"所属销售名称"`
	GroupId          int       `description:"所属销售分组id"`
	DepartmentId     int       `description:"所属销售部门id"`
	IsSuspend        int       `description:"1:暂停,0:启用"`
	SuspendTime      time.Time `description:"暂停时间"`
	FreezeTime       time.Time `description:"冻结时间"`
	Remark           string    `description:"备注信息"`
	StartDate        string    `description:"开始日期"`
	EndDate          string    `description:"结束日期"`
	CreateTime       time.Time `description:"创建时间"`
	ModifyTime       time.Time `description:"修改时间"`
	LoseReason       string    `description:"流失原因"`
	LossTime         time.Time `description:"流失时间"`
	LogType          string    `description:"日志类型"`
	LogCreateTime    time.Time `description:"日志创建时间"`
	AdminId          int       `description:"操作人id"`
	ApproveStatus    string    `description:"审批状态:'审批中','通过','驳回'"`
	FreezeStartDate  string    `description:"冻结开始日期"`
	FreezeEndDate    string    `description:"冻结结束日期"`
}

//type CompanyReportPermission struct {
//之前的结构体已存在
//}

type CompanySource struct {
	SourceId   int    `orm:"column(source_id);pk"`
	SourceName string `description:"来源名称"`
}

// 判断公司名称是否存在
func GetCompanyCountByName(companyName string) (count int, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT  COUNT(1) AS count FROM company WHERE company_name = ?`
	err = o.Raw(sql, companyName).QueryRow(&count)
	return
}

// 判断三方公司公司名称是否存在
func GetCompanyCountByThirdName(tripartiteCompanyCode string) (count int, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT  COUNT(1) AS count FROM company WHERE tripartite_company_code = ?`
	err = o.Raw(sql, tripartiteCompanyCode).QueryRow(&count)
	return
}

// 获取来源详情
func GetCompanySourceByName(companyName string) (item *CompanySource, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT *  FROM company_source WHERE source_name = ?`
	err = o.Raw(sql, companyName).QueryRow(&item)
	return
}

func GetCompanyCode() (companyCode string, err error) {
	var num int
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT COUNT(1) AS num FROM company WHERE created_time >=? `
	err = o.Raw(sql, time.Now().Format(utils.FormatDate)).QueryRow(&num)
	if err != nil {
		return
	}
	companyCode = "KH" + time.Now().Format("20060102") + fmt.Sprintf("%03d", num)
	return
}

// 新增客户
func AddCompany(item *Company) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	lastId, err = o.Insert(item)
	return
}

// 更新客户基础信息
func (company *Company) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	_, err = o.Update(company, cols...)
	fmt.Println(company)
	fmt.Println(err)
	return
}

// 新增客户产品
func AddCompanyProduct(item *CompanyProduct) (newId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	newId, err = o.Insert(item)
	return
}

// 新增客户产品
func AddCompanyProductLog(item *CompanyProductLog) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	_, err = o.Insert(item)
	return
}

func GetCompanyReportPermissionCount(companyId, productId int) (count int, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT COUNT(1) AS count FROM company_report_permission WHERE company_id=? AND product_id=? `
	err = o.Raw(sql, companyId, productId).QueryRow(&count)
	return
}

func DeleteCompanyReportPermission(companyId, productId int) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := ` DELETE FROM company_report_permission WHERE company_id=? AND product_id=? `
	_, err = o.Raw(sql, companyId, productId).Exec()
	return
}

// 新增客户权限
func AddCompanyReportPermission(item *CompanyReportPermission) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	_, err = o.Insert(item)
	return
}

// 新增客户权限日志
func AddCompanyPermissionLog(item *CompanyPermissionLog) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	_, err = o.Insert(item)
	return
}

// 新增客户操作记录
func AddCompanyOperationRecord(item *CompanyOperationRecord) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	lastId, err = o.Insert(item)
	return
}

// 新增客户产品
func AddCompanyLog(item *CompanyLog) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	_, err = o.Insert(item)
	return
}

type UserSellerRelation struct {
	RelationId int64     `orm:"column(relation_id);pk"`
	UserId     int       `description:"用户id"`
	CompanyId  int       `description:"企业用户id"`
	SellerId   int       `description:"销售id"`
	Seller     string    `description:"销售员名称"`
	ProductId  int       `description:"产品id"`
	Mobile     string    `description:"手机号"`
	Email      string    `description:"邮箱"`
	ModifyTime time.Time `description:"修改时间"`
	CreateTime time.Time `description:"创建时间"`
}

// 添加销售员与员工的关系
func AddUserSellerRelation(userId int64, companyId, sellerId, productId int, seller, mobile, email string) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	relation := UserSellerRelation{
		UserId:     int(userId),
		SellerId:   sellerId,
		CompanyId:  companyId,
		Seller:     seller,
		ProductId:  productId,
		Mobile:     mobile,
		Email:      email,
		CreateTime: time.Now(),
		ModifyTime: time.Now(),
	}
	lastId, err = o.Insert(&relation)
	return
}
