package report

import (
	"errors"
	"fmt"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/chart_permission_search_key_word_mapping"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/classify"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"sort"
	"strings"
)

// GetClassListByClassifyId 专栏详情：查询二级分类列表
func GetClassListByClassifyId(user user.UserInfo, classifyIdFirst int) (list []*response.ClassifyListItem, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetClassListByClassifyName: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	classifyInfo, err := classify.GetByClassifyId(classifyIdFirst)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}

	if classifyInfo.Id == 0 {
		err = errors.New("分类不存在")
		return
	}

	if classifyInfo.ParentId != 0 {
		err = errors.New("不允许查询二级分类")
		return
	}

	classifyList, err := classify.GetListByPid(classifyInfo.Id)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("二级分类查询出错")
		return
	}
	var secondIds []int
	for _, v := range classifyList {
		secondIds = append(secondIds, v.Id)
	}

	//查询二级分类中最新的报告ID
	reportList, err := report.GetLatestReportsByClassifyIdFirst(classifyIdFirst, secondIds)
	if err != nil && err != utils.ErrNoRow {
		errMsg = err.Error()
		err = errors.New("报告查询出错")
		return
	}

	reportMap := make(map[int]*report.Report)
	for _, v := range reportList {
		reportMap[v.ClassifyIdSecond] = v
	}
	for _, item := range classifyList {
		temp := new(response.ClassifyListItem)
		temp.ClassifyIdSecond = item.Id
		temp.ParentId = item.ParentId
		temp.AuthorDescript = item.AuthorDescript
		temp.Abstract = item.Abstract
		temp.ReportAuthor = item.ReportAuthor
		temp.HomeImgUrl = item.AvatarImgUrl // 此处图片用二级分类的"头像"
		temp.ClassifyNameSecond = item.ClassifyName
		temp.VipTitle = item.VipTitle
		if classifyInfo.ClassifyName == "权益研报" {
			temp.ProductName = "权益"
		} else {
			temp.ProductName = "FICC"
		}
		// 专栏下无报告则不展示
		if _, ok := reportMap[item.Id]; ok {
			list = append(list, temp)
			temp.Stage = reportMap[item.Id].Stage
		}
	}
	return
}

func GetClassifyDetail(user user.UserInfo, classifyIdSecond int) (detail *response.ClassifyDetail, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetClassifyDetail: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	classifyInfo, err := classify.GetByClassifyId(classifyIdSecond)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}

	if classifyInfo.Id == 0 {
		err = errors.New("分类不存在")
		return
	}
	if classifyInfo.ParentId == 0 {
		err = errors.New("只允许查询二级分类")
		return
	}
	//查询权限, 查询当前分类下的最新的报告，
	permissionIds, err := chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(classifyIdSecond)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类权限查询出错")
		return
	}
	authOk, permissionCheckInfo, _, err := company.GetCheckPermission(user.CompanyID, int(user.UserID), permissionIds)
	if err != nil && err != utils.ErrNoRow {
		errMsg = err.Error()
		err = errors.New("权限查询出错")
		return
	}

	detail = new(response.ClassifyDetail)
	detail.ClassifyIdSecond = classifyInfo.Id
	detail.ParentId = classifyInfo.ParentId
	detail.AuthorDescript = classifyInfo.AuthorDescript
	detail.ReportAuthor = classifyInfo.ReportAuthor
	detail.AvatarImgUrl = classifyInfo.AvatarImgUrl
	detail.ClassifyNameSecond = classifyInfo.ClassifyName
	detail.Abstract = classifyInfo.Abstract
	detail.Descript = classifyInfo.Descript
	detail.VipTitle = classifyInfo.VipTitle
	detail.PermissionCheck = &permissionCheckInfo
	detail.AuthOk = authOk

	return
}

// GetClassifyReportList 查询二级分类下的报告列表
func GetClassifyReportList(user user.UserInfo, classifyIdSecond int, pageIndex, pageSize int) (list *response.ClassReportList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetClassifyDetail: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	// 判断用户状态是否是正常和永续和试用
	var productAuthOk bool
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err == utils.ErrNoRow {
		err = nil
	}
	if err != nil {
		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
			}
		}
	}
	classifyInfo, err := classify.GetByClassifyId(classifyIdSecond)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}

	if classifyInfo.Id == 0 {
		err = errors.New("分类不存在")
		return
	}
	if classifyInfo.ParentId == 0 {
		err = errors.New("只允许查询二级分类")
		return
	}
	//查询权限, 查询当前分类下的最新的报告，
	var permissionIds []int
	if productAuthOk {
		permissionIds, err = chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(classifyIdSecond)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("分类权限查询出错")
			return
		}
	}
	authOk, permissionCheckInfo, _, err := company.GetCheckPermission(user.CompanyID, int(user.UserID), permissionIds)
	if err != nil && err != utils.ErrNoRow {
		errMsg = err.Error()
		err = errors.New("权限查询出错")
		return
	}
	//查询 report列表
	offset := (pageIndex - 1) * pageSize
	reportList, err := report.GetListByClassifyIdSecond(classifyIdSecond, offset, pageSize)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询报告列表出错")
		return
	}
	total, err := report.GetListCountByClassifyIdSecond(classifyIdSecond)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询报告总数出错")
		return
	}

	var newList []*response.ClassReportListItem
	if len(reportList) > 0 {
		for _, reportInfo := range reportList {
			reportItem := new(response.ClassReportListItem)
			reportItem.ReportId = reportInfo.Id
			reportItem.Title = reportInfo.Title
			reportItem.PublishTime = reportInfo.PublishTime
			reportItem.ClassifyNameFirst = reportInfo.ClassifyNameFirst
			reportItem.ClassifyIdFirst = reportInfo.ClassifyIdFirst
			reportItem.ClassifyIdSecond = reportInfo.ClassifyIdSecond
			reportItem.ClassifyNameSecond = reportInfo.ClassifyNameSecond
			reportItem.Stage = reportInfo.Stage
			reportItem.Abstract = reportInfo.Abstract
			if reportInfo.Abstract != "" {
				reportItem.Abstract = "<div style=\"overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">" + reportInfo.Abstract + "</div>"
			}
			reportItem.Author = classifyInfo.ReportAuthor
			reportItem.ReportImgUrl = classifyInfo.AvatarImgUrl // 此处图片用二级分类的"头像"
			reportItem.VideoName = reportInfo.VideoName
			reportItem.VideoPlaySeconds = reportInfo.VideoPlaySeconds
			if reportInfo.VideoUrl != "" && reportInfo.VideoName == "" {
				reportItem.VideoName = reportInfo.Title
			}
			if authOk {
				reportItem.VideoUrl = reportInfo.VideoUrl
			}
			newList = append(newList, reportItem)
		}
	}
	list = new(response.ClassReportList)
	list.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	list.List = newList
	list.PermissionCheck = &permissionCheckInfo
	list.AuthOk = authOk

	return
}

// GetClassifySecondSimpleList 获取二级分类简写名称列表
func GetClassifySecondSimpleList(user user.UserInfo, classifyIdFirst int) (list []*response.ClassifySimpleListItem, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetClassifySecondSimpleList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	classifyParent, err := classify.GetByClassifyId(classifyIdFirst)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}
	if classifyParent.Id == 0 {
		err = errors.New("该分类不存在")
		return
	}

	simpleList, err := classify.GetListByPid(classifyIdFirst)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("二级分类查询出错")
		return
	}

	if len(simpleList) > 0 {
		for _, item := range simpleList {
			if item.ClassifyName == classifyParent.ClassifyName && len(simpleList) == 1 {
				break
			}
			temp := new(response.ClassifySimpleListItem)
			temp.ClassifyIdSecond = item.Id
			temp.ClassifyNameSecond = item.ClassifyName
			if index := strings.Index(item.ClassifyName, "双周报"); index > 0 {
				temp.ClassifySecondNameSimple = item.ClassifyName[0:index]
			} else if item.ClassifyName == "纺织服装与商品价格" {
				temp.ClassifySecondNameSimple = "纺织服装"
			} else {
				temp.ClassifySecondNameSimple = item.ClassifyName
			}

			list = append(list, temp)
		}
	}

	return
}

// GetClassifyFirstList 获取一级分类列表
func GetClassifyFirstList(user user.UserInfo) (resp response.ClassifyFirstList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetClassifyFirstList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	classifyParents, err := classify.GetParentList()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}
	if len(classifyParents) == 0 {
		err = errors.New("分类不存在")
		return
	}
	classifyIconMap := make(map[string]string)
	classifySortMap := make(map[string]int)
	for _, v := range classifyParents {
		classifyIconMap[v.ClassifyName] = v.YbFiccIcon
		classifySortMap[v.ClassifyName] = v.YbFiccSort
	}
	var list response.ClassifyFirstList
	for _, item := range classifyParents {
		temp := new(response.ClassifyFirstListItem)
		temp.ClassifyIdFirst = item.Id
		temp.ClassifyNameFirst = item.ClassifyName
		temp.IconImgUrl = classifyIconMap[item.ClassifyName]
		temp.Sort = classifySortMap[item.ClassifyName]
		//if temp.Sort == 0 {
		//	continue
		//}
		// ShowType展示类型：1-列表 2-专栏 3-品种; RedirectType跳转类型：1-专栏列表 2-报告列表 3-专栏详情 4-品种类型列表
		temp.RedirectType = 2
		if item.ShowType == 2 {
			temp.RedirectType = 1
			classifyChild, _ := classify.GetChildByPid(item.Id)
			if classifyChild != nil && len(classifyChild) == 1 {
				// 存在二级分类且仅有一个时直接跳转专栏详情
				temp.ClassifyIdSecond = classifyChild[0].Id
				temp.ClassifyNameSecond = classifyChild[0].ClassifyName
				temp.RedirectType = 3
			}
		} else if item.ShowType == 3 {
			temp.RedirectType = 4
		}
		list = append(list, temp)
	}
	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err == utils.ErrNoRow {
		err = nil
	}
	if err != nil && err != utils.ErrNoRow {
		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
			}
		}
	}

	// 获取有效的权限id列表
	var validPermissionIdList []int
	//var allClassifySecondIds []int
	if productAuthOk {
		validPermissionIdList, err = company.GetValidPermissionIdListByCompany2ProductId(user.CompanyID, 1)
		if err != nil && err != utils.ErrNoRow {
			errMsg = err.Error()
			err = errors.New("查询分类出错")
			return
		}
	}

	//classifyNames, err := chart_permission_search_key_word_mapping.GetKeyWordsByChartPermissionByIds(validPermissionIdList)
	//if err != nil {
	//	errMsg = err.Error()
	//	err = errors.New("查询权限对应的分类出错")
	//	return
	//}
	//
	//if len(classifyNames) > 0 {
	//	allClassifySecondIds, err = classify.GetSecondIdsByClassifyNames(classifyNames)
	//	if err != nil {
	//		errMsg = err.Error()
	//		err = errors.New("查询分类出错")
	//		return
	//	}
	//}
	for _, item := range list {
		//无权限用户关闭品种类别入口
		if item.RedirectType == 4 && !productAuthOk {
			continue
		}

		//只有宏观经济权限的用户关闭品种类别入口
		if len(validPermissionIdList) == 1 && validPermissionIdList[0] == 1 && item.RedirectType == 4 {
			continue
		}

		resp = append(resp, item)
	}

	if len(resp) > 0 {
		sort.Sort(resp)
	}

	return
}
