package models

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

type CygxArticleHistoryRecord struct {
	Id          int `orm:"column(id);pk"`
	ArticleId   int
	UserId      int
	CreateTime  time.Time
	Mobile      string    `description:"手机号"`
	Email       string    `description:"邮箱"`
	CompanyId   int       `description:"公司id"`
	CompanyName string    `description:"公司名称"`
	ModifyTime  time.Time `description:"修改时间"`
	StopTime    int       `description:"停留时间"`
	OutType     int       `description:"退出方式，1正常退出，2强制关闭"`
}

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

// 添加历史信息
func AddCygxArticleHistoryRecord(item *CygxArticleHistoryRecord) (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()
		}
	}()
	//var count int
	//sql := `SELECT COUNT(1) AS count FROM cygx_article_history_record WHERE user_id=? AND article_id=? `
	//err = o.Raw(sql, item.UserId, item.ArticleId).QueryRow(&count)

	sql := `UPDATE wx_user SET report_last_view_time=NOW() WHERE user_id=?`
	_, err = o.Raw(sql, item.UserId).Exec()
	if err != nil {
		return
	}
	//if count > 0 {
	//	sql := `UPDATE cygx_article_history_record SET modify_time=NOW() WHERE user_id=? AND article_id=? `
	//	_, err = o.Raw(sql, item.UserId, item.ArticleId).Exec()
	//} else {
	//	item.ModifyTime = time.Now()
	//	lastId, err = o.Insert(item)
	//}
	item.ModifyTime = time.Now()
	lastId, err = o.Insert(item)
	return
}

// 获取用户阅读记录
func GetUserToArticleCount(uid, articleId int) (count int, err error) {
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_article_history_record WHERE user_id=? AND article_id=? `
	o := orm.NewOrm()
	err = o.Raw(sqlCount, uid, articleId).QueryRow(&count)
	return
}

type AddStopTimeRep struct {
	ArticleId int    `description:"文章ID"`
	StopTime  int    `description:"停留时间"`
	OutType   int    `description:"退出方式，1正常退出，2强制关闭"`
	Source    string `description:"来源，MOBILE：手机端，PC：电脑端"`
}

type AddStopTimeHtgjRep struct {
	ArticleId   int    `description:"文章ID"`
	StopTime    int    `description:"停留时间"`
	OutType     int    `description:"退出方式，1正常退出，2强制关闭"`
	Source      string `description:"来源，MOBILE：手机端，PC：电脑端"`
	CompanyCode string `description:"机构编码"`
	CompanyName string `description:"机构名称"`
	Email       string `description:"机构邮箱"`
	Sign        string `description:"签名"`
}

type AddStopTimeNewRep struct {
	Id        int `description:"ID"`
	ArticleId int `description:"文章ID"`
	StopTime  int `description:"停留时间"`
	OutType   int `description:"退出方式，1正常退出，2强制关闭"`
}

type ArticleDetailAddStopTimeRep struct {
	HasPermission int `description:"1:有该行业权限,正常展示，2：无该行业权限，不存在权益客户下，3:无该品类权限,已提交过申请，4：无该行业权限,未提交过申请，5：潜在客户，未提交过申请，6：潜在客户,已提交过申请"`
	HasFree       int `description:"1:已付费(至少包含一个品类的权限)，2:未付费(没有任何品类权限)"`
}

func UpdateArticleStopTime(item *AddStopTimeNewRep) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article_history_record SET stop_time = ?,out_type = ? WHERE id =?`
	_, err = o.Raw(sql, item.StopTime, item.OutType, item.Id).Exec()
	return
}

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

// 获取用户阅读记录
func GetNoAddStoptimeArticleCount(uid, articleId int) (count int, err error) {
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_article_history_record WHERE user_id=? AND article_id=? AND create_time > '` + utils.OnlineTime + `' AND stop_time = 0 `
	o := orm.NewOrm()
	err = o.Raw(sqlCount, uid, articleId).QueryRow(&count)
	return
}

// 最新标的列表
func GetArticleHistoryList() (items []*CygxArticleHistoryRecordNewpv, err error) {
	o := orm.NewOrm()
	sql := `SELECT *  FROM cygx_article_history_record WHERE company_id != 16 `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取用户阅读记录
func GetUserToArticleHistory(uid int, articleIdArr []int) (items []*CygxArticleHistoryResp, err error) {
	arrLen := len(articleIdArr)
	if arrLen == 0 {
		return
	}
	sql := `SELECT
			article_id 
		FROM
			cygx_article_history_record 
		WHERE
			1 = 1 
		AND user_id = ?
			AND article_id IN (` + utils.GetOrmInReplace(len(articleIdArr)) + `)   
		GROUP BY
			article_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql, uid, articleIdArr).QueryRows(&items)
	return
}

// GetArticleHistoryRecord 或用户阅读过的文章ID
func GetArticleHistoryRecord(condition string, pars []interface{}) (item []*CygxArticleHistoryRecord, err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT *
			FROM
			cygx_article_history_record  
			WHERE 1 = 1 ` + condition + `  GROUP BY article_id`
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}
