package cygx

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"html"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 报告管理
type ReportArticleController struct {
	controllers.BaseAuthController
}

// @Title 主题列表
// @Description 获取主题列表接口
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Success 200 {object} cygx.CygxReportMappingListRep
// @router /reportMappingist/list [get]
func (this *ReportArticleController) CygxReportMappingist() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	if chartPermissionId < 1 {
		br.Msg = "请输入分类ID"
		return
	}
	list, err := cygx.CygxReportMappingist(chartPermissionId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxReportMappingListRep)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报告匹配类型列表
// @Description 获取报告匹配类型列表接口
// @Success 200 {object} cygx.CygxReportMappingMatchTypeRep
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @router /reportMappingMatchTypeRep/list [get]
func (this *ReportArticleController) CygxReportMappingMatchTypeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	var condition string
	var pars []interface{}
	if chartPermissionId > 0 {
		condition += ` AND chart_permission_id  = ?  `
		pars = append(pars, chartPermissionId)
	}
	list, err := cygx.GetCygxReportMappingCygxList(condition, pars, 0, 0)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxCygxReportMappingCygxResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报告列表
// @Description 报告列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   IsFilter   query   int  true       "是否过滤 ，1是，0否，不传默认为0"
// @Param   IsClass   query   int  true       "是否归类 ，1是，0否 ，不传默认为0"
// @Param   ChartPermissionId   query   int  true     "行业ID --> 一级分类列表中 ChartPermissionId"
// @Param   SubCategoryName   query   string  true     "主题"
// @Param   MatchTypeName   query   string  true     "报告匹配类型"
// @Param   IndustrialManagementId   int   string  true     "产业ID"
// @Param   StartDate   query   string  true       "开始时间用0 补齐，列如2021-03-06 08:09:01"
// @Param   EndDate   query   string  true       "结束时间用0 补齐，列如2021-03-06 08:09:01"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   KeyWordStock   query   string  true       "搜索关键词.个股标签，关联标的部分"
// @Success 200 {object} cygx.GetReportArticleListRep
// @router /reportArticle/list [get]
func (this *ReportArticleController) ReportArticleList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	isFilter, _ := this.GetInt("IsFilter")
	isClass, _ := this.GetInt("IsClass")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	subCategoryName := this.GetString("SubCategoryName")
	matchTypeName := this.GetString("MatchTypeName")
	industrialManagementId, _ := this.GetInt("IndustrialManagementId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	keyWord := this.GetString("KeyWord")
	keyWordStock := this.GetString("KeyWordStock")
	reportLabel := this.GetString("ReportLabel") // 查研观向7.4-报告标签
	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{}

	listPermission, errper := cygx.GetPermissionMappingCategoryID()
	if errper != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errper.Error()
		return
	}
	condition += ` AND art.is_report = 1 AND re.id !=28 `
	if isClass == 0 {
		condition += ` AND art.is_class = 0  `
	} else {
		condition += ` AND art.is_class = 1 `
		if industrialManagementId > 0 {
			condition += ` AND man.industrial_management_id  =  ` + strconv.Itoa(industrialManagementId)
		}
	}
	if keyWord != "" {
		condition += ` AND (art.title LIKE '%` + keyWord + `%' )  `
	}
	//个股标签跟标的的搜索
	if keyWordStock != "" {
		condition += ` AND (art.stock LIKE '%` + keyWordStock + `%' OR art.article_id IN (SELECT article_id FROM cygx_industrial_article_group_subject WHERE industrial_subject_id IN (SELECT industrial_subject_id FROM cygx_industrial_subject WHERE subject_name LIKE '%` + keyWordStock + `%')) )  `
	}
	if isFilter == 0 {
		condition += ` AND art.is_filter = 0 `
	} else {
		condition += ` AND art.is_filter = 1 `
	}
	//行业
	if chartPermissionId > 0 {
		condition += ` AND re.chart_permission_id  =  ` + strconv.Itoa(chartPermissionId)
	}
	//主题
	if subCategoryName != "" {
		condition += ` AND art.sub_category_name  =  ` + "'" + subCategoryName + "' "
	}
	//发布时间
	if startDate != "" {
		condition += ` AND art.publish_date >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND art.publish_date <= ` + "'" + endDate + " 23:59:59'"
	}
	//报告匹配类型
	if matchTypeName != "" && chartPermissionId > 0 {
		//condition += ` AND re.match_type_name  =  ` + "'" + matchTypeName + "' "
		//mappingCygxDetai, err := cygx.GetCygxReportMappingCygxDetailByNameAndChartPermissionId(matchTypeName, chartPermissionId)
		//if err != nil && err.Error() != utils.ErrNoRow() {
		//	br.Msg = "获取失败"
		//	br.ErrMsg = "获取失败，Err:" + err.Error()
		//	return
		//}
		//if mappingCygxDetai == nil {
		//	resp := new(cygx.GetReportArticleListRep)
		//	resp.List = make([]*cygx.CygxReportArticle, 0)
		//	page := paging.GetPaging(currentIndex, pageSize, 0)
		//	resp.Paging = page
		//	br.Ret = 200
		//	br.Success = true
		//	br.Msg = "获取成功"
		//	br.Data = resp
		//	return
		//}
		//这里量不大，走一下子查询
		//condition += ` 	AND art.category_id IN ( SELECT category_id_celue FROM cygx_report_mapping_group WHERE id_cygx = ` + strconv.Itoa(mappingCygxDetai.Id) + ` )  `
		condition += ` 	AND art.category_id IN ( SELECT category_id FROM cygx_report_mapping WHERE match_type_name = ` + "'" + matchTypeName + "'" + ` )  `
	}
	// 报告标签
	if reportLabel != "" {
		keywords := "%" + reportLabel + "%"
		// 查询包含关键词的产业/标的所关联的报告IDs
		artIds, e := cygx.GetArticleIdsFromIndustryAndSubjectGroupByKeyword(keywords)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "产业/标的关键词获取文章IDs失败, Err:" + e.Error()
			return
		}
		if len(artIds) > 0 {
			condition += ` AND art.article_id IN (` + utils.GetOrmInReplace(len(artIds)) + `)`
			pars = append(pars, artIds)
		}
	}
	total, err := cygx.GetReportArticleCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += `	GROUP BY art.article_id  ORDER BY art.publish_date DESC `
	//fmt.Println(condition)
	list, err := cygx.GetReportArticleList(condition, pars, startSize, pageSize, isClass)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	reportMap := make(map[int]string)
	listMap, err := cygx.GetReportMapping()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取映射分类失败，Err:" + err.Error()
		return
	}
	for _, v := range listMap {
		reportMap[v.CategoryId] = v.MatchTypeName
	}
	var articleIds string
	for k, v := range list {
		var isShowButton bool
		if sysUser.RoleTypeCode == "rai_admin" || sysUser.RoleTypeCode == "rai_researcher" || sysUser.RoleTypeCode == "admin" {
			isShowButton = true
		} else {
			isShowButton = false
		}
		list[k].MatchTypeName = reportMap[v.CategoryId]
		list[k].ShowButton = true
		for _, vper := range listPermission {
			if v.CategoryId == vper.CategoryId {
				isShowButton = false
			}
			list[k].ShowButton = isShowButton
		}
		articleIds += strconv.Itoa(v.ArticleId) + ","
	}
	mapCommment := make(map[int]int)
	if articleIds != "" {
		articleIds = strings.TrimRight(articleIds, ",")
		condition = `	AND  art.article_id IN (` + articleIds + `)`
		listPv, err := cygx.GetReportArticleListPvUv(condition)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取PV,Uv 失败，Err:" + err.Error()
			return
		}

		var condition string
		var pars []interface{}
		condition = `	AND  k.article_id IN (` + articleIds + `)`
		listComment, err := cygx.GetArticleCommentListSearch(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}

		for _, v := range listComment {
			mapCommment[v.ArticleId]++
		}

		if len(listPv) > 0 {
			for _, pv := range listPv {
				for k, v := range list {
					if v.ArticleId == pv.ArticleId {
						list[k].Pv = pv.Pv
						list[k].Uv = pv.Uv
						list[k].ClPv = pv.ClPv
						list[k].ClUv = pv.ClUv
						list[k].CollectionNum = pv.CollectionNum
					}
				}
			}
		}
	}
	//ListIndustrial          []*IndustrialActivityGroupManagementRep
	//ListSubject             []*SubjectActivityGroupManagementRep
	mapIndustrial := make(map[int]string)
	mapSubject := make(map[string]string)

	mapIndustrialList := make(map[int][]*cygx.IndustrialActivityGroupManagementRep)
	mapSubjectList := make(map[int][]*cygx.SubjectActivityGroupManagementRep)
	if articleIds != "" {
		industrialList, err := cygx.GetIndustrialArticleGroupListByarticleIds(articleIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetIndustrialArticleGroupListByarticleIds Err:" + err.Error()
			return
		}
		subjectList, err := cygx.GetSubjectArticleGroupListByarticleIds(articleIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetSubjectArticleGroupListByarticleIds Err:" + err.Error()
			return
		}
		//合并活动对应的多个标的
		for _, v := range subjectList {
			mapSubject[fmt.Sprint(v.ArticleId, "_", v.IndustrialManagementId)] += v.SubjectName + "/"
			itemSubject := new(cygx.SubjectActivityGroupManagementRep)
			itemSubject.SubjectName = v.SubjectName
			itemSubject.IndustrialSubjectId = v.IndustrialSubjectId
			mapSubjectList[v.ArticleId] = append(mapSubjectList[v.ArticleId], itemSubject)
		}
		//活动对应的产业
		for _, v := range industrialList {
			var labelSubject string
			labelSubject = mapSubject[fmt.Sprint(v.ArticleId, "_", v.IndustrialManagementId)]
			if labelSubject != "" {
				mapIndustrial[v.ArticleId] += v.IndustryName + "--" + strings.TrimRight(labelSubject, "/") + "，"
			} else {
				mapIndustrial[v.ArticleId] += v.IndustryName + "，"
			}

			itemindustrial := new(cygx.IndustrialActivityGroupManagementRep)
			itemindustrial.IndustryName = v.IndustryName
			itemindustrial.IndustrialManagementId = v.IndustrialManagementId
			mapIndustrialList[v.ArticleId] = append(mapIndustrialList[v.ArticleId], itemindustrial)
		}
	}
	for k, v := range list {
		if mapIndustrial[v.ArticleId] != "" {
			list[k].Label = strings.TrimRight(mapIndustrial[v.ArticleId], "，")
		}
		if v.SubCategoryName == "专项调研" {
			v.PublishDate = cygxService.ArticlePublishDate(v.PublishDate)
		}
		list[k].CommentNum = mapCommment[v.ArticleId]
		list[k].ListIndustrial = mapIndustrialList[v.ArticleId]
		list[k].ListSubject = mapSubjectList[v.ArticleId]
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.GetReportArticleListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 过滤报告
// @Description 过滤报告接口
// @Param   ReportId   query   int  true       "报告ID"
// @Success Ret=200
// @router /reportArticle/filter [post]
func (this *IndustrialSubjectController) ReportArticleFilter() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	//if sysUser.RoleTypeCode != "rai_admin" && sysUser.RoleTypeCode != "rai_researcher" && sysUser.RoleTypeCode != "admin" {
	//	br.Msg = "你没有操作权限请联系管理员"
	//	return
	//}
	var req cygx.CygxReportArticleID
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportId := req.ReportId
	reportInfo, err := cygx.GetReportArticleId(reportId)
	if reportInfo == nil {
		br.Msg = "报告ID不存在！"
		return
	}
	if err != nil {
		br.Msg = "过滤失败！"
		br.ErrMsg = "过滤失败，Err:" + err.Error()
		return
	}
	if reportInfo.IsFilter == 1 {
		br.Msg = "您已过滤请勿重复操作！"
		return
	}
	if reportInfo.ReportType != 2 {
		br.Msg = "操作失败！"
		br.ErrMsg = "报告类型不属于产业报告！"
		return
	}
	err = cygx.FilterReportArticle(reportId)
	if err != nil {
		br.Msg = "过滤失败"
		br.ErrMsg = "过滤失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "过滤成功"
	br.IsAddLog = true
}

// @Title 报告归类
// @Description 报告归类接口
// @Param	request	body cygx.ReportArticleClassificationResp true "type json string"
// @Success Ret=200
// @router /reportArticle/classification [post]
func (this *IndustrialSubjectController) ReportArticleClassification() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	//if sysUser.RoleTypeCode != "rai_admin" && sysUser.RoleTypeCode != "rai_researcher" && sysUser.RoleTypeCode != "admin" {
	//	br.Msg = "你没有操作权限请联系管理员"
	//	return
	//}
	var req cygx.ReportArticleClassificationResp
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	var pars []interface{}
	var condition string
	reportId := req.ReportId
	industrialManagementIdStr := req.IndustrialManagementId
	reportInfo, _ := cygx.GetReportArticleId(reportId)
	if reportInfo == nil {
		br.Msg = "报告ID不存在！"
		return
	}
	if reportInfo.ReportType != 2 {
		br.Msg = "操作失败！"
		br.ErrMsg = "报告类型不属于产业报告！"
		return
	}

	industrialStrList := strings.Split(industrialManagementIdStr, ",")
	for _, v := range industrialStrList {
		condition = `AND industrial_management_id = ` + v
		totalIndustrialManagement, _ := cygx.GetIndustrialManagementCount(condition, pars)
		if totalIndustrialManagement < 1 {
			br.Msg = "操作失败"
			br.ErrMsg = "操作失败，产业不存在IndustrialManagementId：" + v
			return
		}
	}
	if req.IndustrialSubjectIdStr != "0" && req.IndustrialSubjectIdStr != "" {
		strList := strings.Split(req.IndustrialSubjectIdStr, ",")
		for _, v := range strList {
			condition = `AND industrial_subject_id = ` + v + ` AND industrial_management_id IN ( ` + industrialManagementIdStr + `)`
			totalIndustrialSubject, _ := cygx.GetIndustrialSubjectCount(condition, pars)
			if totalIndustrialSubject < 1 {
				br.Msg = "操作失败"
				br.ErrMsg = "操作失败，标的不存在IndustrialSubjectId：" + v
				return
			}
		}
	}

	err = cygx.ReportArticleClassificationEditNew(req.ReportId, industrialManagementIdStr, reportInfo.ArticleId, req.IndustrialSubjectIdStr)
	if err != nil {
		br.Msg = "分类失败"
		br.ErrMsg = "分类失败,Err:" + err.Error()
		return
	}

	go cygxService.DoArticleOnenIdWxTemplateMsg(reportInfo.ArticleId, 2)
	br.Ret = 200
	br.Success = true
	br.Msg = "分类成功"
	br.IsAddLog = true
}

// @Title 是否展示操作按钮
// @Description 获取是否展示操作按钮接口
// @Success Ret=200 {object} cygx.ShowButton
// @router /reportArticle/showButton [get]
func (this *IndustrialSubjectController) ShowButton() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	resp := new(cygx.ShowButton)
	if sysUser.RoleTypeCode == "rai_admin" || sysUser.RoleTypeCode == "rai_researcher" || sysUser.RoleTypeCode == "admin" {
		resp.IsShowButton = true
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 下载阅读明细
// @Description 获取下载阅读明细接口
// @Param   ReportId   query   int  true       "报告ID"
// @Success Ret=200
// @router /reportArticle/export [get]
func (this *IndustrialSubjectController) Export() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	reportId, _ := this.GetInt("ReportId")
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)

	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}

	var list []*cygx.ReportExportRep
	var err error
	if resp.IsCanDownload == false {
		//权益申请销售只能看到自己名下的客户的申请
		companyIds, err := cygxService.GetAdminLookUserCompanyIds(sysUser)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
			return
		}
		var companyIdstr []string
		for _, v := range companyIds {
			companyIdstr = append(companyIdstr, strconv.Itoa(v))
		}
		sqlStr := ` AND h.company_id IN  (` + strings.Join(companyIdstr, ",") + `) `
		listSeller, errSeller := cygx.GetReportExportRep(reportId, sqlStr)
		list = listSeller
		err = errSeller

	} else {
		sqlStr := ""
		listAdmin, errAdmin := cygx.GetReportExportRep(reportId, sqlStr)
		list = listAdmin
		err = errAdmin
	}
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var listNew []*cygx.ReportExportRep
	for k, v := range list {
		if k > 0 && list[k].Id == list[k-1].Id {
			list[k-1].SellerName = list[k-1].SellerName + "/" + v.SellerName
		}
	}
	for k, v := range list {
		if k > 0 && list[k].Id != list[k-1].Id {
			listNew = append(listNew, v)
		}
	}

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("关键词搜索统计")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "公司名"
	cellC := rowTitle.AddCell()
	cellC.Value = "销售名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "阅读时间"
	cellE := rowTitle.AddCell()
	cellE.Value = "停留时间(s)"
	for _, item := range listNew {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.CompanyName
		cellC := row.AddCell()
		cellC.Value = item.SellerName
		cellD := row.AddCell()
		cellD.Value = item.CreateTime
		cellE := row.AddCell()
		cellE.Value = item.StopTime
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "阅读明细统计列表" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 通过报告ID获取对应的匹配类型
// @Description 通过报告ID获取对应的匹配类型接口
// @Param   ReportId   query   int  true       "报告ID"
// @Success 200 {object} cygx.ReportMatchTypeNameList
// @router /reportArticle/getMatchTypeName [get]
func (this *IndustrialSubjectController) GetMatchTypeNameByReportId() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	reportId, _ := this.GetInt("ReportId")
	detail, err := cygx.GetArticleDetailById(reportId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	list, err := cygx.GetMatchTypeName(detail.CategoryId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp := new(cygx.ReportMatchTypeNameList)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 修改报告的匹配类型
// @Description 修改报告的匹配类型接口
// @Param	request	body cygx.UpdateReportMatchTypeNameRep true "type json string"
// @Success Ret=200
// @router /reportArticle/updateMatchTypeName [post]
func (this *IndustrialSubjectController) UpdateMatchTypeName() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req cygx.UpdateReportMatchTypeNameRep

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	reportId := req.ReportId
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	detail, err := cygx.GetMatchTypeNameById(req.MatchID)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	detailArt, err := cygx.GetArticleDetailById(reportId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	err = cygx.UpdateReportMatchTypeName(detail.MatchTypeName, detail.ReportType, detail.CategoryId, req.ReportId, detailArt.IsSummary, detailArt.IsClass)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	go cygxService.DoArticleOnenIdWxTemplateMsg(detailArt.ArticleId, 2)
	go cygxService.AddCygxReportMappingCategoryGroupByArticleId(detailArt.ArticleId) // 手动修改报告归类
	go cygxService.UpdateArticleResourceData(detailArt.ArticleId)                    //写入首页最新  cygx_resource_data 表
	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
	br.IsAddLog = true
}

// @Title 报告内容的保存与发布
// @Description 报告内容的保存与发布接口
// @Param	request	body cygx.ReportAddRep true "type json string"
// @Success 200 操作成功
// @router /reportArticle/PreserveAndPublish [post]
func (this *ReportArticleController) PreserveAndPublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ReportAddRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Title == "" {
		br.Msg = "标题不可为空"
		br.ErrMsg = "标题不可为空"
		return
	}
	if req.Abstract == "" {
		br.Msg = "摘要不可为空"
		br.ErrMsg = "摘要不可为空"
		return
	}
	var articleId int
	industrialManagementIds := req.IndustrialManagementIds
	industrialSubjectIds := req.IndustrialSubjectIds
	chartPermissionId := req.ChartPermissionId
	publishDate := req.PublishDate
	if industrialManagementIds == "" {
		br.Msg = "请选择产业"
		return
	}
	if publishDate == "" {
		br.Msg = "请选择发布时间"
		return
	}
	industryIds := make([]int, 0)
	industrialManagementIdList := strings.Split(industrialManagementIds, ",")
	for _, v := range industrialManagementIdList {
		i, err := strconv.Atoi(v)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "产业ID不规范，Err:" + err.Error() + industrialManagementIds
			return
		}
		industryIds = append(industryIds, i)
	}
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			_, err := strconv.Atoi(v)
			if err != nil {
				br.Msg = "参数解析异常！"
				br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialSubjectIds
				return
			}
		}
	}
	var pars []interface{}
	var condition string
	condition += ` AND chart_permission_id = ? AND sub_category_name = '专项调研' `
	pars = append(pars, chartPermissionId)
	charInfo, err := cygx.GetReportMappingDetail(condition, pars)
	if err != nil {
		br.Msg = "请选择所属行业"
		br.ErrMsg = "获取所属行业信息失败,Err:" + err.Error()
		return
	}
	var articleIdNew int
	if articleId == 0 {
		maxArticleIdArticleInfo, errMax := cygx.GetMaxArticleIdInfo()
		if errMax != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + errMax.Error()
			return
		}
		if maxArticleIdArticleInfo.ArticleId < utils.SummaryArticleId {
			articleIdNew = utils.SummaryArticleId
		} else {
			articleIdNew = maxArticleIdArticleInfo.ArticleId + 1
		}
	}
	expertNumStr, expertContentStr, interviewDateStr, fileLink := cygx.BodyAnalysis(req.Body)
	item := new(cygx.CygxArticle)
	item.AdminId = AdminUser.AdminId
	item.AdminName = AdminUser.AdminName
	item.Title = req.Title
	item.Body = cygxService.GetRichtext(req.Body)
	item.BodyText, _ = cygx.GetReportContentTextSub(item.Body)
	item.Abstract = req.Abstract
	item.CategoryName = charInfo.MatchTypeName
	item.SubCategoryName = charInfo.SubCategoryName
	item.ArticleId = articleId
	item.CreateDate = time.Now()
	item.LastUpdatedTime = time.Now()
	item.IsReport = 1
	item.IsSummary = 1
	item.Source = 1
	item.IsClass = 1
	item.IsReport = 1
	item.ReportType = 2
	item.ArticleIdMd5 = utils.MD5(strconv.Itoa(articleIdNew))
	item.UpdateFrequency = "unknow"
	item.SellerAndMobile = req.SellerAndMobile
	item.ExpertBackground = expertContentStr
	item.ExpertNumber = expertNumStr
	item.InterviewDate = interviewDateStr
	item.FileLink = fileLink
	item.CategoryId = charInfo.CategoryId
	item.CategoryIdTwo = charInfo.CategoryId
	item.ChartPermissionIds = strconv.Itoa(chartPermissionId)
	item.PublishDate = utils.StrTimeToTime(publishDate + " 00:00:00") //时间字符串格式转时间格式
	//处理作者内容的格式信息
	if req.DoType == 1 {
		item.PublishStatus = 1
	}

	itemDepartment := new(cygx.CygxArticleDepartment)
	if req.ArticleId == 0 {
		item.ArticleId = articleIdNew
		//需求修改纪要的新增与修改与报告一致
		_, err := cygx.AddAReportrticle(item, 0, "", "", itemDepartment, industrialManagementIds, industrialSubjectIds)
		if err != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
	} else {
		articleInfo, err := cygx.GetArticleIdInfoByArticleId(req.ArticleId)
		if err != nil {
			br.Msg = "文章不存在"
			return
		}
		if item.PublishStatus == 0 {
			item.PublishStatus = articleInfo.PublishStatus
		}
		item.ArticleId = req.ArticleId
		err = cygx.EditReportrticle(item, 0, "", "", articleInfo.PublishStatus, itemDepartment, industrialManagementIds, industrialSubjectIds)
		if err != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
	}
	//if req.DoType == 1 {
	//	go cygxService.DoArticleOnenIdWxTemplateMsg(articleId, 1)
	//}
	//{|1|}表示报告类型，{|2|}表示纪要类型
	//cygx.UpdateSubjecIds(subjectIds+"—"+strconv.Itoa(industrialDetail.IndustrialManagementId)+"{|2|}", industrialDetail.IndustrialManagementId, articleId)
	if item.PublishStatus == 1 {
		services.EsAddOrEditData(item)
		//go cygxService.UpdateResourceData(item.ArticleId, "article", "add", time.Now().Format(utils.FormatDateTime))
		go cygxService.UpdateArticleResourceData(item.ArticleId) //写入首页最新  cygx_resource_data 表
	}

	// 查研观向7.4-更新产业布局时间
	if len(industryIds) > 0 {
		go cygxService.UpdateIndustryLayoutTime(industryIds, false)
	}
	if len(industryIds) > 0 && req.DoType == 1 {
		//查研观向8.2.1专项调研报告模板消息推送
		cygxService.SendWxMsgWithCygxActivitySpecialArticle(item.ArticleId)
	}
	go cygxService.AddCygxReportMappingCategoryGroupByArticleId(item.ArticleId) // 手动修改报告归类
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title  报告详情
// @Description 获取报告详情接口
// @Param   ReportId   query   int  true       "报告ID"
// @Success Ret=200 {object} cygx.CygxArticleReport
// @router /reportArticle/detail [get]
func (this *ReportArticleController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	//reportId, _ := this.GetInt("ReportId")
	//if reportId < 1 {
	//	br.Msg = "请输入报告ID"
	//	return
	//}
	//articleInfo, err := cygx.GetArticleIdInfoByreportIdEdit(reportId)
	//if err != nil {
	//	br.Msg = "报告不存在"
	//	br.ErrMsg = "报告ID错误，Err:" + err.Error()
	//	return
	//}

	articleId, _ := this.GetInt("ArticleId")
	if articleId < 1 {
		br.Msg = "请输入文章ID"
		return
	}
	articleInfo, err := cygx.GetArticleIdInfoByreportIdEdit(articleId)
	if err != nil {
		br.Msg = "文章内容不存在"
		br.ErrMsg = "纪要ID错误，Err:" + err.Error()
		return
	}
	industrialList, err := cygx.GetIndustrialArticleGroupManagementList(articleInfo.ArticleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动关联的产业列表信息失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(articleInfo.ArticleId)
		return
	}
	subjectList, err := cygx.GetSubjectArticleGroupManagementList(articleInfo.ArticleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动关联的标的列表信息失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(articleInfo.ArticleId)
		return
	}
	articleInfo.PublishDate = cygxService.ArticlePublishDate(articleInfo.PublishDate)
	articleInfo.ListIndustrial = industrialList
	articleInfo.ListSubject = subjectList
	if articleInfo.ChartPermissionIds != "" {
		chartPermissionIdArr := strings.Split(articleInfo.ChartPermissionIds, ",")
		if len(chartPermissionIdArr) > 0 {
			articleInfo.ChartPermissionId, _ = strconv.Atoi(chartPermissionIdArr[0])
		}
	}

	if articleId < utils.SummaryArticleId {
		articleInfo.Abstract, _ = cygx.GetReportContentTextSub(articleInfo.Abstract)
		articleInfo.Body = html.UnescapeString(articleInfo.Body)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = articleInfo
}

// @Title 获取作者列表
// @Description 获取作者列表接口
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success Ret=200  {object} cygx.CygxArticleDepartmentList
// @router /reportArticle/departmentList [get]
func (this *ReportArticleController) DepartmentList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var condition string
	keyWord := this.GetString("KeyWord")
	if keyWord != "" {
		condition = `WHERE nick_name LIKE'%` + keyWord + `%'  ORDER BY create_time DESC `
	} else {
		condition += `  ORDER BY create_time DESC`
	}
	list, err := cygx.GetCygxArticleDepartmentList(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxArticleDepartmentList)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 下载客户阅读记录
// @Description 下载客户阅读记录接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Success Ret=200
// @router /reportArticle/companyHistory [get]
func (this *IndustrialSubjectController) CompanyHistory() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId < 1 {
		br.Msg = "请输入公司ID"
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	var isCanDownload bool
	adminInfo, err := system.GetSysUserById(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if adminInfo.Role == "admin" || strings.Index(adminInfo.RoleTypeCode, "rai") > -1 {
		isCanDownload = true
	}
	if !isCanDownload {
		br.Msg = "暂无下载权限"
		return
	}
	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取企业客户信息失败，Err:" + err.Error()
		return
	}

	mapChartPermissionName := make(map[int]string)

	listMap, err := cygx.GetPermissionMappingCategoryAll()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for _, v := range listMap {
		mapChartPermissionName[v.CategoryId] = v.ChartPermissionName
	}

	mobiles, err := models.GetCompanyUserMobilesByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户手机号信息失败,Err:" + err.Error()
		return
	}
	if mobiles != "" {
		mobiles = strings.Replace(mobiles, ",", "','", -1)
		mobiles = "'" + mobiles + "'"
	} else {
		mobiles = "'1'"
	}

	emails, err := models.GetCompanyUserEmailsByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户邮箱信息失败,Err:" + err.Error()
		return
	}
	if emails != "" {
		emails = strings.Replace(emails, ",", "','", -1)
		emails = "'" + emails + "'"
	} else {
		emails = "'1'"
	}

	list, err := cygx.GetCompanyHistoryRecordNewPv(mobiles, emails)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		list[k].PermissionName = mapChartPermissionName[v.CategoryId]
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("客户阅读记录")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号/邮箱"
	cellC := rowTitle.AddCell()
	cellC.Value = "报告标题"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属行业"
	cellE := rowTitle.AddCell()
	cellE.Value = "所属产业"
	cellF := rowTitle.AddCell()
	cellF.Value = "关联标的"
	cellG := rowTitle.AddCell()
	cellG.Value = "发布时间"
	cellH := rowTitle.AddCell()
	cellH.Value = "阅读时间"
	cellI := rowTitle.AddCell()
	cellI.Value = "阅读时长"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		if item.Mobile == "" {
			cellB.Value = item.Email
		}
		cellC := row.AddCell()
		cellC.Value = item.Title
		cellD := row.AddCell()
		if item.CategoryId == 0 {
			cellD.Value = "研选"
		} else {
			cellD.Value = item.PermissionName
		}
		cellE := row.AddCell()
		cellE.Value = item.IndustryName
		cellF := row.AddCell()
		cellF.Value = item.SubjectNameStr
		cellG := row.AddCell()
		cellG.Value = item.PublishDate
		cellH := row.AddCell()
		cellH.Value = item.CreateTime
		cellI := row.AddCell()
		cellI.Value = item.StopTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := companyInfo.CompanyName + "阅读记录" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 客户其他行为数据
// @Description 下载客户其他行为数据接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Success Ret=200
// @router /reportArticle/companyOtherHistory [get]
func (this *IndustrialSubjectController) CompanyOtherHistory() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户参数错误"
		return
	}
	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取企业客户信息失败，Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}

	//非管理员，那么只能看到该产品下的联系人
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		productId := services.GetProductId(sysUser.RoleTypeCode)
		condition += ` AND b.product_id = ? `
		pars = append(pars, productId)

		//流失客户（除非是超级管理员或者是部门管理员，要不然不允许看对应的联系人）
		var companyProduct *company.CompanyProduct

		if productId == 2 && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
			// 当前是权益权限，且非 权益管理员
			tmpCompanyProduct, _ := company.GetCompanyProductByCompanyIdAndProductId(companyId, 2)
			companyProduct = tmpCompanyProduct
			if companyProduct != nil && companyProduct.Status == utils.COMPANY_STATUS_LOSE {
				condition += ` AND seller_id=? `
				pars = append(pars, sysUser.AdminId)
			}
		}
	}
	list, err := company.GetCompanyUserListV2(condition, pars, companyId, 0, 1000)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	var userIdstr string
	for _, v := range list {
		userIdstr += strconv.Itoa(int(v.UserId)) + ","
	}
	userIdstr = strings.TrimRight(userIdstr, ",")
	resp := new(cygx.CompanyOtherHistoryListResp)

	condition = `	AND user_id IN (` + userIdstr + `)`
	listArticle, err := cygx.GetArticleCollectList(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	listIndustry, err := cygx.GetCygxIndustryList(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	listDepartment, err := cygx.GetArticleDepartmentList(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	//listkeyWord, err := cygx.GetCygxUserSearchKeyWordList(userIdstr)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取数据失败，Err:" + err.Error()
	//	return
	//}

	//listkeyWord, err := cygx.GetCygxUserSearchKeyWordList(userIdstr)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取数据失败，Err:" + err.Error()
	//	return
	//}

	for _, v := range list {
		userItem := new(cygx.CompanyOtherHistoryList)
		var artItems []*cygx.CygxArticleCollect
		var industryItems []*cygx.CygxArticleIndustry
		var departmentItems []*cygx.ArticleDepartment
		//var keyWordItems []*cygx.KeyWord
		for _, vArt := range listArticle {
			if vArt.UserId == int(v.UserId) {
				artItems = append(artItems, vArt)
			}
		}
		for _, vIn := range listIndustry {
			if vIn.UserId == int(v.UserId) {
				industryItems = append(industryItems, vIn)
			}
		}
		for _, vDe := range listDepartment {
			if vDe.UserId == int(v.UserId) {
				departmentItems = append(departmentItems, vDe)
			}
		}
		//for _, vKw := range listkeyWord {
		//	if vKw.UserId == int(v.UserId) {
		//		keyWordItems = append(keyWordItems, vKw)
		//	}
		//}
		if len(artItems) > 0 || len(industryItems) > 0 || len(departmentItems) > 0 {
			userItem.RealName = v.RealName
			userItem.Email = v.Email
			userItem.Mobile = v.Mobile
			userItem.ListArticle = artItems
			userItem.ListIndustrial = industryItems
			userItem.ListDepartment = departmentItems
			//userItem.ListKeyWord = keyWordItems
			resp.List = append(resp.List, userItem)
		}
	}

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("客户其他行为数据(收藏，关注)")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}

	//标题样式
	titleStyle := xlsx.NewStyle()
	titleFont := xlsx.NewFont(16, "宋体")
	titleFont.Bold = true
	titleStyle.Font = *titleFont
	titleStyle.Alignment = alignment
	sheet.SetColWidth(0, 0, 20)
	sheet.SetColWidth(1, 1, 20)
	sheet.SetColWidth(2, 2, 20)
	sheet.SetColWidth(3, 3, 20)
	sheet.SetColWidth(4, 4, 20)

	titleSonStyle := xlsx.NewStyle()
	titleSonFont := xlsx.NewFont(16, "宋体")
	titleSonFont.Bold = true
	titleSonStyle.Font = *titleSonFont

	for _, item := range resp.List {

		rowTitle := sheet.AddRow()
		//标题列
		titleCell := rowTitle.AddCell()
		titleCell.HMerge = 6 //向右合并列数，不包括自身列
		titleCell.SetValue("客户姓名：" + item.RealName + "      手机号/邮箱：" + item.Mobile)
		titleCell.SetStyle(titleStyle)

		//文章
		if len(item.ListArticle) > 0 {
			rowArticle := sheet.AddRow()
			cellA := rowArticle.AddCell()
			cellA.Value = "收藏报告"
			cellB := rowArticle.AddCell()
			cellB.Value = "收藏时间"
			cellC := rowArticle.AddCell()
			cellC.Value = "发布时间"
			cellD := rowArticle.AddCell()
			cellD.Value = "报告类型"
			cellE := rowArticle.AddCell()
			cellE.Value = "所属产业"
			cellF := rowArticle.AddCell()
			cellF.Value = "关联标的"

			cellA.SetStyle(titleSonStyle)
			cellB.SetStyle(titleSonStyle)
			cellC.SetStyle(titleSonStyle)
			cellD.SetStyle(titleSonStyle)
			cellE.SetStyle(titleSonStyle)
			cellF.SetStyle(titleSonStyle)
			for _, vArt := range item.ListArticle {
				rowArticleVal := sheet.AddRow()
				cellA := rowArticleVal.AddCell()
				cellA.Value = vArt.Title
				cellB := rowArticleVal.AddCell()
				cellB.Value = vArt.CreateTime
				cellC := rowArticleVal.AddCell()
				cellC.Value = vArt.PublishDate
				cellD := rowArticleVal.AddCell()
				cellD.Value = vArt.MatchTypeName
				cellE := rowArticleVal.AddCell()
				cellE.Value = vArt.IndustryName
				cellF := rowArticleVal.AddCell()
				cellF.Value = vArt.SubjectName
			}
		}
		//产业
		if len(item.ListIndustrial) > 0 {
			rowIndustrial := sheet.AddRow()
			cellA := rowIndustrial.AddCell()
			cellA.Value = "关注产业"
			cellB := rowIndustrial.AddCell()
			cellB.Value = "关注时间"

			cellA.SetStyle(titleSonStyle)
			cellB.SetStyle(titleSonStyle)
			for _, vArt := range item.ListIndustrial {
				rowIndustrialVal := sheet.AddRow()
				cellA := rowIndustrialVal.AddCell()
				cellA.Value = vArt.IndustryName
				cellB := rowIndustrialVal.AddCell()
				cellB.Value = vArt.CreateTime
			}
		}
		//作者
		if len(item.ListDepartment) > 0 {
			rowDepartment := sheet.AddRow()
			cellA := rowDepartment.AddCell()
			cellA.Value = "关注作者"
			cellB := rowDepartment.AddCell()
			cellB.Value = "关注时间"
			cellC := rowDepartment.AddCell()
			cellC.Value = "作者相关产业"

			cellA.SetStyle(titleSonStyle)
			cellB.SetStyle(titleSonStyle)
			cellC.SetStyle(titleSonStyle)
			for _, vArt := range item.ListDepartment {
				rowDepartmentVal := sheet.AddRow()
				cellA := rowDepartmentVal.AddCell()
				cellA.Value = vArt.NickName
				cellB := rowDepartmentVal.AddCell()
				cellB.Value = vArt.CreateTime
				cellC := rowDepartmentVal.AddCell()
				cellC.Value = vArt.IndustryName
			}
		}
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := companyInfo.CompanyName + "其他行为数据(收藏，关注)" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Data = resp
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 客户阅读量月度统计
// @Description 客户阅读量月度统计
// @Param   CompanyId   query   int  true       "公司ID"
// @Success Ret=200
// @router /reportArticle/companyCount [get]
func (this *IndustrialSubjectController) CompanyCount() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	if companyId < 1 {
		br.Msg = "请输入公司ID"
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	var isCanDownload bool
	adminInfo, err := system.GetSysUserById(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if adminInfo.Role == "admin" || strings.Index(adminInfo.RoleTypeCode, "rai") > -1 {
		isCanDownload = true
	}
	if !isCanDownload {
		br.Msg = "暂无下载权限"
		return
	}
	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取企业客户信息失败，Err:" + err.Error()
		return
	}
	mobiles, err := models.GetCompanyUserMobilesByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户手机号信息失败,Err:" + err.Error()
		return
	}
	if mobiles != "" {
		mobiles = strings.Replace(mobiles, ",", "','", -1)
		mobiles = "'" + mobiles + "'"
	} else {
		mobiles = "'1'"
	}

	emails, err := models.GetCompanyUserEmailsByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户邮箱信息失败,Err:" + err.Error()
		return
	}
	if emails != "" {
		emails = strings.Replace(emails, ",", "','", -1)
		emails = "'" + emails + "'"
	} else {
		emails = "'1'"
	}
	listDate, err := cygx.GetCompanyHistoryRecordPvGroupDate(mobiles, emails)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	dateMap := make(map[string]int)
	permissionNameMap := make(map[string]int)
	list, err := cygx.GetCompanyHistoryRecordPv(mobiles, emails)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for _, v := range list {
		if dateMap[v.CreateTime] == 0 {
			dateMap[v.CreateTime] = 1
		} else {
			dateMap[v.CreateTime] += 1
		}
		if v.CategoryId == 0 {
			v.PermissionName = "研选"
		}

		if permissionNameMap[v.CreateTime+v.PermissionName] == 0 {
			permissionNameMap[v.CreateTime+v.PermissionName] = 1
		} else {
			permissionNameMap[v.CreateTime+v.PermissionName] += 1
		}
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("客户阅读量月度统计")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "月份"
	cellB := rowTitle.AddCell()
	cellB.Value = "总阅读数"
	cellC := rowTitle.AddCell()
	cellC.Value = "医药"
	cellD := rowTitle.AddCell()
	cellD.Value = "消费"
	cellE := rowTitle.AddCell()
	cellE.Value = "科技"
	cellF := rowTitle.AddCell()
	cellF.Value = "智造"
	cellG := rowTitle.AddCell()
	cellG.Value = "策略"
	cellH := rowTitle.AddCell()
	cellH.Value = "研选"

	for _, item := range listDate {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.CreateTimes
		cellB := row.AddCell()
		cellB.Value = strconv.Itoa(dateMap[item.CreateTimes])
		cellC := row.AddCell()
		cellC.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"医药"])
		cellD := row.AddCell()
		cellD.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"消费"])
		cellE := row.AddCell()
		cellE.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"科技"])
		cellF := row.AddCell()
		cellF.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"智造"])
		cellG := row.AddCell()
		cellG.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"策略"])
		cellH := row.AddCell()
		cellH.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"研选"])
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := companyInfo.CompanyName + "客户阅读量月度统计" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 客户导出文件种类
// @Description 客户导出文件种类接口
// @Success Ret=200  {object} cygx.NameAndUrlList
// @router /company/exportList [get]
func (this *ReportArticleController) ExportList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	detail, err := cygx.GetCygxConfigDetailByCode("export_list")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.NameAndUrlList)
	exportList := strings.Split(detail.ConfigValue, "{|}")
	for _, v := range exportList {
		item := new(cygx.NameAndUrl)
		vslice := strings.Split(v, "_")
		item.Name = vslice[0]
		item.Url = vslice[len(vslice)-1]
		resp.List = append(resp.List, item)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 留言列表详情
// @Description 获取留言列表详情接口
// @Param   ArticleId   query   int  true       "文章ID"
// @Success 200 {object} cygx.ArticleCommentListResp
// @router /reportArticle/commentList [get]
func (this *ReportArticleController) CommentList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	articleId, _ := this.GetInt("ArticleId")
	articleInfo, _ := cygx.GetArticleIdInfoByArticleId(articleId)
	if articleInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "报告ID错误"
		return
	}
	list, err := cygx.GetArticleCommentList(articleInfo.ArticleId)
	resp := new(cygx.ArticleCommentListResp)
	if err != nil {
		br.Msg = "获取留言失败"
		br.ErrMsg = "获取留言失败，Err:" + err.Error()
		return
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 提问详情excel表格下载
// @Description 提问详情excel表格下载接口
// @Param   SummaryManageId   query   int  true       "纪要ID"
// @Success 200 导出成功
// @router /reportArticle/commnetListExport [get]
func (this *ReportArticleController) CommentListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	articleId, _ := this.GetInt("ArticleId")
	articleInfo, _ := cygx.GetArticleIdInfoByArticleId(articleId)
	if articleInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "报告ID错误"
		return
	}
	list, err := cygx.GetArticleCommentList(articleInfo.ArticleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "公司名称"
	cellC := rowTitle.AddCell()
	cellC.Value = "留言"
	cellD := rowTitle.AddCell()
	cellD.Value = "提交时间"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.CompanyName
		cellC := row.AddCell()
		cellC.Value = item.Content
		cellD := row.AddCell()
		cellD.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "留言列表" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.Msg = "导出成功"
}

// @Title 新建报告类型
// @Description 新建报告类型接口
// @Param	request	body cygx.CygxReportMappingCygxAdd true "type json string"
// @Success Ret=200  {object} cygx.CygxReportMappingCygx
// @router /reportMapping/add [post]
func (this *IndustrialSubjectController) ReportMappingAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.CygxReportMappingCygxAdd
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	var condition string
	var pars []interface{}
	reportType := req.ReportType
	chartPermissionId := req.ChartPermissionId
	chartPermissionName := req.ChartPermissionName
	matchTypeName := req.MatchTypeName
	condition = ` AND match_type_name = ?  AND chart_permission_id = ? `
	pars = append(pars, matchTypeName, chartPermissionId)
	total, err := cygx.GetCygxReportMappingCygxCount(condition, pars)
	if err != nil {
		br.Msg = "新建报告类型失败"
		br.ErrMsg = "新建报告类型失败，Err:" + err.Error()
		return
	}
	if total > 0 {
		br.Msg = "名称已存在"
		br.ErrMsg = "名称已存在，Err:" + matchTypeName
		return
	}

	maxDeatil, err := cygx.GetCygxReportMappingCelueMaxDetail()
	if err != nil {
		br.Msg = "新建报告类型失败"
		br.ErrMsg = "GetCygxReportMappingCelueMaxDetail，Err:" + err.Error()
		return
	}

	itemCygx := new(cygx.CygxReportMappingCygx)
	itemCygx.ChartPermissionId = chartPermissionId
	itemCygx.ChartPermissionName = chartPermissionName
	itemCygx.MatchTypeName = matchTypeName
	itemCygx.ReportType = reportType
	itemCygx.IsReport = 1
	itemCygx.CreateTime = time.Now()
	itemCygx.ModifyTime = time.Now()

	itemCelue := new(cygx.CygxReportMappingCelue)
	itemCelue.ChartPermissionId = chartPermissionId
	itemCelue.ChartPermissionName = chartPermissionName
	itemCelue.SubCategoryName = matchTypeName
	itemCelue.ReportType = reportType
	itemCelue.IsReport = 1
	itemCelue.CategoryId = maxDeatil.CategoryId + 1
	itemCelue.CreateTime = time.Now()
	itemCelue.ModifyTime = time.Now()

	itemCygxId, err := cygx.AddCygxReportMappingCygx(itemCygx, itemCelue)
	if err != nil {
		br.Msg = "新建报告类型失败"
		br.ErrMsg = "AddCygxReportMappingCygx，Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxReportMappingCygx)
	resp.Id = int(itemCygxId)
	resp.MatchTypeName = matchTypeName

	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "分类成功"
	br.IsAddLog = true
}
