package logic

import (
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/common"
	reportResp "hongze/hongze_open_api/models/response/report"
	"hongze/hongze_open_api/models/tables/chart_permission"
	"hongze/hongze_open_api/models/tables/chart_permission_chapter_mapping"
	"hongze/hongze_open_api/models/tables/chart_permission_search_key_word_mapping"
	"hongze/hongze_open_api/models/tables/company_product"
	"hongze/hongze_open_api/models/tables/company_report_permission"
	"hongze/hongze_open_api/models/tables/daily_base_column"
	"hongze/hongze_open_api/models/tables/rddp/classify"
	"hongze/hongze_open_api/models/tables/rddp/report"
	"hongze/hongze_open_api/models/tables/rddp/report_chapter"
	"hongze/hongze_open_api/models/tables/rddp/report_chapter_ticker"
	"hongze/hongze_open_api/models/tables/report_chapter_type"
	"hongze/hongze_open_api/models/tables/wx_user"
	"hongze/hongze_open_api/services/company"
	"hongze/hongze_open_api/utils"
	"html"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
)

// GetReportList 获取报告列表
func GetReportList(classifyId int, mobile, keyword string, startSize, pageSize int) (total int, list []*report.ReportList, err error, errMsg string) {
	//加密后的手机号
	encryptMobile := string(utils.DesBase64Encrypt([]byte(mobile)))
	errMsg = `获取失败`
	// 获取用户信息
	userInfo, err := wx_user.GetWxUserByMobileCountryCode(mobile, "86")
	if err != nil {
		errMsg = "获取用户信息失败"
		return
	}

	productId := 1
	companyProduct, err := company_product.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, productId)
	if err != nil {
		errMsg = "获取客户信息失败"
		return
	}
	//`is_suspend` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1:暂停,0:启用',
	if companyProduct.IsSuspend != 0 {
		errMsg = "客户状态异常"
		return
	}

	permissionList, err := company_report_permission.GetPermissionListByCompanyIdAndProductId(userInfo.CompanyId, productId)
	if err != nil {
		errMsg = "获取客户品种失败"
		return
	}
	if len(permissionList) == 0 {
		errMsg = "客户品种异常"
		return
	}
	//客户品种id列表
	permissionIdList := make([]int, 0)
	for _, v := range permissionList {
		permissionIdList = append(permissionIdList, v.ChartPermissionId)
	}

	// 获取分类信息
	classifyInfo, err := classify.GetClassify(classifyId)
	if err != nil {
		errMsg = "获取分类信息失败"
		return
	}
	var firstClassifyId, secondClassifyId int
	firstClassifyId = classifyInfo.ParentId
	secondClassifyId = classifyInfo.Id
	if classifyInfo.ParentId <= 0 {
		firstClassifyId = classifyInfo.Id
		secondClassifyId = 0
	}

	var condition string
	var pars []interface{}

	// 分类
	condition = ` AND state = 2 AND classify_id_first = ? AND classify_id_second = ? `
	pars = append(pars, firstClassifyId, secondClassifyId)

	//报告名称
	if keyword != "" {
		condition += ` AND  title LIKE ? `
		pars = append(pars, `%`+keyword+`%`)
	}
	total, list, err = report.GetReportList(condition, pars, startSize, pageSize)

	encryptMobile = url.QueryEscape(encryptMobile) //转义 +
	nonceStr := common.GetRandString(10)
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10)

	for _, v := range list {
		//if v.Stage > 0 {
		//	v.Title = fmt.Sprintf("【第%d期】%s", v.Stage, v.Title)
		//}
		//v.Title = fmt.Sprintf("%s(%s)", v.Title, v.CreateTime.Format(utils.FormatMonthDate))

		//跳转地址
		postData := make(map[string]string)
		reportId := strconv.Itoa(v.Id)
		parameter := "mobile=" + encryptMobile + "&report_id=" + reportId + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
		postData["mobile"] = encryptMobile
		postData["report_id"] = reportId
		postData["appid"] = utils.ReportAppid
		postData["nonce_str"] = nonceStr
		postData["timestamp"] = timeUnix
		sign := utils.GetSign(postData)
		v.HttpUrl = utils.NewResearchReportUrl + "hzsl/report/new/detail?" + parameter + "&sign=" + sign
	}
	return
}

// GetReportDetail 获取报告详情
func GetReportDetail(reportId int, mobile string) (reportDetail reportResp.ReportDetail, err error, errMsg string) {
	encryptMobile := string(utils.DesBase64Encrypt([]byte(mobile)))
	errMsg = `获取失败`
	// 获取用户信息
	userInfo, err := wx_user.GetWxUserByMobileCountryCode(mobile, "86")
	if err != nil {
		errMsg = "获取用户信息失败"
		return
	}

	// 判断用户状态是否是正常和永续
	var productAuthOk bool

	productId := 1
	companyProduct, err := company_product.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, productId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = nil
		} else {
			errMsg = err.Error()
			err = errors.New("查询用户购买产品出错")
			return
		}
	}
	if companyProduct != nil {
		// 无FICC权限的客户不可见
		if companyProduct.CompanyProductId > 0 {
			// 已购或者试用用户可见
			if strings.Contains("永续,正式", companyProduct.Status) || (companyProduct.Status == "试用" && companyProduct.IsSuspend != 1) {
				productAuthOk = true
			}
		}
	}

	reportInfo, err := report.GetById(reportId)
	if err != nil {
		errMsg = "获取报告失败"
		return
	}
	//  `state` tinyint(2) DEFAULT '1' COMMENT '1:未发布，2:已发布',
	if reportInfo.State != 2 {
		errMsg = "报告未发布"
		err = errors.New("报告未发布")
		return
	}
	// 判断报告是否属于专栏报告
	firstClassify, e := classify.GetClassify(reportInfo.ClassifyIdFirst)
	if e != nil {
		errMsg = "报告异常"
		err = errors.New("报告一级分类有误")
		return
	}
	if firstClassify.IsShow != 1 {
		errMsg = "报告异常"
		err = errors.New("报告一级分类未发布")
		return
	}

	var authOk bool
	var permissionCheckInfo reportResp.PermissionCheckInfo
	var vaildWeekTypeIds []int
	if reportInfo.ClassifyNameFirst == "晨报" {
		authOk, permissionCheckInfo, err = CheckDayReportPermission(userInfo, productAuthOk)
	} else if reportInfo.ClassifyNameFirst == "周报" {
		authOk, permissionCheckInfo, vaildWeekTypeIds, err = CheckWeekReportPermission(userInfo, productAuthOk)
	} else {
		authOk, permissionCheckInfo, err = CheckReportPermission(userInfo, reportId, productAuthOk)
	}
	if err != nil {
		return
	}

	reportItem := reportResp.ReportItem{
		ReportId:           reportInfo.Id,
		ClassifyNameFirst:  reportInfo.ClassifyNameFirst,
		ClassifyNameSecond: reportInfo.ClassifyNameSecond,
		Title:              reportInfo.Title,
		Abstract:           reportInfo.Abstract,
		Author:             reportInfo.Author,
		Frequency:          reportInfo.Frequency,
		PublishTime:        reportInfo.PublishTime,
		Stage:              reportInfo.Stage,
		Content:            html.UnescapeString(reportInfo.ContentSub),
		VideoUrl:           "",
		VideoName:          reportInfo.VideoName,
		VideoSize:          reportInfo.VideoSize,
		VideoPlaySeconds:   reportInfo.VideoPlaySeconds,
		VideoImg:           "",
		ContentSub:         "",
		BannerUrl:          "",
	}

	if reportInfo.VideoName == "" && reportInfo.VideoUrl != "" {
		reportItem.VideoName = reportInfo.Title
	}
	var reportTypeList []*reportResp.ReportChapterListItem

	if reportInfo.ClassifyNameFirst == "晨报" || reportInfo.ClassifyNameFirst == "周报" {
		//（晨报和周报的banner图）
		if reportInfo.ClassifyNameFirst == "晨报" {
			reportItem.BannerUrl = utils.ALIYUN_YBIMG_HOST + "report_banner_day.jpg"
		} else {
			reportItem.BannerUrl = utils.ALIYUN_YBIMG_HOST + "report_banner_week.jpg"
		}
		if authOk {
			reportTypeList, err, errMsg = GetChapterListByReport(reportInfo.ClassifyNameFirst, reportInfo.Id, vaildWeekTypeIds, reportInfo.CreateTime)
			if err != nil {
				return
			}
		}
	} else {
		// 音频播放条图片用分类图片
		reportItem.VideoImg = utils.HZ_DEFAULT_AVATAR
		permissionIds, tmpErr := chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(reportItem.ClassifyNameSecond)
		if tmpErr != nil {
			errMsg = tmpErr.Error()
			err = errors.New("查询报告权限失败")
			return
		}
		if len(permissionIds) > 0 {
			chartPermission, tmpErr := chart_permission.GetListByIds(permissionIds)
			if tmpErr != nil {
				errMsg = tmpErr.Error()
				err = errors.New("查询品种信息失败")
				return
			}
			lenChart := len(chartPermission)
			for i := 0; i < lenChart; i++ {
				if chartPermission[i].YbImgUrl != "" {
					reportItem.VideoImg = utils.ALIYUN_YBIMG_HOST + chartPermission[i].YbImgUrl
					break
				}
			}
		}
	}

	//如果有权限则展示content
	//var likeNum int64
	//var likeEnabled int8
	if authOk {
		//go AddViewRecord(userinfo, reportInfo.Id, reportInfo.ClassifyNameFirst, 0)
		reportItem.Content = html.UnescapeString(reportInfo.Content)
		reportItem.VideoUrl = reportInfo.VideoUrl
		//查询点赞数
		//likeNum,likeEnabled, _ = services.GetReportLikeByReportIdOldReportId(userinfo.UserID, reportInfo.Id, 0,0,0)
	}

	encryptMobile = url.QueryEscape(encryptMobile) //转义 +
	nonceStr := common.GetRandString(10)
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10)

	for _, v := range reportTypeList {
		//跳转地址
		postData := make(map[string]string)
		reportChapterId := strconv.Itoa(v.ReportChapterId)
		parameter := "mobile=" + encryptMobile + "&report_chapter_id=" + reportChapterId + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
		postData["mobile"] = encryptMobile
		postData["report_chapter_id"] = reportChapterId
		postData["appid"] = utils.ReportAppid
		postData["nonce_str"] = nonceStr
		postData["timestamp"] = timeUnix
		sign := utils.GetSign(postData)
		v.HttpUrl = utils.NewResearchReportUrl + "hzsl/report/new/chapter/detail?" + parameter + "&sign=" + sign
	}

	reportDetail.ReportInfo = reportItem
	reportDetail.ReportChapterList = reportTypeList
	reportDetail.PermissionCheck = permissionCheckInfo
	reportDetail.AuthOk = authOk
	//reportDetail.LikeNum = likeNum
	//reportDetail.LikeEnabled = likeEnabled
	reportDetail.ReportShowType = firstClassify.ShowType
	return
}

// GetChapterListByReport 根据报告获取章节列表
func GetChapterListByReport(classifyNameFirst string, reportId int, validWeekTypeIds []int, reportCreateTime time.Time) (reportTypeList reportResp.ReportChapterList, err error, errMsg string) {
	defer func() {
		if err != nil {
			utils.FileLog.Critical(fmt.Sprintf("GetChapterListByReport: err:%s， errMsg:%s", err.Error(), errMsg))
		}
	}()

	//查询有效的章节
	typeList, err := report_chapter_type.GetEffectTypes()
	if err != nil {
		errMsg = "章节类型查询出错"
		return
	}
	if len(typeList) == 0 {
		errMsg = "无有效的章节"
		err = errors.New("无有效的章节")
		return
	}

	typeMap := make(map[uint64]*report_chapter_type.ReportChapterType)
	var typeIds []int
	newTypeMap := make(map[int]bool)
	for _, v := range typeList {
		typeMap[v.ReportChapterTypeId] = v
		typeIds = append(typeIds, int(v.ReportChapterTypeId))
	}

	if classifyNameFirst == "周报" {
		for _, v := range validWeekTypeIds {
			newTypeMap[v] = true
		}
	}
	//获取所有当前研报的章节
	chapterList, err := report_chapter.GetListByReportId(reportId, classifyNameFirst)
	if err != nil {
		errMsg = "章节查询出错"
		return
	}
	if len(chapterList) == 0 {
		errMsg = "无有效章节"
		err = errors.New("无有效章节")
		return
	}

	for _, item := range chapterList {
		if typeItem, ok := typeMap[uint64(item.TypeId)]; ok {
			// 如果是周报只展示有权限的章节
			if classifyNameFirst == "周报" {
				if _, ok1 := newTypeMap[item.TypeId]; !ok1 {
					continue
				}
			}
			temp := new(reportResp.ReportChapterListItem)
			if reportCreateTime.Before(typeItem.PauseStartTime) || reportCreateTime.After(typeItem.PauseEndTime) {
				temp.ReportChapterId = item.ReportChapterId
				temp.TypeId = item.TypeId
				temp.TypeName = item.TypeName
				temp.Title = item.Title
				temp.Trend = item.Trend
				temp.ReportId = item.ReportId
				temp.Sort = typeItem.Sort
				temp.PublishTime = item.PublishTime
				temp.ReportChapterTypeKey = typeItem.ReportChapterTypeKey
				temp.ReportChapterTypeName = typeItem.ReportChapterTypeName
				temp.ReportChapterTypeThumb = typeItem.YbIconUrl
				reportTypeList = append(reportTypeList, temp)
			}
		}
	}
	if len(reportTypeList) > 0 {
		sort.Sort(reportTypeList)
	}
	return
}

// GetChapterDetail 获取章节详情
func GetChapterDetail(mobile string, reportChapterId int) (reportChapterDetail reportResp.ReportChapterDetail, err error, errMsg string) {
	defer func() {
		if err != nil {
			utils.FileLog.Critical(fmt.Sprintf("GetChapterDetail: mobile=%s, err:%s， errMsg:%s", mobile, err.Error(), errMsg))
		}
	}()
	encryptMobile := string(utils.DesBase64Encrypt([]byte(mobile)))
	errMsg = `获取失败`
	// 获取用户信息
	userInfo, err := wx_user.GetWxUserByMobileCountryCode(mobile, "86")
	if err != nil {
		errMsg = "获取用户信息失败"
		return
	}
	var authOk bool
	var productAuthOk bool
	var chapterAuthOk bool
	var permissionCheckInfo reportResp.PermissionCheckInfo

	//查询客户信息（判断客户状态是否是正常和永续）
	productId := 1
	companyProduct, err := company_product.GetCompanyProductByCompanyIdAndProductId(userInfo.CompanyId, productId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = nil
		} else {
			errMsg = err.Error()
			err = errors.New("查询用户购买产品出错")
			return
		}
	}
	if companyProduct != nil {
		// 无FICC权限的客户不可见
		if companyProduct.CompanyProductId > 0 {
			// 已购或者试用用户可见
			if strings.Contains("永续,正式", companyProduct.Status) || (companyProduct.Status == "试用" && companyProduct.IsSuspend != 1) {
				productAuthOk = true
			}
		}
	}

	//章节分类
	typeIds, err := report_chapter_type.GetEffectTypeID()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("章节类型查询出错")
		return
	}
	if len(typeIds) == 0 {
		err = errors.New("无有效的章节类型")
		return
	}
	reportChapter, err := report_chapter.GetContentById(reportChapterId, typeIds)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("章节查询出错")
		return
	}

	if reportChapter.ReportChapterId == 0 {
		err = errors.New("章节不存在")
		return
	}

	//报告信息
	reportInfo, tErr := report.GetById(reportChapter.ReportId)
	if tErr != nil {
		errMsg = tErr.Error()
		err = errors.New("报告查询出错")
		return
	}
	if reportInfo.Id == 0 {
		err = errors.New("报告不存在")
		return
	}
	if reportInfo.ClassifyNameFirst == "周报" && reportChapter.IsEdit != 1 {
		err = errors.New("章节未编辑")
		return
	}

	//判断权限
	var reportChapterTypeIds []int
	if reportInfo.ClassifyNameFirst == "晨报" {
		authOk, permissionCheckInfo, err = CheckDayReportPermission(userInfo, productAuthOk)
		if err != nil && err.Error() != utils.ErrNoRow() {
			errMsg = err.Error()
			err = errors.New("权限查询出错")
			return
		}
	} else if reportInfo.ClassifyNameFirst == "周报" {
		authOk, permissionCheckInfo, reportChapterTypeIds, err = CheckWeekReportPermission(userInfo, productAuthOk)
		if err != nil && err.Error() != utils.ErrNoRow() {
			errMsg = err.Error()
			err = errors.New("权限查询出错")
			return
		}
		for _, v := range reportChapterTypeIds {
			if v == reportChapter.TypeId {
				chapterAuthOk = true
			}
		}
		authOk = chapterAuthOk
	}

	videoImgMap := map[string]string{
		"day":  "report_list_chen.png",
		"week": "report_list_zhou.png",
	}

	reportChapterItem := reportResp.ReportChapterItem{
		ReportChapterId:       reportChapter.ReportChapterId,
		ReportId:              reportChapter.ReportId,
		Title:                 reportChapter.Title,
		Abstract:              reportChapter.Abstract,
		TypeId:                reportChapter.TypeId,
		TypeName:              reportChapter.TypeName,
		Trend:                 "",
		ReportChapterTypeName: "",
		PublishTime:           reportChapter.PublishTime,
		Content:               "",
		ContentSub:            html.UnescapeString(reportChapter.ContentSub),
		VideoUrl:              "",
		VideoName:             reportChapter.VideoName,
		VideoPlaySeconds:      reportChapter.VideoPlaySeconds,
		VideoSize:             reportChapter.VideoSize,
		VideoImg:              utils.ALIYUN_YBIMG_HOST + videoImgMap[reportChapter.ReportType],
		Author:                reportChapter.Author,
		Stage:                 reportChapter.Stage,
		ClassifyIdFirst:       reportChapter.ClassifyIdFirst,
		ClassifyNameFirst:     reportChapter.ClassifyNameFirst,
	}
	if reportChapter.VideoUrl != "" && reportChapter.VideoName == "" {
		reportChapterItem.VideoName = reportChapter.Title
	}

	//var likeNum int64
	//var likeEnabled int8
	//底部菜单切换
	var chapterMenu []reportResp.ReportChapterMenu
	if authOk {
		reportChapterItem.Content = html.UnescapeString(reportChapter.Content)
		reportChapterItem.VideoUrl = reportChapter.VideoUrl
		//底部菜单切换
		if reportInfo.ClassifyNameFirst == "周报" {
			chapterMenu, err = GetMenuChapter(reportInfo.Id, reportChapterTypeIds, reportInfo.ClassifyNameFirst, reportInfo.CreateTime, encryptMobile)
		} else {
			chapterMenu, err = GetMenuChapter(reportInfo.Id, typeIds, reportInfo.ClassifyNameFirst, reportInfo.CreateTime, encryptMobile)
		}
		//查询点赞数
		//likeNum,likeEnabled, _ = services.GetReportLikeByReportIdOldReportId(user.UserID, reportInfo.Id, reportChapter.ReportChapterId,0,0)
		//go AddViewRecord(user, reportInfo.Id, reportInfo.ClassifyNameFirst, reportChapterId)
	} else {
		reportChapterItem.ContentSub = html.UnescapeString(reportChapter.ContentSub)
	}

	//请求指标数据的参数
	tickerDataParams := ``
	{
		nonceStr := common.GetRandString(10)
		timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
		postData := make(map[string]string)
		reportChapterIdStr := strconv.Itoa(reportChapterId)
		parameter := "report_chapter_id=" + reportChapterIdStr + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
		postData["mobile"] = encryptMobile
		postData["report_chapter_id"] = reportChapterIdStr
		postData["appid"] = utils.ReportAppid
		postData["nonce_str"] = nonceStr
		postData["timestamp"] = timeUnix
		sign := utils.GetSign(postData)
		tickerDataParams = parameter + "&sign=" + sign
	}

	reportChapterDetail = reportResp.ReportChapterDetail{
		ReportChapterItem:     reportChapterItem,
		ReportChapterMenuList: chapterMenu,
		AuthOk:                authOk,
		PermissionCheck:       permissionCheckInfo,
		TickerDataParams:      tickerDataParams,
		//LikeNum:               0,
		//LikeEnabled:           0,
	}
	//reportChapterDetail.PermissionCheck = &permissionCheckInfo
	//reportChapterDetail.LikeNum = likeNum
	//reportChapterDetail.LikeEnabled = likeEnabled
	return
}

// GetMenuChapter 获取章节下面的菜单
func GetMenuChapter(reportId int, typeIds []int, classifyNameFirst string, reportCreateTime time.Time, encryptMobile string) (reportTypeList reportResp.ReportChapterMenuList, err error) {
	reportTypeList = make([]reportResp.ReportChapterMenu, 0)

	//查询有效的章节
	typeList, tErr := report_chapter_type.GetEffectTypes()
	if tErr != nil {
		return
	}
	if len(typeList) == 0 {
		err = errors.New("无有效的章节")
		return
	}

	typeMap := make(map[uint64]*report_chapter_type.ReportChapterType)
	for _, v := range typeList {
		typeMap[v.ReportChapterTypeId] = v
	}

	//获取所有当前研报的章节
	chapterList, tErr := report_chapter.GetListByReportIdTypeIds(reportId, typeIds, classifyNameFirst)
	if tErr != nil {
		return
	}

	encryptMobile = url.QueryEscape(encryptMobile) //转义 +
	nonceStr := common.GetRandString(10)
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
	if len(chapterList) > 0 {
		for _, item := range chapterList {
			if typeItem, ok := typeMap[uint64(item.TypeId)]; ok {
				if reportCreateTime.Before(typeItem.PauseStartTime) || reportCreateTime.After(typeItem.PauseEndTime) {
					//typeItem.ReportChapterTypeId
					//跳转地址
					postData := make(map[string]string)
					reportChapterId := strconv.Itoa(item.ReportChapterId)
					parameter := "mobile=" + encryptMobile + "&report_chapter_id=" + reportChapterId + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
					postData["mobile"] = encryptMobile
					postData["report_chapter_id"] = reportChapterId
					postData["appid"] = utils.ReportAppid
					postData["nonce_str"] = nonceStr
					postData["timestamp"] = timeUnix
					sign := utils.GetSign(postData)

					temp := reportResp.ReportChapterMenu{
						ReportChapterId:        item.ReportChapterId,
						ReportId:               item.ReportId,
						ReportChapterTypeName:  typeItem.ReportChapterTypeName,
						ReportChapterTypeThumb: typeItem.YbBottomIcon,
						PcSelectedThumb:        typeItem.PcSelectedImage,
						PcUnselectedThumb:      typeItem.PcUnselectedImage,
						Sort:                   typeItem.Sort,
						HttpUrl:                utils.NewResearchReportUrl + "hzsl/report/new/chapter/detail?" + parameter + "&sign=" + sign,
					}

					reportTypeList = append(reportTypeList, temp)
				}
			}
		}
	}
	if len(reportTypeList) > 0 {
		sort.Sort(reportTypeList)
	}
	return
}

// CheckDayReportPermission 验证晨报的权限
func CheckDayReportPermission(userInfo *wx_user.WxUser, productAuthOk bool) (authOk bool, permissionCheckInfo reportResp.PermissionCheckInfo, err error) {
	if productAuthOk {
		authOk = true
		return
	}
	authOk, permissionCheckInfo, _, err = company.GetCheckPermission(userInfo.CompanyId, int(userInfo.UserId), []int{})
	return
}

// CheckWeekReportPermission 验证周报的权限
func CheckWeekReportPermission(userInfo *wx_user.WxUser, productAuthOk bool) (authOk bool, permissionCheckInfo reportResp.PermissionCheckInfo, validTypeIds []int, err error) {
	var permissionIds []int
	var validPermissionIds []int //最后允许显示的章节
	if productAuthOk {
		permissionIds, err = chart_permission_chapter_mapping.GetPermissionIdsByWeek()
		if err != nil && err.Error() != utils.ErrNoRow() {
			return
		}
	}
	authOk, permissionCheckInfo, validPermissionIds, err = company.GetCheckPermission(userInfo.CompanyId, int(userInfo.UserId), permissionIds)
	if err != nil {
		return
	}
	//返回可用的章节列表
	if len(validPermissionIds) > 0 {
		validTypeIds, err = chart_permission_chapter_mapping.GetReportChapterTypeIdsByPermissionIds(validPermissionIds, "week")
	}
	return
}

// CheckReportPermission 验证用户查看报告的权限
func CheckReportPermission(userInfo *wx_user.WxUser, reportId int, productAuthOk bool) (authOk bool, permissionCheckInfo reportResp.PermissionCheckInfo, err error) {
	var permissionIds []int
	if productAuthOk {
		permissionIds, err = chart_permission_chapter_mapping.GetPermissionIdsByReportId(reportId, "rddp")
		if err != nil && err.Error() != utils.ErrNoRow() {
			return
		}
	}
	authOk, permissionCheckInfo, _, err = company.GetCheckPermission(userInfo.CompanyId, int(userInfo.UserId), permissionIds)
	return
}

// GetTickerData 获取指标数据
func GetTickerData(reportChapterId int) (ret reportResp.TickerData, err error, errMsg string) {
	defer func() {
		if err != nil {
			utils.FileLog.Critical(fmt.Sprintf("GetTickerData:  err:%s， errMsg:%s", err.Error(), errMsg))
		}
	}()

	//查询章节类型
	chapter, err := report_chapter.GetTypeIdById(reportChapterId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询章节失败")
		return
	}

	if chapter.ReportChapterId == 0 {
		err = errors.New("章节不存在或者未发布")
		return
	}

	tickers, err := report_chapter_ticker.GetTickerByChapterId(reportChapterId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询章节指标失败")
		return
	}

	var list []reportResp.TickerDataItem
	if len(tickers) > 0 {
		var tickerNames []string
		for _, v := range tickers {
			tickerNames = append(tickerNames, v.Ticker)
		}
		var dataList []*daily_base_column.TickerDataItem
		if chapter.TypeId == 17 {
			dataList, err = daily_base_column.GetDataByBaseColumnTickers17(tickerNames)
		} else {
			dataList, err = daily_base_column.GetDataByBaseColumnTickers(tickerNames)
		}

		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询指标数据失败")
			return
		}
		chapterTypeInfo, tErr := report_chapter_type.GetTickerTitleByTypeId(chapter.TypeId)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询章节类型失败")
			return
		}
		if len(dataList) >= 0 {
			for _, v := range dataList {
				temp := reportResp.TickerDataItem{
					Date:           v.Date,
					Ticker:         v.Ticker,
					BaseColumnName: v.BaseColumnName,
				}
				temp.TickerValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.TickerValue), 2)
				temp.LastValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.LastValue), 2)
				temp.MmValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.MmValue), 2)
				temp.DdValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.DdValue), 2)
				temp.WwValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.WwValue), 2)

				list = append(list, temp)
			}
		}

		tickerTitle := reportResp.TickerTitleData{
			TickerTitle:           chapterTypeInfo.TickerTitle,
			ReportChapterTypeId:   int(chapterTypeInfo.ReportChapterTypeId),
			ReportChapterTypeName: chapterTypeInfo.ReportChapterTypeName,
			DataTableImage:        fmt.Sprintf("http://hongze.oss-cn-shanghai.aliyuncs.com/data_table/%s.png", chapterTypeInfo.ReportChapterTypeKey),
		}

		ret = reportResp.TickerData{
			List:        list,
			TickerTitle: tickerTitle,
		}
	}
	return
}
