package cygx

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/utils"
	"html"
	"strconv"
	"strings"
	"time"
)

type SummaryManageAddRep struct {
	ArticleId               int    `description:"文章ID，等于0新增，大于0修改"`
	ArticleTypeId           int    `description:"文章类型ID"`
	ChartPermissionIds      string `description:"行业ID ,多个用 , 隔开"`
	IndustryName            string `description:"产业名称"`
	SubjectName             string `description:"标的名称,多标的 用 , 隔开"`
	Title                   string `description:"标题"`
	Abstract                string `description:"摘要"`
	Body                    string `description:"内容"`
	SellerAndMobile         string `description:"销售和手机号"`
	DoType                  int    `description:"操作类型 0，保存 、1，发布"`
	Department              string `description:"作者"`
	IndustrialManagementIds string `description:"产业id 多个用 , 隔开"`
	IndustrialSubjectIds    string `description:"标的id 多个用 , 隔开"`
	PublishDate             string `description:"发布时间 列如 2020-03-23"`
	ReportLink              string `description:"报告链接"`
}

type SummaryManageEditDetail struct {
	SummaryManageId int `description:"纪要ID 等于0新增纪要，大于0修改纪要"`
	ArticleId       int `description:"文章ID"`
	//ChartPermissionId  int    `description:"行业ID"`
	ChartPermissionIds string `description:"行业ID ,多个用 , 隔开"`
	Title              string `description:"标题"`
	Abstract           string `description:"摘要"`
	Body               string `description:"内容"`
	SellerAndMobile    string `description:"销售和手机号"`
	SubjectName        string `description:"标的名称"`
	IndustryName       string `description:"产业名称"`
	PublishStatus      int    `description:"发布状态，0未发布 ，1已发布"`
	ListIndustrial     []*IndustrialActivityGroupManagementRep
	ListSubject        []*SubjectActivityGroupManagementRep
}

type SummaryManageIdRep struct {
	ArticleId int `description:"文章ID"`
}

type CygxArticle struct {
	SummaryManageId    int       `orm:"column(id);pk"`
	CategoryName       string    `description:"行业分类名称"`
	CategoryId         int       `description:"行业分类ID"`
	CategoryIdTwo      int       `description:"分类id用作修改匹配类型使用"`
	ArticleId          int       `description:"文章ID"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Body               string    `description:"内容"`
	BodyText           string    `description:"内容"`
	PublishStatus      int       `description:"发布状态，0未发布 ，1已发布"`
	PublishDate        time.Time `description:"发布时间"`
	CreateDate         time.Time `description:"创建时间"`
	LastUpdatedTime    time.Time `description:"更新时间"`
	IsSummary          int       `description:"是否属于纪要库 1是、0否"`
	IsReport           int       `description:"是否属于报告 1是、0否"`
	ReportType         int       `description:"'报告类型，1行业报告，2产业报告'"`
	Source             int       `description:"来源 0策略平台同步，1小程序后台添加"`
	MatchTypeName      string    `description:"匹配类型名称"`
	ArticleIdMd5       string    `description:"ID，md5值"`
	UpdateFrequency    string    `description:"更新周期"`
	SellerAndMobile    string    `description:"销售和手机号"`
	Department         string    `description:"作者"`
	ExpertBackground   string    `description:"专家背景"`
	ExpertNumber       string    `description:"专家编号"`
	InterviewDate      string    `description:"访谈日期"`
	FileLink           string    `description:"下载预览链接"`
	ChartPermissionIds string    `description:"行业ID ,多个用 , 隔开"`
	DepartmentId       int       `description:"作者ID"`
	Periods            string    `description:"期数"`
	ReportLink         string    `description:"报告链接"`
	ArticleType        string    `description:"文章类型 文章类型，lyjh:路演精华 "`
	HavePublish        int       `description:"是否发布过，1是 ，0 否"`
	IsClass            int       `description:"是否归类过，1是 ，0 否"`
	SubCategoryName    string    `description:"主题名称"`
	LinkArticleId      int       `description:"报告ID链接"`
	AdminId            int       `description:"销售/管理员ID"`
	AdminName          string    `description:"销售/管理员姓名"`
	ArticleTypeId      int       `description:"文章类型ID"`
	ArticleTypeName    string    `description:"文章类型名称"`
	Annotation         string    `description:"核心观点"`
	VisibleRange       int       `description:"设置可见范围1全部，0内部"`
	//NickName           string    `description:"作者昵称"`
}

type CygxArticleResp struct {
	SummaryManageId    int       `orm:"column(id);pk"`
	CategoryName       string    `description:"行业分类名称"`
	CategoryId         int       `description:"行业分类ID"`
	CategoryIdTwo      int       `description:"行业分类ID"`
	ArticleId          int       `description:"文章ID"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Body               string    `description:"内容"`
	BodyText           string    `description:"内容"`
	PublishStatus      int       `description:"发布状态，0未发布 ，1已发布"`
	PublishDate        time.Time `description:"发布时间"`
	CreateDate         time.Time `description:"创建时间"`
	LastUpdatedTime    time.Time `description:"更新时间"`
	IsSummary          int       `description:"是否属于纪要库 1是、0否"`
	IsReport           int       `description:"是否属于报告 1是、0否"`
	Source             int       `description:"来源 0策略平台同步，1小程序后台添加"`
	ArticleIdMd5       string    `description:"ID，md5值"`
	UpdateFrequency    string    `description:"更新周期"`
	SellerAndMobile    string    `description:"销售和手机号"`
	Department         string    `description:"作者"`
	ExpertBackground   string    `description:"专家背景"`
	ExpertNumber       string    `description:"专家编号"`
	InterviewDate      string    `description:"访谈日期"`
	FileLink           string    `description:"下载预览链接"`
	ChartPermissionIds string    `description:"行业ID ,多个用 , 隔开"`
	DepartmentId       int       `description:"作者ID"`
	Periods            string    `description:"期数"`
	ReportLink         string    `description:"报告链接"`
	ArticleType        string    `description:"文章类型 文章类型，lyjh:路演精华 "`
	HavePublish        int       `description:"是否发布过，1是 ，0 否"`
	IsClass            int       `description:"是否归类过，1是 ，0 否"`
	IsClassFail        int       `description:"是否自动归类失败，1是 ，0 否"`
	SubCategoryName    string    `description:"主题名称"`
	LinkArticleId      int       `description:"报告ID链接"`
	NickName           string    `description:"作者昵称"`
	HeadImgUrl         string    `description:"作者头像"`
	SubjectIds         string    `description:"报告所关联的标的"`
	AdminId            int       `description:"销售/管理员ID"`
	AdminName          string    `description:"销售/管理员姓名"`
	Annotation         string    `description:"核心观点"`
	VisibleRange       int       `description:"设置可见范围1全部，0内部"`
	TopTime            int       `description:"置顶时间"`
}

type GetSummaryManageListRep struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*CygxArticleList
}

type ElasticTestArticleDetail struct {
	ArticleId        int    `description:"报告id"`
	Title            string `description:"标题"`
	BodyText         string `description:"内容"`
	PublishDate      string `description:"发布时间"`
	ExpertBackground string `description:"专家背景"`
	CategoryId       string `description:"文章分类"`
	Abstract         string `description:"摘要"`
	Annotation       string `description:"核心观点"`
}

// 添加文章
func AddArticle(item *CygxArticle) (newId int64, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	newId, err = o.Insert(item)
	fmt.Println(newId)
	return
}

//item.ExpertBackground = expertContentStr
//item.ExpertNumber = expertNumStr
//item.InterviewDate = interviewDateStr
//item.FileLink = fileLink

// 修改文章
func EditArticle(item *CygxArticle, oldPublishStatus int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	if oldPublishStatus == 1 {
		sql := `UPDATE cygx_article SET category_name=?, title=?, abstract=?, body=?, body_text=?, publish_status=?,last_updated_time = ?,seller_and_mobile=?,expert_background =?, expert_number=? ,interview_date=?, file_link=? ,chart_permission_ids =? WHERE id=? AND source = 1`
		_, err = o.Raw(sql, item.CategoryName, item.Title, item.Abstract, item.Body, item.BodyText, item.PublishStatus, item.LastUpdatedTime, item.SellerAndMobile, item.ExpertBackground, item.ExpertNumber, item.InterviewDate, item.FileLink, item.ChartPermissionIds, item.SummaryManageId).Exec()
	} else {
		if item.PublishStatus == 1 {
			sql := `UPDATE cygx_article SET category_name=?, title=?, abstract=?, body=?, body_text=?, publish_status=?, publish_date =? ,last_updated_time = ?,seller_and_mobile=?,expert_background =?, expert_number=? ,interview_date=?, file_link=?,chart_permission_ids =? WHERE id=? AND source = 1`
			_, err = o.Raw(sql, item.CategoryName, item.Title, item.Abstract, item.Body, item.BodyText, item.PublishStatus, item.PublishDate, item.LastUpdatedTime, item.SellerAndMobile, item.ExpertBackground, item.ExpertNumber, item.InterviewDate, item.FileLink, item.ChartPermissionIds, item.SummaryManageId).Exec()
		} else {
			sql := `UPDATE cygx_article SET category_name=?, title=?, abstract=?, body=?, body_text=?, publish_status=?,last_updated_time = ?, publish_date = '' ,seller_and_mobile=?,expert_background =?, expert_number=? ,interview_date=?, file_link=?,chart_permission_ids =? WHERE id=? AND source = 1`
			_, err = o.Raw(sql, item.CategoryName, item.Title, item.Abstract, item.Body, item.BodyText, item.PublishStatus, item.LastUpdatedTime, item.SellerAndMobile, item.ExpertBackground, item.ExpertNumber, item.InterviewDate, item.FileLink, item.ChartPermissionIds, item.SummaryManageId).Exec()
		}
	}
	return
}

func GetMaxArticleIdInfo() (item *ArticleDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article   ORDER BY article_id desc  LIMIT 1`
	err = o.Raw(sql).QueryRow(&item)
	return
}

// 通过纪要ID获取文章详情
func GetArticleIdInfoBySummaryManageId(summaryManageId int) (item *CygxArticleResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT art.* ,dm.nick_name  FROM cygx_article as art 
			LEFT JOIN cygx_article_department as dm ON dm.department_id = art.department_id  WHERE id=? AND source = 1`
	err = o.Raw(sql, summaryManageId).QueryRow(&item)
	return
}

// 通过文章ID获取文章、以及所关联的标的详情
func GetArticleInfoOtherByArticleId(articleId int) (item *CygxArticleResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT art.* ,dm.nick_name ,dm.img_url as head_img_url   FROM cygx_article as art 
			LEFT JOIN cygx_article_department as dm ON dm.department_id = art.department_id  WHERE article_id=? `
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

// 通过纪要ID获取文章详情
func GetArticleIdInfoByArticleId(articleId int) (item *CygxArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article  WHERE article_id= ?`
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

func GetReportContentTextSub(content string) (contentSub string, err error) {
	content = html.UnescapeString(content)
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
	docText := doc.Text()
	bodyRune := []rune(docText)
	bodyRuneLen := len(bodyRune)
	if bodyRuneLen > 200 {
		bodyRuneLen = 200
	}
	body := string(bodyRune[:bodyRuneLen])
	contentSub = body
	return
}

// 修改发布状态
func PublishAndCancel(item *CygxArticle) (err error) {
	sql := `UPDATE cygx_article SET  publish_status=? ,admin_id =? ,admin_name =?  WHERE article_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.PublishStatus, item.AdminId, item.AdminName, item.ArticleId).Exec()
	return
}

// 修改发布状态
func ArticleVisibleRange(item *CygxArticle) (err error) {
	sql := `UPDATE cygx_article SET  visible_range=? ,admin_id =? ,admin_name =?  WHERE article_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.VisibleRange, item.AdminId, item.AdminName, item.ArticleId).Exec()
	return
}

// 修改发布状态
func UpdateIsClassFail(item *CygxArticleResp) (err error) {
	sql := `UPDATE cygx_article SET  is_class_fail=0  WHERE article_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.ArticleId).Exec()
	return
}

// 通过纪要ID获取文章详情
func GetArticleIdInfoBySummaryManageIdEdit(summaryManageId int) (item *CygxArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article  WHERE id=? AND source = 1`
	err = o.Raw(sql, summaryManageId).QueryRow(&item)
	return
}

// 删除数据
func DeleteSummaryManage(summaryManageId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` DELETE FROM cygx_article  WHERE id=? AND source = 1`
	_, err = o.Raw(sql, summaryManageId).Exec()
	return
}

type CygxArticleList struct {
	ArticleId       int    `description:"报告id"`
	CategoryName    string `description:"行业分类名称"`
	Title           string `description:"标题"`
	Abstract        string `description:"摘要"`
	Body            string `description:"内容"`
	PublishStatus   int    `description:"发布状态，0未发布 ，1已发布"`
	PublishDate     string `description:"发布时间"`
	LastUpdatedTime string `description:"更新时间"`
	ArticleIdMd5    string `description:"ID，md5值"`
	Pv              int    `description:"PV"`
	Uv              int    `description:"UV"`
	CommentNum      int    `description:"留言总数"`
	CollectionNum   int    `description:"收藏"`
	NickName        string `description:"作者昵称"`
	DepartmentId    int    `description:"作者ID"`
	IndustryName    string `description:"产业名称"`
	SubjectName     string `description:"标的名称"`
	ArticleTypeId   int    `description:"文章类型ID"`
	ArticleTypeName string `description:"文章类型名称"`
	VisibleRange    int    `description:"设置可见范围1全部，0内部"`
	TopTime         int    `description:"置顶时间"`
}

// 列表
func GetSummaryManageList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxArticleList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT 
		(SELECT COUNT(1) FROM cygx_article_history_record_newpv AS h   WHERE h.article_id=art.article_id AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS pv,
	   	(SELECT COUNT(DISTINCT h.user_id) FROM cygx_article_history_record_newpv AS h  WHERE h.article_id=art.article_id AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS uv,
		(SELECT COUNT(1) FROM cygx_article_comment AS k    WHERE k.article_id=art.article_id) AS comment_num,
		(SELECT COUNT(1) FROM cygx_article_collect AS c   WHERE c.article_id = art.article_id ) AS collection_num,
		(SELECT GROUP_CONCAT(DISTINCT s.subject_name  SEPARATOR '/')  FROM cygx_industrial_subject as s  WHERE s.industrial_management_id = m.industrial_management_id) AS subject_name ,
		art.title ,art.category_name ,art.publish_date ,art.id,art.last_updated_time,art.publish_status,art.abstract,art.body,art.article_id_md5 ,art.article_id,dm.nick_name , art.department_id,m.industry_name,art.article_type_id,art.article_type_name,art.visible_range,art.top_time
		FROM cygx_article as art 
		LEFT JOIN cygx_article_department as dm ON dm.department_id = art.department_id
		LEFT JOIN cygx_industrial_article_group_management as mg ON mg.article_id = art.article_id 
		LEFT JOIN cygx_industrial_management as m ON m.industrial_management_id = mg.industrial_management_id`
	if condition != "" {
		sql += condition
	}
	sql += `   LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 列表
func GetCygxArticleList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxReportArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT *
		FROM cygx_article as art WHERE  1 =1 `
	if condition != "" {
		sql += condition
	} else {
		return
	}
	sql += `   LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type CygxArticleSubjectList struct {
	ArticleId   int    `description:"报告id"`
	SubjectName string `description:"标的名称"`
}

// 文章标的列表
func GetArticleSubjectList(articleId string) (items []*CygxArticleSubjectList, err error) {
	if articleId == "" {
		articleId = "0"
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' )  AS subject_name,
			 sg.article_id
			FROM
				cygx_industrial_article_group_subject AS sg
				LEFT  JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = sg.industrial_subject_id 
			WHERE
				sg.article_id IN (` + articleId + `)
				GROUP BY sg.article_id`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取文章数量
func GetASummaryManageCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_article as art  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// body 解析
func BodyAnalysis(body string) (expertNumStr, expertContentStr, interviewDateStr, fileLink string) {
	body = html.UnescapeString(body)
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(body))
	if err != nil {
		fmt.Println("create doc err:", err.Error())
		return
	}

	var expertNumArr []string
	var expertContentArr []string
	var interviewDateArr []string
	doc.Find("p").Each(func(i int, s *goquery.Selection) {
		contentTxt := s.Text()
		if strings.Contains(contentTxt, "#访谈时间：") || strings.Contains(contentTxt, "访谈时间：") {
			interviewDate := s.Next().Text()
			interviewDateArr = append(interviewDateArr, interviewDate)
		}
		if strings.Contains(contentTxt, "#专家评价") || strings.Contains(contentTxt, "专家评价") {

			expertContent := s.Next().Text()
			//Powered 是编辑器传过来的字段
			if expertContent == "" || strings.Contains(expertContent, "Powered") {
				expertContent = contentTxt
			}
			//如果内容中最前的文字是 "专家" 这个词，则认为这句话是专家背景
			if !strings.Contains(expertContent, "专家评价") && strings.Contains(expertContent, "专家") && strings.Index(expertContent, "专家") == 0 {
				expertContentArr = append(expertContentArr, expertContent)
			}
			if expertContent != "" {
				rightIndex := strings.Index(expertContent, "）")
				if rightIndex == 0 {
					rightIndex = strings.Index(expertContent, ")")
				}
				if rightIndex > 0 {
					expertNum := expertContent[:rightIndex]
					expertNum = strings.Replace(expertNum, "（", "", -1)
					expertNum = strings.Replace(expertNum, "(", "", -1)
					expertNum = strings.Replace(expertNum, "专家评价", "", -1)
					if expertNum != "" {
						expertNumArr = append(expertNumArr, expertNum)
						rightIndex = rightIndex
						expertContentStr := expertContent[rightIndex:]
						expertContentStr = strings.Replace(expertContentStr, "）", "", -1)
						expertContentStr = strings.TrimLeft(expertContentStr, "：")
						expertContentStr = strings.TrimRight(expertContentStr, "（推荐")
						expertContentArr = append(expertContentArr, expertContentStr)
					}
				}
				if !strings.Contains(contentTxt, "（") || !strings.Contains(contentTxt, "(") {
					expertContentArr = append(expertContentArr, expertContent)
				}

			}
		}
	})
	if len(expertContentArr) == 0 {
		doc.Find("pre").Each(func(i int, s *goquery.Selection) {
			contentTxt := s.Text()
			if strings.Contains(contentTxt, "#访谈时间：") || strings.Contains(contentTxt, "访谈时间：") {
				interviewDate := s.Next().Text()
				numStar := strings.Index(contentTxt, " #访谈时间：")
				numEnd := strings.Index(contentTxt, " #纪要详情：")
				interviewDate = contentTxt[numStar+19 : numEnd]
				if interviewDate != "" {
					interviewDateArr = append(interviewDateArr, interviewDate)
				}
			}
			if strings.Contains(contentTxt, "#专家评价") || strings.Contains(contentTxt, "专家评价") {
				expertContent := s.Next().Text()
				if expertContent == "" {
					expertContent = contentTxt
				}

				if expertContent != "" {
					expertIsHave := strings.Index(expertContent, "专家评价")
					if expertIsHave > 0 {
						expertContent = expertContent[expertIsHave:]
						rightIndex := strings.Index(expertContent, "）")
						if rightIndex == 0 {
							rightIndex = strings.Index(expertContent, ")")
						}
						if rightIndex > 0 {
							expertNum := expertContent[:rightIndex]
							expertNum = strings.Replace(expertNum, "（", "", -1)
							expertNum = strings.Replace(expertNum, "(", "", -1)
							expertNum = strings.Replace(expertNum, "专家评价", "", -1)
							expertNum = strings.Replace(expertNum, "：", "", -1)
							expertNum = strings.Replace(expertNum, ":", "", -1)
							if expertNum != "" {
								expertNumArr = append(expertNumArr, expertNum)
								rightIndex = rightIndex
								expertContentStr := expertContent[rightIndex:]
								expertContentStr = strings.Replace(expertContentStr, "）", "", -1)
								expertContentStr = strings.TrimLeft(expertContentStr, "：")
								expertContentStr = strings.TrimRight(expertContentStr, "（推荐")
								if expertContentStr != "" {
									expertContentArr = append(expertContentArr, expertContentStr)
								}
							}
						}
					}
					if !strings.Contains(contentTxt, "（") || !strings.Contains(contentTxt, "(") {
						expertContentArr = append(expertContentArr, expertContent)
					}
				}
			}
		})
	}
	if len(expertNumArr) > 0 {
		expertNumStr = expertNumArr[0]
		if expertNumStr != "" {
			expertNumStr = strings.Replace(expertNumStr, "#：", "", -1)
			expertNumStr = strings.Replace(expertNumStr, "# ", "", -1)
			expertNumStr = strings.Trim(expertNumStr, "")
		}
	}

	if len(expertContentArr) > 0 {
		expertContentStr = expertContentArr[0]
	}
	if len(expertContentStr) > 600 {
		strnum := strings.Index(expertContentStr, "#专家评价：")
		content := expertContentStr[strnum:]
		strnum2 := strings.Index(content, "（")
		content = content[strnum2+9:] //中文括号3位 专家编号6位
		expertContentStr = content
	}
	if len(interviewDateArr) > 0 {
		interviewDateStr = interviewDateArr[0]
	}
	return
}

// 列表
func GetCygxArticleCollectionList(articleId int) (items []*CygxDepartmentFllowList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			f.* 
		FROM
			cygx_article_collect AS f
		WHERE
			f.article_id = ?
			GROUP BY f.id`
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

type ArticleHistoryRep struct {
	ArticleId   int    `description:"文章ID"`
	RealName    string `description:"姓名"`
	Mobile      string `description:"手机号"`
	CompanyName string `description:"公司名称"`
	SellerName  string `description:"所属销售"`
	StopTime    string `description:"阅读停留时间"`
	CreateTime  string `description:"创建时间"`
}

// 列表
func GetArticleHistoryList(articleId int, condition string) (items []*ArticleHistoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			h.*
			FROM
				cygx_article_history_record_all AS h
			WHERE
				h.article_id = ?
				AND h.platfor = 1  AND h.is_del = 0  `
	if condition != "" {
		sql = sql + condition + ` GROUP BY h.id`
	}
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 用户阅读记录，不过滤弘则内部的
func GetArticleHistoryListOld(articleId int, condition string) (items []*ArticleHistoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			h.*
			FROM
				cygx_article_history_record AS h
			WHERE
				h.article_id = ?
				AND c.product_id = 2`
	if condition != "" {
		sql = sql + condition + ` GROUP BY h.id`
	}
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 列表
func GetSellerUserMobileList(condition string) (items []*ArticleHistoryRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT mobile FROM wx_user as h WHERE h.mobile != '' ` + condition
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type ArticleTypeAndAbstract struct {
	Abstract      string
	ArticleTypeId int
}

func GetArticleTypeAndAbstract() (list []*ArticleTypeAndAbstract, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
	* 
FROM
	( SELECT abstract, article_type_id FROM cygx_article GROUP BY publish_date DESC ) AS a 
GROUP BY
	a.article_type_id `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// 更新文章置顶时间
func UpdateArticleTopTime(activityId, topTime int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` UPDATE cygx_article SET  top_time=? WHERE article_id=?`
	_, err = o.Raw(sql, topTime, activityId).Exec()
	return
}

// 添加朋友圈分享封面图片
func UpdateCygxArticleMomentsImg(momentsImg string, articleId int) (err error) {
	sql := `UPDATE cygx_article SET  moments_img=?  WHERE article_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, momentsImg, articleId).Exec()
	return
}
