package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models/company"
	"strconv"
	"time"
)

type ChartResultApi struct {
	Data []ChartResultApidate `json:"data"`
	Code int                  `json:"code"`
	Msg  string               `json:"msg"`
}

type ChartFavoritesResultApi struct {
	Data       []ChartInfo `json:"data"`
	Code       int         `json:"code"`
	Msg        string      `json:"msg"`
	Pagination Pagination  `json:"pagination"`
}

type Pagination struct {
	Total     int `json:"total"`
	Page      int `json:"id"`
	PageSize  int `json:"page_size"`
	PageTotal int `json:"page_total"`
}

type ChartInfo struct {
	ChartInfo  *ChartResultApidate `json:"chart_info"`
	ChartId    int                 `json:"chart_id"`
	CreateDate string              `json:"add_favorites_time"`
}

type ChartResultApidate struct {
	ChartId       int    `json:"id"`
	PtagId        int    `json:"ptag_id"`
	CtagId        int    `json:"ctag_id"`
	Title         string `json:"title"`
	TitleEn       string `json:"title_en"`
	CreateDate    string `json:"create_date"`
	UpdateDate    string `json:"update_date"`
	PublishStatus int    `json:"publish_status"`
	Cover         string `json:"cover"`
	Iframe        string `json:"iframe"`
	Ptag          Ptag   `json:"ptag"`
	Ctag          Ptag   `json:"ctag"`
	PtagTwo       Ptag   `json:"ptag1"`
	CtagTwo       Ptag   `json:"ctag1"`
}

type Ptag struct {
	Id          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

type Ctag struct {
	Id          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	PtagId      int    `json:"ptag_id"`
}

type CygxChart struct {
	Id            int       `orm:"column(id);pk"`
	ChartId       int       `description:"图表id"`
	PtagId        int       `description:"图表父类分类id"`
	CtagId        int       `description:"图表子类分类id"`
	PtagIdTwo     int       `description:"图表父类分类id"`
	CtagIdTwo     int       `description:"图表子类分类id"`
	Title         string    `description:"标题"`
	TitleEn       string    `description:"英文标题 "`
	CreateDate    string    `description:"本地创建时间"`
	CreateDateApi time.Time `description:"图表创建时间"`
	PublishStatus int       `description:"发布状态"`
	PtagName      string    `description:"父类名称"`
	CtagName      string    `description:"子类名称"`
	Cover         string    `description:"图表图片"`
	Iframe        string    `description:"图表详情跳转地址"`
	PtagNameTwo   string    `description:"父类名称"`
	CtagNameTwo   string    `description:"子类名称"`
}

type CygxChartDetail struct {
	ChartId       int    `description:"图表id"`
	Title         string `description:"标题"`
	TitleEn       string `description:"英文标题 "`
	IsCollection  bool   `description:"是否收藏 "`
	CollectionNum int    `description:"本人收藏数量 "`
	HttpUrl       string `orm:"column(iframe)";description:"文章链接跳转地址"`
}

func GetChartCountById(chartId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM cygx_chart WHERE chart_id = ? `
	err = o.Raw(sql, chartId).QueryRow(&count)
	return
}

// 新增图表
func AddCygxChart(item *CygxChart) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// 标签分类
type ChartPtagResultApi struct {
	Data []ChartPtagResultApidate `json:"data"`
	Code int                      `json:"code"`
	Msg  string                   `json:"msg"`
}

type ChartPtagResultApidate struct {
	ChartPermissionId   int    `json:"id"`
	ChartPermissionName string `json:"name"`
	Ctag                []Ctag `json:"ctag"`
}

type ChartPtagResp struct {
	ChartPermissionId int         `description:"分类ID"`
	PermissionName    string      `description:"分类名称"`
	List              []*CtagResp `description:"子分类"`
}

type CtagResp struct {
	CtagId int    `description:"子分类ID"`
	Name   string `description:"子分类名称"`
}

type ChartUserTokenResult struct {
	AccessToken string `json:"access_token"`
}

type ChartUserTokenResultApi struct {
	Data ChartUserTokenResult `json:"data"`
	Code int                  `json:"code"`
	Msg  string               `json:"msg"`
}

type HomeChartListResp struct {
	ChartId     int    `description:"图表ID"`
	Title       string `description:"标题"`
	TitleEn     string `description:"英文标题 "`
	CreateDate  string `description:"创建时间"`
	PtagName    string `description:"父类名称"`
	CtagName    string `description:"子类名称"`
	PtagNameTwo string `description:"父类名称"`
	CtagNameTwo string `description:"子类名称"`
	CtagNamePc  string `description:"Pc端所有的分类名称"`
	BodyHtml    string `orm:"column(cover)";description:"图片链接"`
	HttpUrl     string `orm:"column(iframe)";description:"文章链接跳转地址"`
	IsNeedJump  bool   `description:"是否需要跳转链接地址"`
	IsTop       bool   `description:"是否置顶"`
	NumTop      int    `description:"置顶数量"`
	Source      int    `description:"来源  1:文章, 2:图表"`
}

type HomeChartListItem struct {
	IsBindingMobile bool `description:"是否绑定过手机号"`
	Paging          *paging.PagingItem
	List            []*HomeChartListResp `description:"图表列表"`
}

type ChartCollectReq struct {
	ChartId int `description:"图表ID"`
}

// 获取图表列表
func GetChartList(condition string, pars []interface{}, startSize, pageSize int) (items []*HomeChartListResp, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM cygx_chart AS a WHERE a.publish_status=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY create_date DESC LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 获取图表列表
func GetChartListCollection(chartIds string, userId, startSize, pageSize int) (items []*UserInteraction, err error) {
	o := orm.NewOrm()
	sql := ` SELECT a.*,
			t.create_time AS t_create_time,
			c.create_time AS c_create_time,
			( SELECT COUNT(*) FROM cygx_chart_top AS t WHERE t.chart_id = a.chart_id AND t.user_id = ? ) AS num_top,
			( SELECT COUNT(*) FROM cygx_chart_collect AS c WHERE c.chart_id = a.chart_id AND c.user_id = ? ) AS num_c 
		FROM
			cygx_chart AS a
			LEFT JOIN cygx_chart_top AS t ON t.chart_id = a.chart_id
			LEFT JOIN cygx_chart_collect AS c ON c.chart_id = a.chart_id 
		WHERE
			 1=1
			AND a.chart_id IN (` + chartIds + `) 
		GROUP BY
			a.chart_id 
		ORDER BY
			t_create_time DESC,
			c_create_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, userId, userId, startSize, pageSize).QueryRows(&items)
	return
}

// 获取图表列表本地
func GetChartListCollectionWithCygxByMobile(condition string, startSize, pageSize int) (items []*HomeChartListResp, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			a.chart_id,a.title,a.title_en,a.ptag_name,a.ctag_name,a.cover,a.iframe,a.ptag_name_two,a.ctag_name_two,
			r.create_time AS create_date
		FROM
			cygx_chart_collect AS r
			INNER JOIN cygx_chart_all AS a ON a.chart_id = r.chart_id
		WHERE 1 =1 ` + condition + `
		GROUP BY
			a.chart_id 
		ORDER BY
			create_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// 获取图表列表本地
func GetChartListCollectionWithCygx(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			a.chart_id,a.title,a.title_en,a.ptag_name,a.ctag_name,a.cover,a.iframe,a.ptag_name_two,a.ctag_name_two,
			r.create_time AS create_time
		FROM
			cygx_chart_collect AS r
			INNER JOIN cygx_chart_all AS a ON r.chart_id = a.chart_id
		WHERE
			1= 1 ` + condition +
		`  GROUP BY
			a.chart_id 
		ORDER BY
			r.create_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// 获取图表数量
func GetChartCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count
                FROM cygx_chart AS a
                WHERE a.publish_status=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func GetChartCountByUser(condition string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_chart_collect as r INNER JOIN cygx_chart_all AS a ON r.chart_id = a.chart_id  WHERE 1=1   ` + condition
	err = orm.NewOrm().Raw(sql).QueryRow(&count)
	return
}
func GetChartCountByUserMobile(condition string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_chart_collect as r  INNER JOIN cygx_chart_all AS a ON a.chart_id = r.chart_id  WHERE 1= 1 ` + condition
	err = orm.NewOrm().Raw(sql).QueryRow(&count)
	return
}

type CygxChartCollect struct {
	Mobile string `description:"手机号"`
	UserId int    `description:"手机号"`
}

// 获取图表列表
func GetChartCollectList(condition string) (items []*UserInteraction, err error) {
	o := orm.NewOrm()
	sql := `SELECT u.mobile,u.user_id,u.real_name FROM cygx_chart_collect AS r
			INNER JOIN wx_user AS u ON u.mobile = r.mobile 
			LEFT  JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
			WHERE 1= 1 ` + condition + `   GROUP BY r.mobile  ORDER BY ui.chart_count_num DESC `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取图表列表
func GetChartCollectBycompanyList(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
	o := orm.NewOrm()
	sql := `SELECT u.mobile,u.user_id,u.real_name,r.company_name,
			cp.seller_name FROM cygx_chart_collect AS r
			INNER JOIN wx_user AS u ON u.user_id = r.user_id 
			INNER  JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
			LEFT JOIN company_product AS cp ON cp.company_id = r.company_id AND cp.product_id = 2
			INNER JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
			WHERE 1= 1 ` + condition + `   GROUP BY r.mobile  ORDER BY ci.chart_count_num DESC , ui.chart_count_num DESC `
	if startSize > 0 || pageSize > 0 {
		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取一共有多少用户收藏图表
func GetChartCountByUserCount(condition string) (count int, err error) {
	sql := ` SELECT
	COUNT( 1 ) AS count 
FROM
	(
	SELECT
		COUNT( 1 ) 
	FROM
		cygx_chart_collect AS r
		INNER JOIN wx_user AS u ON u.user_id = r.user_id
		INNER JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
		INNER JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id 
		WHERE 1= 1 ` + condition + ` GROUP BY u.user_id ) AS count`
	err = orm.NewOrm().Raw(sql).QueryRow(&count)
	return
}

func GetChartCountBySeller(condition string) (list []*company.CompanyReportRecordGroup, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	p.seller_id AS admin_id,
	count(
	DISTINCT ( r.company_id )) num,
	GROUP_CONCAT( DISTINCT r.company_id SEPARATOR ',' ) AS company_ids 
FROM
	cygx_chart_collect AS r
	INNER JOIN cygx_chart_all AS a ON a.chart_id = r.chart_id
	INNER JOIN company_product AS p ON p.company_id = r.company_id 
WHERE
	1 = 1 
	AND p.product_id = 2  ` + condition

	sql += ` GROUP BY p.seller_id `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}