package controllers

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

// 策略
type TacticsController struct {
	BaseAuthController
}

type TacticsCommonController struct {
	BaseCommonController
}

// @Title 策略、行业列表接口
// @Description 获取策略、行业 通用列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   CategoryId   query   int  true       "分类ID"
// @Success 200 {object} models.TacticsListResp
// @router /list [get]
func (this *TacticsController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	//uid := user.UserId
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	categoryId, _ := this.GetInt("CategoryId")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	//var condition string
	//var listTacticsSrt string
	//var pars []interface{}
	//var total int
	resp := new(models.TacticsListResp)
	list := make([]*models.ReportArticle, 0)
	var total int
	var err error
	if categoryId == utils.ACTEGORY_ID_AI_QY {
		list, total, err = services.GetAiQianYanArtilceList(startSize, pageSize)
	} else {
		list, total, err = models.GetReportAndproductIndustrylList(categoryId, startSize, pageSize)
	}
	if err != nil {
		br.Msg = "获取信息失败"
		br.Msg = "获取帖子数据失败，Err:" + err.Error()
		return
	}
	var articleIds []int
	var productInteriorIs []int
	page := paging.GetPaging(currentIndex, pageSize, total)
	for _, v := range list {

		if v.Resource == 1 {
			articleIds = append(articleIds, v.ArticleId)
		} else {
			productInteriorIs = append(productInteriorIs, v.ArticleId)
		}
	}
	ArticleHistoryMap := services.GetArticleHistoryByUser(articleIds, user)
	ProductInteriorHistoryMap := services.GetCygxProductInteriorHistoryListMap(productInteriorIs, user)
	productInteriorMapPv := services.GetCygxProductInteriorHistoryListPvMap(productInteriorIs) //产品内测Pv
	for k, v := range list {
		if v.Resource == 1 {
			if ArticleHistoryMap[v.ArticleId] == 0 && user.CreatedTime.Before(utils.StrTimeToTime(v.PublishDate)) && utils.StrTimeToTime(utils.OnlineTime).Before(utils.StrTimeToTime(v.PublishDate)) {
				list[k].IsRed = true
			}
		} else {
			if ProductInteriorHistoryMap[v.ArticleId] == 0 && user.CreatedTime.Before(utils.StrTimeToTime(v.PublishDate)) && utils.StrTimeToTime(utils.OnlineTime).Before(utils.StrTimeToTime(v.PublishDate)) {
				list[k].IsRed = true
			}
		}
		list[k].Abstract, _ = services.GetReportContentTextSub(v.Abstract)
	}
	if categoryId > 0 {
		detail, errCategory := models.GetCygxReportMappingCygxByCategoryId(categoryId)
		if errCategory != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取信息失败,Err:" + errCategory.Error() + "categoryID 不存在：" + strconv.Itoa(categoryId)
			return
		}
		resp.MatchTypeName = detail.MatchTypeName
		if detail.MatchTypeName == "热点问答" || detail.ChartPermissionName == utils.ZHOU_QI_NAME || detail.ChartPermissionName == utils.GU_SHOU_NAME {
			resp.IsShowAbstract = true
		}
	}

	articleMapPv := services.GetArticleHistoryByArticleId(articleIds)                       //文章Pv
	articleCollectMap, _ := services.GetCygxArticleCollectMap(user.UserId)                  //用户收藏的文章
	articleCollectNumMap, _ := services.GetCygxArticleCollectNumMapByArtcileIds(articleIds) //文章收藏的数量

	for _, v := range list {
		if v.Resource == 1 {
			v.Pv = articleMapPv[v.ArticleId]
			v.IsCollect = articleCollectMap[v.ArticleId]
			v.CollectNum = articleCollectNumMap[v.ArticleId]
		}
		if v.Resource == 2 {
			v.PublishDate = utils.TimeRemoveHms2(v.PublishDate)
			v.Pv = productInteriorMapPv[v.ArticleId]
		}
		if v.ReportId > 0 {
			v.Resource = 3
		}
		if v.Abstract != "" {
			v.IsShowAbstract = true
		}
	}
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取报告详情
// @Description 获取报告详情接口
// @Param   ArticleId   query   int  true       "报告ID"
// @Success 200 {object} models.ArticleDetailResp
// @router /detail [get]
func (this *TacticsController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	uid := user.UserId
	articleId, err := this.GetInt("ArticleId")
	if articleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误"
		return
	}
	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
	}
	fmt.Println(user.CompanyId)
	//`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()
			return
		}
		fmt.Println(detail.Department)

		detail.Body = html.UnescapeString(detail.Body)
		//detail.Abstract = html.UnescapeString(detail.Abstract)
		detail.Abstract, _ = services.GetReportContentTextSub(detail.Abstract)
		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
			}
			if strings.Contains(companyPermission, articlePermissionPermissionName) {
				hasPermission = 1
				historyRecord := new(models.CygxArticleHistoryRecord)
				historyRecord.UserId = uid
				historyRecord.ArticleId = articleId
				historyRecord.CreateTime = time.Now()
				historyRecord.Mobile = user.Mobile
				historyRecord.Email = user.Email
				historyRecord.CompanyId = user.CompanyId
				historyRecord.CompanyName = user.CompanyName
				recordCount, _ := models.GetNoAddStoptimeArticleCount(uid, articleId)
				if recordCount == 0 {
					go models.AddCygxArticleHistoryRecord(historyRecord)
				} else {
					detailNew, err := models.GetNewArticleHistoryRecord(uid, articleId)
					if err != nil {
						br.Msg = "获取信息失败"
						br.ErrMsg = "获取信息失败,Err:" + err.Error()
						return
					}
					if detailNew.StopTime > 0 {
						go models.AddCygxArticleHistoryRecord(historyRecord)
					}
				}
			} else { //无该行业权限
				hasPermission = 3
			}

		}
		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:" + err.Error() + strconv.Itoa(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}

		if interviewApplyItem != nil && interviewApplyItem.InterviewApplyId > 0 {
			detail.IsInterviewApply = true
			detail.InterviewApplyStatus = interviewApplyItem.Status
		}
		//获取销售手机号
		sellerItem, err := models.GetSellerByCompanyId(user.CompanyId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取销售数据失败，Err:" + err.Error() + strconv.Itoa(uid) + ";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(uid) + ";articleId" + strconv.Itoa(articleId)
			return
		}
		if detail.ArticleId > 1000000 {
			var hrefRegexp = regexp.MustCompile("[0-9]\\d*")
			match := hrefRegexp.FindAllString(detail.SellerAndMobile, -1)
			if match != nil {
				for _, v := range match {
					sellerAndMobile := &models.SellerRep{
						SellerMobile: v,
						SellerName:   strings.Replace(detail.SellerAndMobile, v, "", -1),
					}
					sellerList = append(sellerList, sellerAndMobile)
				}
			}
		}
		detail.SellerList = sellerList
	} else { //潜在客户
		if applyCount > 0 {
			hasPermission = 5
		} else {
			hasPermission = 4
		}
	}
Loop:
	if hasPermission != 1 {
		detail.Body = ""
		detail.BodyText = ""
	}
	resp := new(models.ArticleDetailResp)
	resp.HasPermission = hasPermission
	resp.HasFree = hasFree
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 时间线列表
// @Description 时间线列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.GetCygxTacticsTimeLineResp
// @router /tacticsTimeLine/list [get]
func (this *TacticsController) TacticsTimeLineList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(models.GetCygxTacticsTimeLineResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	condition += ` AND art.status = 1 `
	total, err := models.GetCygxTacticsTimeLineCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.publish_time DESC , art.time_line_id DESC "
	list, err := models.GetCygxTacticsTimeLineList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for _, v := range list {
		v.PublishTime = utils.TimeRemoveHms2(v.PublishTime)
		v.Resource = 1
		v.Content = services.AnnotationHtml(v.Content)
	}
	if len(list) == 0 {
		list = make([]*models.CygxTacticsTimeLineResp, 0)
	}
	cf, err := models.GetConfigByCode(utils.CYGX_TACTICS_TIME_LINE_STATUS)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//如果不是弘则用户，并且设置了内部可见，那么数据就隐藏
	if user.CompanyId != utils.HZ_COMPANY_ID && cf.ConfigValue != "1" {
		list = make([]*models.CygxTacticsTimeLineResp, 0)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 时间线列表
// @Description 时间线列表接口
// @Param	request	body models.TacticsTimeLineTimeLineIdReq true "type json string"
// @Success Ret=200 新增成功
// @router /tacticsTimeLine/history [post]
func (this *TacticsController) History() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req models.TacticsTimeLineTimeLineIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	timeLineId := req.TimeLineId
	if timeLineId == 0 {
		br.Msg = "时间线ID错误"
		return
	}
	var sellerName string
	sellerName, err = models.GetCompanySellerName(user.CompanyId)
	if err != nil {
		br.Msg = "报名失败！"
		br.ErrMsg = "获取对应销售失败，Err:" + err.Error()
		return
	}
	item := models.CygxTacticsTimeLineHistory{
		TimeLineId:  timeLineId,
		UserId:      user.UserId,
		Mobile:      user.Mobile,
		Email:       user.Email,
		CompanyId:   user.CompanyId,
		CompanyName: user.CompanyName,
		RealName:    user.RealName,
		SellerName:  sellerName,
		CreateTime:  time.Now(),
		ModifyTime:  time.Now(),
	}
	err = models.AddCygxTacticsTimeLineHistory(&item)
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
