package models

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

// CompanyViewStatistics 客户报告报告阅读数量统计表
type CompanyViewStatistics struct {
	Id         int       `orm:"column(id)" description:"自增Id"`
	CompanyId  int       `description:"客户id"`
	ViewNum    int       `description:"阅读总数"`
	Date       time.Time `description:"阅读日期"`
	CreateTime time.Time `description:"添加时间"`
}

// CompanyViewTotalSlice 获取客户的浏览次数
type CompanyViewTotalSellerSlice struct {
	CompanyIds string `description:"客户id字符串"`
	Num        int    `description:"用户浏览次数"`
	AdminId    int    `description:"所属销售id"`
}

// GetCompanyViewTotalList 获取客户的浏览数
func GetCompanyViewTotalList(condition string, pars []interface{}, viewNum int, sumNumType string) (items []*CompanyViewTotalSellerSlice, err error) {
	o := orm.NewOrm()
	sql := `select count(DISTINCT(company_id)) num,GROUP_CONCAT(DISTINCT company_id SEPARATOR ',') AS company_ids,admin_id from (SELECT sum(a.view_num) sum_num,a.company_id,b.seller_id admin_id FROM company_view_statistics a 
join company_product b on a.company_id=b.company_id
WHERE 1=1 `
	if condition != "" {
		sql += condition
	}

	childSql := ` sum_num >= `
	if sumNumType == "<" {
		childSql = ` sum_num ` + sumNumType + ` `
	}

	sql += ` GROUP BY company_id) b where 1 = 1 and ` + childSql + `? GROUP BY admin_id`
	_, err = o.Raw(sql, pars, viewNum).QueryRows(&items)
	return
}

// GetAllCompanyViewTotalList 获取所有客户的浏览数
func GetAllCompanyViewTotalList(condition string, pars []interface{}, viewNum int, sumNumType string) (items []*CompanyViewTotalSellerSlice, err error) {
	o := orm.NewOrm()
	sql := `select count(DISTINCT(company_id)) num,GROUP_CONCAT(DISTINCT company_id SEPARATOR ',') AS company_ids,admin_id from (SELECT sum(a.view_num) sum_num,a.company_id,b.seller_id admin_id FROM company_view_statistics a 
join company_product b on a.company_id=b.company_id
WHERE 1=1 `
	if condition != "" {
		sql += condition
	}

	childSql := ` sum_num >= `
	if sumNumType == "<" {
		childSql = ` sum_num ` + sumNumType + ` `
	}

	sql += ` GROUP BY company_id) b where 1 = 1 and ` + childSql + `? GROUP BY admin_id`
	_, err = o.Raw(sql, pars, viewNum).QueryRows(&items)
	return
}
