package models

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

type CygxArticleHistoryRecordNewpv struct {
	Id               int `orm:"column(id);pk"`
	ArticleId        int
	UserId           int
	CreateTime       time.Time
	ModifyTime       time.Time
	Mobile           string `description:"手机号"`
	Email            string `description:"邮箱"`
	CompanyId        int    `description:"公司id"`
	CompanyName      string `description:"公司名称"`
	StopTime         int    `description:"停留时间"`
	OutType          int    `description:"退出方式，1正常退出，2强制关闭"`
	Source           string `description:"来源，MOBILE：手机端，PC：电脑端"`
	RegisterPlatform int    `description:"来源 1小程序，2：网页"`
}

// 添加阅读记录信息
func AddCygxArticleViewRecordNewpv(item *CygxArticleHistoryRecordNewpv) (lastId int64, err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	userSeller, err := company.GetCompanyProductListByUserId(item.UserId)
	if err != nil {
		return
	}

	lastId, err = o.Insert(item)
	if err != nil {
		return
	}

	//写入记录到总的统计表
	record := new(CygxArticleHistoryRecordAll)
	record.UserId = item.UserId
	record.ArticleId = item.ArticleId
	record.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
	record.ModifyTime = item.ModifyTime
	record.Mobile = item.Mobile
	record.Email = item.Email
	record.CompanyId = item.CompanyId
	record.CompanyName = item.CompanyName
	record.StopTime = item.StopTime
	record.OutType = item.OutType
	record.Source = item.Source
	record.CompanyStatus = userSeller.Status
	record.SellerName = userSeller.SellerName
	record.RegisterPlatform = utils.REGISTER_PLATFORM
	record.Platfor = 1
	lastId, err = o.Insert(record)

	if err != nil {
		return
	}
	// 软删除当天策略平台的文章阅读记录
	if item.Mobile != "" {
		sql := `UPDATE cygx_article_history_record_all 
			SET is_del = 1 
			WHERE
			article_id = ? 
			AND mobile = ?
			AND platfor = 2
			AND create_time >= date(NOW()) `
		_, err = o.Raw(sql, record.ArticleId, record.Mobile).Exec()
	}
	return
}

// 获取最新的一条阅读记录
func GetNewArticleHistoryRecordNewpv(uid, articleId int, modifytime string) (item *AddStopTimeNewRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM  cygx_article_history_record_newpv WHERE user_id = ? AND article_id = ? 	AND modify_time <='` + modifytime + `'  ORDER BY id DESC LIMIT 1;`
	err = o.Raw(sql, uid, articleId).QueryRow(&item)
	return
}

// 把十分钟之内的阅读记录进行累加
func UpdateCygxArticleViewRecordNewpv(itemRep *CygxArticleHistoryRecordNewpv, stopTime int) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	sql := `UPDATE cygx_article_history_record_newpv 
			SET modify_time = NOW(), stop_time = stop_time + ` + strconv.Itoa(stopTime) + `
			WHERE
			article_id = ? 
			AND user_id = ?
			AND out_type = 2
			AND timestampdiff(MINUTE,modify_time,NOW()) < 10`
	_, err = o.Raw(sql, itemRep.ArticleId, itemRep.UserId).Exec()

	// 修改总表的停留时间
	sql = `UPDATE cygx_article_history_record_all 
			SET modify_time = NOW(), stop_time = stop_time + ` + strconv.Itoa(stopTime) + `
			WHERE
			article_id = ? 
			AND user_id = ?
			AND out_type = 2
			AND timestampdiff(MINUTE,modify_time,NOW()) < 10`
	_, err = o.Raw(sql, itemRep.ArticleId, itemRep.UserId).Exec()

	return
}

// 把十分钟之内的阅读记录进行累加
func UpdateCygxArticleViewRecordNewpvList(itemRep *CygxArticleHistoryRecordNewpv, stopTime int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article_history_record_newpv 
			SET stop_time = stop_time + ` + strconv.Itoa(stopTime) + `
			WHERE
			article_id = ? 
			AND user_id = ? 
			AND modify_time = ? 
			AND id = ?`
	_, err = o.Raw(sql, itemRep.ArticleId, itemRep.UserId, itemRep.ModifyTime, itemRep.Id).Exec()

	return
}

// 获取当天总表的阅读记录
func GetArticleHistoryRecordAllList() (items []*CygxArticleHistoryRecordNewpv, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM cygx_article_history_record_all WHERE create_time >= date(NOW()) 
			AND mobile <> '' 
			AND platfor = 1
			GROUP BY mobile,article_id `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取列表信息根据手机号分组
func GetArticleHistoryRecordAllByMobileList(condition string) (items []*CygxArticleHistoryRecordAll, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article_history_record_all  WHERE 1 = 1 ` + condition + `  GROUP BY mobile   `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 修改用户阅读的相关信息
func UpdateCygxArticleHistoryRecordAll(wxUser *WxUserItem) (err error) {
	o := orm.NewOrm()
	var sql string
	if wxUser.Mobile != "" {
		sql = `UPDATE cygx_article_history_record_all SET email=?,company_id=?,company_name=?,user_id=?,real_name=? WHERE mobile=? `
		_, err = o.Raw(sql, wxUser.Email, wxUser.CompanyId, wxUser.CompanyName, wxUser.UserId, wxUser.RealName, wxUser.Mobile).Exec()
	} else if wxUser.Email != "" {
		sql = `UPDATE cygx_article_history_record_all SET mobile=?,company_id=?,company_name=?,user_id=?,real_name=? WHERE email=? `
		_, err = o.Raw(sql, wxUser.Mobile, wxUser.CompanyId, wxUser.CompanyName, wxUser.UserId, wxUser.RealName, wxUser.Email).Exec()
	}
	return
}

type EsUserInteraction struct {
	Id                       int    `description:"主键ID"`
	ArticleId                int    `description:"文章id"`
	ArticleType              int    `description:"文章类型 1：查研观向, 2:策略平台"`
	Title                    string `description:"标题"`
	PublishDate              string `description:"发布时间"`
	CreateTime               string `description:"创建时间"`
	StopTime                 string `description:"阅读停留时间"`
	RealName                 string `description:"姓名"`
	CompanyName              string `description:"公司名称"`
	CompanyId                int    `description:"公司ID"`
	SellerName               string `description:"所属销售"`
	SellerId                 int    `description:"所属销售ID"`
	Mobile                   string `description:"手机号"`
	Email                    string `description:"邮箱"`
	UserId                   int    `description:"用户ID"`
	UserArticleHistoryNum    int    `description:"用户阅读数量"`
	CompanyArticleHistoryNum int    `description:"机构阅读数量"`
}

// 机构阅读记录列表
func GetCygxArticleHistoryRecordByCompanyList(condition string, startSize, pageSize int) (items []*EsUserInteraction, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			r.id,
			art.title,
			art.article_id,
			art.article_id_md5,
			art.publish_date,
			art.category_name,
			r.create_time,
			r.mobile,
			r.user_id,
			r.company_name,
			cp.seller_name,
			cp.seller_id,
			cp.company_id,
			r.real_name,
			r.stop_time,
			ci.article_history_num AS company_article_history_num,
			ui.article_history_num AS user_article_history_num 
		FROM
			cygx_article_history_record_all AS r
			INNER JOIN cygx_article AS art ON art.article_id = r.article_id
			INNER 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
			INNER JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
		WHERE
			1 = 1 
			AND r.is_del = 0 ` + condition + ` GROUP BY r.id  `
	if startSize > 0 || pageSize > 0 {
		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 机构阅读记录列表
func GetCygxArticleHistoryRecordByCompanyListNew(condition string, pars interface{}, startSize, pageSize int) (items []*EsUserInteraction, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			r.id,
			art.title,
			art.article_id,
			art.article_id_md5,
			art.publish_date,
			art.category_name,
			r.create_time,
			r.mobile,
			r.user_id,
			r.company_name,
			r.company_id,
			r.real_name,
			r.stop_time,
			ci.article_history_num AS company_article_history_num,
			ui.article_history_num AS user_article_history_num 
		FROM
			cygx_article_history_record_all AS r
			INNER JOIN cygx_article AS art ON art.article_id = r.article_id
			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
		WHERE
			1 = 1 
			AND r.is_del = 0 ` + condition + ` GROUP BY r.id  `
	if startSize > 0 || pageSize > 0 {
		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 获取阅读记录数量
func GetCygxArticleHistoryCountByCompany(condition string) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := `SELECT
	COUNT( 1 ) AS count 
FROM
	(
	SELECT
		COUNT( 1 ) 
	FROM
		cygx_article_history_record_all AS r
		INNER JOIN cygx_article AS art ON art.article_id = r.article_id
		INNER 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
		INNER JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
	WHERE
		r.is_del = 0 ` + condition + `
	GROUP BY
	r.id 
	) AS count `
	err = o.Raw(sqlCount).QueryRow(&count)
	return
}

type CygxArticleHistoryAllTopResp struct {
	Pv        int `description:"阅读PV"`
	ArticleId int `description:"文章id"`
	Num       int `description:"数量"`
}

// 获取近15天之内的阅读数据最多的15报告
func GetCygxArticleHistoryAllTop(pars []interface{}, condition string) (items []*CygxArticleHistoryAllTopResp, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			COUNT( 1 ) AS pv,
			a.article_id 
		FROM
			cygx_article_history_record_all AS l
			INNER JOIN cygx_article AS a ON a.article_id = l.article_id
			INNER JOIN cygx_report_mapping AS m ON m.category_id = a.category_id 
			WHERE
				1 = 1 
				AND l.platfor = 1` + condition + `
			GROUP BY
				l.article_id 
			ORDER BY
				pv DESC ,a.publish_date DESC 
				LIMIT 15 `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 列表
func GetCygxArticleHistoryRecordNewpvList(condition string, pars []interface{}) (items []*CygxArticleHistoryRecordNewpv, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article_history_record_newpv as art WHERE 1= 1  `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

type ListPvUvResp struct {
	ArticleId int `description:"文章ID"`
	Pv        int `description:"pv"`
	Uv        int `description:"pv"`
}

// 列表
func GetCygxArticleHistoryRecordNewpvListPv(condition string, pars []interface{}) (items []*ListPvUvResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT( 1 ) AS pv,
			article_id
		FROM
			cygx_article_history_record_newpv  WHERE 1 = 1  `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY article_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 查研PV列表
func GetCygxArticleHistoryRecordNewpvListPvCy(condition string, pars []interface{}) (items []*ListPvUvResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT( 1 ) AS pv,
			article_id
		FROM
			cygx_article_history_record_all  WHERE 1 = 1  AND platfor = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY article_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 策略PV列表
func GetCygxArticleHistoryRecordNewpvListPvCl(condition string, pars []interface{}) (items []*ListPvUvResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT( 1 ) AS pv,
			article_id
		FROM
			cygx_article_history_record_all  WHERE 1 = 1  AND platfor = 2 AND is_del = 0 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY article_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

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