package company

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

// CompanyProductUpdateLog 客户产品变更日志表
type CompanyProductUpdateLog struct {
	Id          int       `orm:"column(id);pk"`
	CompanyId   int       `description:"客户id"`
	ProductId   int       `description:"产品id"`
	Status      string    `description:"变更后的状态"`
	SellerId    int       `description:"销售id"`
	SellerName  string    `description:"销售名称"`
	Source      string    `description:"来源"`
	IsFormal    int       `description:"是否已经转正式，0是没有转正式，1是已经转过正式"`
	StartDate   time.Time `description:"开始日期"`
	EndDate     time.Time `description:"结束日期"`
	RealEndDate time.Time `description:"实际结束日期"`
	CreateTime  time.Time `description:"创建时间"`
}

// AddCompanyProductUpdateLog 新增客户产品变更日志
func AddCompanyProductUpdateLog(item *CompanyProductUpdateLog) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	if err != nil {
		return
	}
	item.Id = int(lastId)
	return
}

type CompanyReportRecordGroup struct {
	AdminId int `description:"所属销售id"`
	//AdminName string `description:"所属销售名称"`
	Num        int    `description:"汇总次数"`
	CompanyIds string `description:"客户id字符串"`
}

// GetGroupCompanyReportRecordGroupList 获取销售分组数据
func GetGroupCompanyReportRecordGroupList(condition string, pars []interface{}) (list []*CompanyReportRecordGroup, err error) {
	o := orm.NewOrm()
	sql := ` SELECT seller_id as admin_id,count(DISTINCT(company_id)) num,GROUP_CONCAT(DISTINCT company_id SEPARATOR ',') AS company_ids
				FROM  company_product_update_log 
				WHERE 1=1  
 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY seller_id`
	_, err = o.Raw(sql, pars).QueryRows(&list)

	return
}

// GetCompanyProductUpdateLogList 获取客户变更试用的数据
func GetCompanyProductUpdateLogList() (list []*CompanyProductUpdateLog, err error) {
	o := orm.NewOrm()
	//add
	//receive
	//thaw
	//apply_receive
	//delay
	sql := ` select * from company_product_update_log where source in("add","receive","thaw","apply_receive");`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// GetCompanyProductLogItem 获取客户变更试用的数据
func GetCompanyProductLogItem(companyId, productId int, createTime time.Time) (item *CompanyProductUpdateLog, err error) {
	o := orm.NewOrm()
	sql := ` select * from company_product_log where company_id=? and product_id=? and create_time >= ? and create_time <=?`
	err = o.Raw(sql, companyId, productId, createTime.Add(-2*60*time.Second), createTime.Add(2*60*time.Second)).QueryRow(&item)
	return
}
