package company

import (
	"github.com/beego/beego/v2/client/orm"
	"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:"地区类型，国内，国外"`
}

type CompanyList struct {
	CompanyId   int    `description:"客户id" json:"company_id"`
	CompanyName string `description:"客户名称" json:"company_name"`
	CreditCode  string `description:"社会统一信用码" json:"credit_code"`
	Status      string `description:"客户状态" json:"status"`
}

// GetCompanyById 根据企业id获取企业信息
func GetCompanyById(companyId int) (items *Company, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM company where company_id= ? `
	err = o.Raw(sql, companyId).QueryRow(&items)
	return
}

// GetList 获取客户列表
func GetList(condition string, pars []interface{}, startSize, pageSize int) (total int, list []*CompanyList, err error) {
	o := orm.NewOrm()
	sql := `SELECT a.company_id,a.company_name,a.credit_code,b.status
			FROM company AS a
			INNER JOIN company_product AS b ON a.company_id=b.company_id
			WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY a.company_id ORDER BY  a.last_updated_time DESC `

	totalSql := `select count(*) count from (` + sql + `) g`

	err = o.Raw(totalSql, pars).QueryRow(&total)
	if err != nil {
		return
	}
	sql += ` limit ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}
