package controllers

import (
	"encoding/json"
	"github.com/medivhzhan/weapp/v2"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"html"
	"strconv"
	"strings"
	"time"
)

//type HtgjController struct {
//	BaseAuthController
//}

type BaseHtgjController struct {
	BaseCommonController
}

// @Title 首页列表接口(海通国际)
// @Description 首页列表接口(海通国际)
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ChartPermissionId   query   int  true       "品类id，最新传0"
// @Param   CompanyCode     query string  false       "机构编号"
// @Param   CompanyName     query string  false       "机构名称"
// @Param   Email     query string  false       "邮箱"
// @Param   Sign   query   string  false       "加密签名"
// @Success 200 {object} models.HomeListResp
// @router /home/listPublic [get]
func (this *BaseHtgjController) ListHomePublic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	companyCode := this.GetString("CompanyCode")
	companyName := this.GetString("CompanyName")
	email := this.GetString("Email")
	sign := this.GetString("Sign")
	var userType int
	var err error
	if companyCode != "" && companyName != "" && email != "" {
		errMsg, errHt, wxUser, _ := services.CheckHtgj(companyCode, companyName, email, sign)
		if errHt != nil {
			br.Msg = "获取"
			br.ErrMsg = "获取数据失败，Err:" + errHt.Error()
			return
		}
		if errMsg != "" {
			br.Msg = errMsg
			return
		}
		user := wxUser
		if user == nil {
			br.Msg = "请登录"
			br.ErrMsg = "请登录，用户信息为空"
			br.Ret = 408
			return
		}
		userType, _, err = services.GetUserType(user.CompanyId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
			return
		}
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	var total int
	resp := new(models.HomeListResp)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.HaveResearch = true
	condition += ` AND is_summary = 1  `
	if chartPermissionId > 0 {
		categoryId, err := models.GetCategoryId(chartPermissionId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取分类权限信息失败，Err:" + err.Error()
			return
		}
		categoryinfo, err := models.GetChartPermissionById(chartPermissionId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取信息失败,Err:" + err.Error()
			return
		}
		if userType == 1 && strings.Contains(categoryinfo.PermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
			resp.HaveResearch = false
			resp.Paging = page
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = resp
			return
		}
		page = paging.GetPaging(currentIndex, pageSize, total)
		if categoryId != "" {
			condition += ` AND category_id IN(` + categoryId + `)`
			//condition += ` OR ( category_name  LIKE '%` + utils.CHART_PERMISSION_NAME_YANXUAN + `%' AND publish_status = 1 AND is_summary = 1 )`
		} else {
			condition += ` AND  category_name   LIKE '%` + utils.CHART_PERMISSION_NAME_YANXUAN + `%'`
		}

	}
	//永续客户无法查看研选分类的内容
	if userType == 1 {
		condition += ` AND  category_name  NOT LIKE '%` + utils.CHART_PERMISSION_NAME_YANXUAN + `%'`
	}
	total, err = models.GetHomeCount(condition, pars)
	if err != nil {
		br.Msg = "获取信息失败"
		br.Msg = "获取帖子总数失败，Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, total)
	list, err := models.GetHomeList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取信息失败"
		br.Msg = "获取帖子数据失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		item := list[k]
		//如果文章一开始的内容是图片，优先展示第一张图片
		imgurl, _ := services.FixArticleImgUrl(html.UnescapeString(list[k].Body))
		newBody, _ := services.GetReportContentTextSub(item.Body)
		list[k].Body = newBody
		if imgurl != "" {
			list[k].BodyHtml = imgurl
		}
		list[k].PublishDate = utils.StrTimeToTime(item.PublishDate).Format(utils.FormatDateTimeNoSecond) //时间字符串格式转时间格式
		if strings.Contains(item.CategoryName, utils.CHART_PERMISSION_NAME_YANXUAN) {
			list[k].IsResearch = true
		}
		if list[k].ArticleId < utils.SummaryArticleId {
			list[k].HttpUrl = utils.StrategyPlatform + strconv.Itoa(v.ArticleId)
			list[k].IsNeedJump = true
		}
		if item.Pv > 999 {
			list[k].Pv = 999
		}
	}
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取搜索推荐词
// @Description 获取搜索推荐词
// @Success 200 {object} models.ConfigResp
// @router /home/detail [get]
func (this *BaseHtgjController) BrowseHistoryList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	resp := new(models.ConfigResp)
	detail := new(models.CygxConfig)
	//configCode := "hot_search"
	//detail, err := models.GetConfigByCode(configCode)
	hotSearch, err := models.GetHotSearch()
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	chartList, err := models.GetChartListConfig()
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	for _, v := range chartList {
		item := new(models.KeyWord)
		item.KeyWord = v.Title
		resp.List = append(resp.List, item)
	}

	var condition string
	var pars []interface{}
	currentTime := time.Now()
	starTime := currentTime.AddDate(0, 0, -8).Format("2006-01-02") + " 00:00:00"
	endTime := currentTime.AddDate(0, 0, -1).Format("2006-01-02") + " 23:59:59"
	condition += ` AND create_time < ` + "'" + endTime + "'" + `AND create_time > ` + "'" + starTime + "'"
	hotList, err := models.GetSearchKeyWordTop(condition, pars)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	for _, v := range hotList {
		item := new(models.KeyWord)
		item.KeyWord = v.KeyWord
		resp.ListHot = append(resp.ListHot, item)
	}
	detail.ConfigValue = hotSearch
	resp.Item = detail
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 访谈申请(海通国际)
// @Description 访谈申请(海通国际)
// @Param	request	body models.ArticleInterviewApplyReqHtgj true "type json string"
// @Success 200 {object} models.FontsCollectResp
// @router /interview/apply [post]
func (this *BaseHtgjController) InterviewApply() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req models.ArticleInterviewApplyReqHtgj
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	//articleId := req.ArticleId
	companyCode := req.CompanyCode
	companyName := req.CompanyName
	wxuUserName := req.Email
	sign := req.Sign
	if companyCode == "" || companyName == "" || wxuUserName == "" || sign == "" {
		br.Msg = "上传失败"
		br.ErrMsg = "必填参数不能为空"
		return
	}
	companyNameHt := companyCode + "_" + companyName
	errMsg := services.CheckSign(companyCode+companyName+wxuUserName, sign)
	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyInfo, err := models.GetCompanyByThirdName(companyNameHt)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}
	user, err := models.GetUserByThirdName(companyInfo.CompanyId, wxuUserName)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}
	uid := user.UserId

	article, err := models.GetArticleDetailById(req.ArticleId)
	if err != nil {
		br.Msg = "获取纪要失败！"
		br.ErrMsg = "获取纪要失败，Err:" + err.Error()
		return
	}

	count, err := models.GetArticleInterviewApplyCount(uid, req.ArticleId)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := new(models.ArticleInterviewApplyResp)
	if count <= 0 {
		item := new(models.CygxInterviewApply)
		item.ArticleId = req.ArticleId
		item.UserId = uid
		item.CompanyId = user.CompanyId
		item.Status = "待邀请"
		item.Sort = 1
		item.ArticleTitle = article.Title
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		item.ArticleIdMd5 = article.ArticleIdMd5
		_, err = models.AddCygxInterviewApply(item)
		if err != nil {
			br.Msg = "申请失败"
			br.ErrMsg = "申请失败,Err:" + err.Error()
			return
		}
		br.Msg = "申请成功"
		resp.Status = 1
		//发送模板消息
		if user.CompanyId > 1 {
			mobile := user.Mobile
			if mobile == "" {
				mobile = user.Email
			}
			sellerItem, _ := models.GetSellerByCompanyId(user.CompanyId)
			if sellerItem != nil && sellerItem.AdminId > 0 && user.Mobile != "" {
				openIpItem, _ := models.GetUserRecordByMobile(4, sellerItem.Mobile)
				if openIpItem != nil && openIpItem.OpenId != "" {
					go services.SendInterviewApplyTemplateMsg(user.RealName, sellerItem.CompanyName, mobile, article.Title, openIpItem)
				}
			}
		}
	} else {
		err = models.RemoveArticleInterviewApply(uid, req.ArticleId)
		if err != nil {
			br.Msg = "取消申请失败"
			br.ErrMsg = "取消申请失败,Err:" + err.Error()
			return
		}
		br.Msg = "已取消申请"
		resp.Status = 2
		if user.CompanyId > 1 {
			mobile := user.Mobile
			if mobile == "" {
				mobile = user.Email
			}
			sellerItem, _ := models.GetSellerByCompanyId(user.CompanyId)
			if sellerItem != nil && sellerItem.AdminId > 0 && user.Mobile != "" {
				openIpItem, _ := models.GetUserRecordByMobile(4, sellerItem.Mobile)
				if openIpItem != nil && openIpItem.OpenId != "" {
					go services.SendInterviewApplyCancelTemplateMsg(user.RealName, sellerItem.CompanyName, mobile, article.Title, openIpItem)
				}
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 收藏(海通国际)
// @Description 收藏(海通国际)
// @Param	request	body models.ArticleInterviewApplyReqHtgj true "type json string"
// @Success 200 {object} models.FontsCollectResp
// @router /collect [post]
func (this *BaseHtgjController) ArticleCollect() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.ArticleInterviewApplyReqHtgj
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	companyCode := req.CompanyCode
	companyName := req.CompanyName
	wxuUserName := req.Email
	sign := req.Sign
	if companyCode == "" || companyName == "" || wxuUserName == "" || sign == "" {
		br.Msg = "上传失败"
		br.ErrMsg = "必填参数不能为空"
		return
	}
	companyNameHt := companyCode + "_" + companyName
	errMsg := services.CheckSign(companyCode+companyName+wxuUserName, sign)
	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyInfo, err := models.GetCompanyByThirdName(companyNameHt)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}
	wxuser, err := models.GetUserByThirdName(companyInfo.CompanyId, wxuUserName)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}
	uid := wxuser.UserId
	user := new(models.WxUserItem)
	user.Mobile = wxuser.Mobile
	user.Email = wxuser.Email
	user.CompanyId = wxuser.CompanyId
	user.RealName = wxuser.RealName
	user.CompanyName = companyInfo.CompanyName
	detail, err := models.GetArticleDetailById(articleId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	count, err := models.GetArticleCollectCount(uid, articleId)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := new(models.ArticleCollectResp)
	if count <= 0 {
		item := new(models.CygxArticleCollect)
		item.ArticleId = req.ArticleId
		item.UserId = uid
		item.CreateTime = time.Now()
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.RealName = user.RealName
		_, err = models.AddCygxArticleCollect(item)
		if err != nil {
			br.Msg = "收藏失败"
			br.ErrMsg = "收藏失败,Err:" + err.Error()
			return
		}
		br.Msg = "收藏成功"
		resp.Status = 1
		// 文章收藏消息发送
		go services.ArticleUserRemind(user, detail, 2)
	} else {
		err = models.RemoveArticleCollect(uid, articleId)
		if err != nil {
			br.Msg = "取消收藏失败"
			br.ErrMsg = "取消收藏失败,Err:" + err.Error()
			return
		}
		br.Msg = "已取消收藏"
		resp.Status = 2
	}
	collectTotal, err := models.GetArticleCollectUsersCount(articleId)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp.CollectCount = collectTotal
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 文章带问(海通国际)
// @Description 新增文章带问接口(海通国际)
// @Param	request	body models.ArticleAskReqHtgj true "type json string"
// @Success Ret=200 新增成功
// @router /askAdd [post]
func (this *BaseHtgjController) AskAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.ArticleAskReqHtgj
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	companyCode := req.CompanyCode
	companyName := req.CompanyName
	wxuUserName := req.Email
	content := req.Content
	sign := req.Sign
	if companyCode == "" || companyName == "" || wxuUserName == "" || sign == "" {
		br.Msg = "上传失败"
		br.ErrMsg = "必填参数不能为空"
		return
	}
	companyNameHt := companyCode + "_" + companyName
	errMsg := services.CheckSign(companyCode+companyName+wxuUserName, sign)
	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyInfo, err := models.GetCompanyByThirdName(companyNameHt)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}
	wxuser, err := models.GetUserByThirdName(companyInfo.CompanyId, wxuUserName)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}

	user := new(models.WxUserItem)
	user.Mobile = wxuser.Mobile
	user.Email = wxuser.Email
	user.CompanyId = wxuser.CompanyId
	user.RealName = wxuser.RealName
	user.CompanyName = companyInfo.CompanyName

	itemToken, err := services.WxGetToken()
	if err != nil {
		br.Msg = "GetWxAccessToken Err:" + err.Error()
		return
	}
	if itemToken.AccessToken == "" {
		br.Msg = "accessToken is empty"
		return
	}
	commerr, err := weapp.MSGSecCheck(itemToken.AccessToken, content)
	if err != nil {
		br.Msg = "内容校验失败！"
		br.ErrMsg = "内容校验失败，Err:" + err.Error()

		return
	}
	if commerr.ErrCode != 0 {
		br.Msg = "内容违规,请重新提交！"
		br.ErrMsg = "颜文字内容违规，Err:" + commerr.ErrMSG
		return
	}
	count, _ := models.GetArticleCountById(articleId)
	if count == 0 {
		br.Msg = "操作失败"
		br.ErrMsg = "文章ID错误,不存在 articleId：" + strconv.Itoa(articleId)
		return
	}
	companyDetail, err := models.GetCompanyDetailById(user.CompanyId)
	if err != nil {
		br.Msg = "提交失败！"
		br.ErrMsg = "获取客户详情失败，Err:" + err.Error()
		return
	}
	if companyDetail == nil {
		br.Msg = "提交失败！"
		br.ErrMsg = "客户不存在，uid:" + strconv.Itoa(user.UserId)
		return
	}
	item := new(models.CygxArticleAsk)
	item.UserId = user.UserId
	item.ArticleId = req.ArticleId
	item.CompanyId = user.CompanyId
	item.CompanyName = companyDetail.CompanyName
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.Content = content
	_, err = models.AddArticleAsk(item)
	if err != nil {
		br.Msg = "提交失败"
		br.ErrMsg = "提交失败,Err:" + err.Error()
		return
	}
	companyItem, err := models.GetSellerDetailAllByCompanyId(user.CompanyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取所属销售信息失败,Err:" + err.Error()
		return
	}
	var mobile string
	if utils.RunMode == "release" {
		//mobile = utils.WxMsgTemplateIdAskMsgMobileAll + "," + companyItem.Mobile
		mobile = utils.WxMsgTemplateIdAskMsgMobileAll
	} else {
		mobile = utils.WxMsgTemplateIdAskMsgMobile
	}
	openIdList, err := models.GetWxOpenIdByMobileList(mobile)
	if err != nil {
		br.Msg = "提交失败"
		br.ErrMsg = "提交失败,Err:" + err.Error()
		return
	}
	detail, err := models.GetArticleDetailById(articleId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	companyName = user.CompanyName + "-" + user.RealName + "（" + companyItem.SellerName + "）"
	go services.SendWxMsgWithAsk(companyName, time.Now().Format(utils.FormatDateTime), content, detail.Title, openIdList, req.ArticleId)
	br.Ret = 200
	br.Success = true
	br.Msg = "提交成功"
}

// @Title 获取所有品种（无需token）
// @Description 获取所有品种（无需token）
// @Success 200 {object} models.ChartPermissionResp
// @router /permission/allPublic [get]
func (this *BaseHtgjController) PermissionPublic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var condition string
	list, err := models.GetChartPermissionAll(condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp := new(models.ChartPermissionResp)
	for k, v := range list {
		resp.List = append(resp.List, v)
		if services.GetShowSustainable() && v.PermissionName == "研选" {
			resp.List[k].IsShowSustainable = true
		}
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 上传文章阅读时间（无需token）
// @Description 上传文章阅读时间接口（无需token）
// @Param  request	body models.AddStopTimeHtgjRep true "type json string"
// @Success 200 {object} models.ArticleDetailResp
// @router /article/addStopTimePublic [post]
func (this *BaseHtgjController) AddStopTimePublic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req models.AddStopTimeHtgjRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	stopTime := req.StopTime
	outType := req.OutType
	source := req.Source
	companyCode := req.CompanyCode
	companyName := req.CompanyName
	wxuUserName := req.Email
	sign := req.Sign
	if companyCode == "" || companyName == "" || wxuUserName == "" || sign == "" {
		br.Msg = "上传失败"
		br.ErrMsg = "必填参数不能为空"
		return
	}
	companyNameHt := companyCode + "_" + companyName
	errMsg := services.CheckSign(companyCode+companyName+wxuUserName, sign)
	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyInfo, err := models.GetCompanyByThirdName(companyNameHt)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}
	user, err := models.GetUserByThirdName(companyInfo.CompanyId, wxuUserName)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}
	uid := user.UserId
	if articleId <= 0 {
		br.Msg = "文章ID不存在"
		br.ErrMsg = "参数错误"
		return
	}
	if stopTime == 0 {
		stopTime = 1
	}
	if outType != 2 {
		outType = 1
	}
	if source != "PC" {
		source = "MOBILE"
	}
	detail := new(models.ArticleDetail)
	hasPermission := 0
	hasFree := 0
	//判断是否已经申请过
	applyCount, err := models.GetApplyRecordCount(uid)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "判断是否已申请过试用失败，Err:" + err.Error()
		return
	}
	//`description:"1:有该行业权限,正常展示，2：无该行业权限，不存在权益客户下，3:无该品类权限，4：潜在客户，未提交过申请，5：潜在客户,已提交过申请"`
	if user.CompanyId > 1 {
		companyPermission, err := models.GetCompanyPermission(user.CompanyId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请访谈失败，Err:" + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		detail, err = models.GetArticleDetailById(articleId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取文章信息失败,Err:" + err.Error() + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if companyPermission == "" {
			if applyCount > 0 {
				hasPermission = 5
			} else {
				hasPermission = 2
			}
			hasFree = 2
			goto Loop
		} else {
			hasFree = 1
			var articlePermissionPermissionName string
			if detail.CategoryId > 0 {
				articlePermission, err := models.GetArticlePermission(detail.CategoryId)
				if err != nil {
					br.Msg = "获取信息失败"
					br.ErrMsg = "获取报告权限失败，Err:" + err.Error() + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
					return
				}
				if articlePermission == nil {
					br.Msg = "获取信息失败"
					br.ErrMsg = "报告权限不存在，Err:" + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
					return
				}
				articlePermissionPermissionName = articlePermission.PermissionName
			} else {
				articlePermissionPermissionName = detail.CategoryName
			}
			var hasPersion bool
			slice := strings.Split(articlePermissionPermissionName, ",")
			for _, v := range slice {
				if strings.Contains(companyPermission, v) {
					hasPersion = true
				}
			}
			if hasPersion {
				detailNew, err := models.GetNewArticleHistoryRecord(uid, articleId)
				if err == nil {
					hasPermission = 1
					historyRecord := new(models.AddStopTimeNewRep)
					historyRecord.StopTime = detailNew.StopTime + stopTime
					historyRecord.Id = detailNew.Id
					historyRecord.OutType = outType
					go models.UpdateArticleStopTime(historyRecord)
				}

				//不统计本公司的阅读记录、正常退出的不做时间差统计
				if user.CompanyId != 16 && stopTime > 3 {
					key := "CYGX_ARTICLE_PV" + strconv.Itoa(articleId) + "_" + strconv.Itoa(uid) + "_" + strconv.Itoa(user.CompanyId) + "_" + strconv.Itoa(outType)
					record := new(models.CygxArticleHistoryRecordNewpv)
					record.UserId = uid
					record.ArticleId = articleId
					record.CreateTime = time.Now().Add(-time.Second * time.Duration(stopTime))
					record.ModifyTime = time.Now()
					record.Mobile = user.Mobile
					record.Email = user.Email
					record.CompanyId = user.CompanyId
					record.CompanyName = companyInfo.CompanyName
					record.StopTime = stopTime
					record.OutType = outType
					record.Source = source
					if !utils.Rc.IsExist(key) || outType != 2 {
						//新增浏览记录
						go models.AddCygxArticleViewRecordNewpv(record)
						recordRedis := new(services.ReportViewRecord)
						recordRedis.UserId = user.UserId
						recordRedis.ReportId = articleId
						recordRedis.Mobile = user.Mobile
						recordRedis.Email = user.Email
						recordRedis.RealName = user.RealName
						recordRedis.CompanyName = companyName
						//recordRedis.CreateTime = time.Now().Add(-time.Second * time.Duration(stopTime))
						go services.PushViewRecordNewRedisData(recordRedis, user.CompanyId)
					} else {
						go models.UpdateCygxArticleViewRecordNewpv(record, stopTime)
					}
					utils.Rc.Put(key, 1, 10*time.Minute)
				}

				models.ModifyReportLastViewTime(uid)
			} else { //无该行业权限
				hasPermission = 3
			}
		}
	} else { //潜在客户
		if applyCount > 0 {
			hasPermission = 5
		} else {
			hasPermission = 4
		}
	}
Loop:
	resp := new(models.ArticleDetailAddStopTimeRep)
	resp.HasPermission = hasPermission
	resp.HasFree = hasFree
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = resp
}

// @Title 获取报告详情（无需token）
// @Description 获取报告详情接口
// @Param   ArticleId   query   int  true       "报告ID"
// @Param   CompanyCode     query string  false       "机构编号"
// @Param   CompanyName     query string  false       "机构名称"
// @Param   Email     query string  false       "邮箱"
// @Param   Sign   query   string  false       "加密签名"
// @Success 200 {object} models.ArticleDetailHtgjResp
// @router /detailPublic [get]
func (this *BaseHtgjController) DetailPublic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	articleId, _ := this.GetInt("ArticleId")
	companyCode := this.GetString("CompanyCode")
	companyNameHt := this.GetString("CompanyName")
	email := this.GetString("Email")
	sign := this.GetString("Sign")
	resp := new(models.ArticleDetailHtgjResp)
	if companyCode == "" || email == "" {
		resp.HasPermission = 2
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	if articleId <= 0 {
		br.Msg = "文章不存在"
		br.ErrMsg = "文章不存在，文章ID错误"
		return
	}

	errMsg, err, wxUser, companyName := services.CheckHtgj(companyCode, companyNameHt, email, sign)

	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyPermission, err := models.GetCompanyPermission(wxUser.CompanyId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户权限失败，Err:" + err.Error() + ";articleId" + strconv.Itoa(articleId)
		return
	}
	hasPermission := 0
	uid := wxUser.UserId
	detail, err := models.GetArticleDetailById(articleId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	detail.Body = html.UnescapeString(detail.Body)
	detail.Body = strings.Replace(detail.Body, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;\">Powered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)
	detail.Body = strings.Replace(detail.Body, "pre", "div", -1)
	detail.Abstract, _ = services.GetReportContentTextSub(detail.Abstract)

	var articlePermissionPermissionName string
	if detail.CategoryId > 0 {
		articlePermission, err := models.GetArticlePermission(detail.CategoryId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取报告权限失败，Err:" + err.Error() + strconv.Itoa(wxUser.UserId) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if articlePermission == nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "报告权限不存在，Err:" + strconv.Itoa(wxUser.UserId) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		articlePermissionPermissionName = articlePermission.PermissionName
	} else {
		articlePermissionPermissionName = detail.CategoryName
	}
	var hasPersion bool
	slice := strings.Split(articlePermissionPermissionName, ",")
	for _, v := range slice {
		if strings.Contains(companyPermission, v) {
			hasPersion = true
		}
	}
	if hasPersion {
		hasPermission = 1
	}
	if strings.Contains(detail.CategoryName, "研选") {
		detail.IsResearch = true
	}

	resp.HasPermission = hasPermission
	if hasPermission == 1 {
		//获取销售手机号
		sellerItem, err := models.GetSellerByCompanyId(wxUser.CompanyId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取销售数据失败2，Err:" + strconv.Itoa(wxUser.UserId) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if sellerItem != nil {
			detail.SellerMobile = sellerItem.Mobile
			detail.SellerName = sellerItem.RealName
		}
		sellerList, err := models.GetSellerList(articleId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取销售数据失败，Err:" + err.Error() + strconv.Itoa(wxUser.UserId) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if detail.ArticleId >= utils.SummaryArticleId && strings.Contains(detail.SellerAndMobile, "-") {
			strnum := strings.Index(detail.SellerAndMobile, "-")
			detail.SellerAndMobile = detail.SellerAndMobile[0:strnum]
			if strnum > 0 {
				nickName := detail.SellerAndMobile[0:strnum]
				sellerAndMobile := &models.SellerRep{
					SellerMobile: "",
					SellerName:   nickName,
				}
				sellerList = append(sellerList, sellerAndMobile)
			}
		}
		detail.SellerList = sellerList

		historyRecord := new(models.CygxArticleHistoryRecord)
		historyRecord.UserId = wxUser.UserId
		historyRecord.ArticleId = articleId
		historyRecord.CreateTime = time.Now()
		historyRecord.Mobile = wxUser.Mobile
		historyRecord.Email = wxUser.Email
		historyRecord.CompanyId = wxUser.CompanyId
		historyRecord.CompanyName = companyName
		recordCount, _ := models.GetNoAddStoptimeArticleCount(wxUser.UserId, articleId)
		if recordCount == 0 {
			go models.AddCygxArticleHistoryRecord(historyRecord)
		} else {
			detailNew, err := models.GetNewArticleHistoryRecord(wxUser.UserId, articleId)
			if err != nil {
				br.Msg = "获取信息失败"
				br.ErrMsg = "获取信息失败,Err:" + err.Error()
				return
			}
			if detailNew.StopTime > 0 {
				go models.AddCygxArticleHistoryRecord(historyRecord)
			}
		}
		key := "CYGX_ARTICLE_" + strconv.Itoa(articleId) + "_" + strconv.Itoa(wxUser.UserId)
		if !utils.Rc.IsExist(key) {
			//新增浏览记录
			record := new(models.CygxArticleViewRecord)
			record.UserId = wxUser.UserId
			record.ArticleId = articleId
			record.CreateTime = time.Now()
			record.Mobile = wxUser.Mobile
			record.Email = wxUser.Email
			record.CompanyId = wxUser.CompanyId
			record.CompanyName = companyName
			go models.AddCygxArticleViewRecord(record)
			utils.Rc.Put(key, 1, 5*time.Second)
			models.ModifyReportLastViewTime(wxUser.UserId)
		}
		if detail.ArticleId < utils.SummaryArticleId {
			chartUserTokenByMobile, _ := services.GetUserTokenByMobile(utils.HtgjPublicMobile)
			detail.HttpUrl = utils.StrategyPlatform + strconv.Itoa(articleId) + "?token=" + chartUserTokenByMobile
			detail.IsNeedJump = true
		}
		collectCount, err := models.GetArticleCollectCount(uid, articleId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已收藏失败，Err:" + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if collectCount > 0 {
			detail.IsCollect = true
		}
		interviewApplyItem, err := models.GetArticleInterviewApply(uid, articleId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请访谈失败，Err:" + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if interviewApplyItem != nil && interviewApplyItem.InterviewApplyId > 0 {
			detail.IsInterviewApply = true
			detail.InterviewApplyStatus = interviewApplyItem.Status
		}
		articleFollowdetail, err := models.GetArticleFollowDetail(articleId, uid)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取关注信息失败，Err:" + err.Error()
			return
		}
		detail.FollowNum = articleFollowdetail.DNum
		detail.CollectionNum = articleFollowdetail.AcNum
		resp.Detail = detail
		resp.Detail = detail
	}
	resp.CompanyName = companyName
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 页面访问统计（无需token）
// @Description 上传页面访问统计（无需token）
// @Param	request	body models.CygxPageHistoryRecordHtgjRep true "type json string"
// @Success Ret=200 新增成功
// @router /pageHistoryPublic [post]
func (this *BaseHtgjController) PageHistoryPublic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req models.CygxPageHistoryRecordHtgjRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	companyCode := req.CompanyCode
	companyName := req.CompanyName
	wxuUserName := req.Email
	sign := req.Sign
	if companyCode == "" || companyName == "" || wxuUserName == "" || sign == "" {
		br.Msg = "上传失败"
		br.ErrMsg = "必填参数不能为空"
		return
	}
	companyNameHt := companyCode + "_" + companyName
	errMsg := services.CheckSign(companyCode+companyName+wxuUserName, sign)
	if errMsg != "" {
		br.Msg = errMsg
		return
	}
	companyInfo, err := models.GetCompanyByThirdName(companyNameHt)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败，Err:" + err.Error()
		return
	}
	user, err := models.GetUserByThirdName(companyInfo.CompanyId, wxuUserName)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}
	item := new(models.CygxPageHistoryRecord)
	item.UserId = user.UserId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = companyName
	item.DetailId = req.DetailId
	item.ChartPermissionId = req.ChartPermissionId
	item.IndustrialManagementId = req.IndustrialManagementId
	item.PageType = "ArticleCopy"
	_, err = models.AddCygxPageHistoryRecord(item)
	if err != nil {
		br.Msg = "记录信息失败"
		br.ErrMsg = "新增访问记录失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}
