package report

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/tables/company"
	"hongze/hongze_yb/models/tables/company_report_permission"
	"hongze/hongze_yb/models/tables/research_report"
	"hongze/hongze_yb/models/tables/research_report_type"
	"hongze/hongze_yb/models/tables/user_view_history"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/utils"
	"strconv"
	"time"
)

type ResearchReportInfo struct {
	//ResearchReportInfo            *research_report.ResearchReport                     `json:"research_report_info"`
	ResearchReportInfo            *ResearchReportShow                                 `json:"research_report_info"`
	ResearchReportTypeList        []*company_report_permission.ResearchReportTypeList `json:"research_report_type_list"`
	HasMenu                       int                                                 `json:"has_menu"`
	ResearchReportTypeContentList []*research_report.ResearchReportTypeContent        `description:"报告详情"`
	LikeNum                       int64                                               `description:"点赞总数" json:"like_num"`
	LikeEnabled                   int8                                                `description:"是否已点赞： 0-未点赞 1-已点赞" json:"like_enabled"`
}

type ResearchReportShow struct {
	ResearchReportID    uint64 `json:"researchReportId"`    // 研究报告id
	ResearchReportName  string `json:"researchReportName"`  // 研究报告名称
	ResearchReportTitle string `json:"researchReportTitle"` // 研究报告标题
	ResearchReportImg   string `json:"researchReportImg"`   // 报告缩略图URL
	ResearchReportDate  string `json:"researchReportDate"`  // 报告日期
	Type                string `json:"type"`                // day 晨报  week 周报 twoweek双周报 month 月报
	Author              string `json:"author"`              // 报告作者
	ReportVariety       string `json:"reportVariety"`       // 研究报告的品种，双周报和月报有标识
	IsHasMenu           int8   `json:"isHasMenu"`           // 报告是否含有目录
	IsSendedMsg         int8   `json:"isSendedMsg"`         // 是否发送过模板消息
	Periods             int    `json:"periods"`             // 期数
	Status              string `json:"status"`              // 状态，draft：草稿，
	Enabled             int8   `json:"enabled"`             // 报告状态
	CreatedTime         string `json:"createdTime"`         // 创建时间
	LastUpdatedTime     string `json:"lastUpdatedTime"`     // 最后更新时间
	Viewers             int    `json:"viewers"`             // H5观看用户数
}

// GetResearchReportInfo 获取报告详情
func GetResearchReportInfo(researchReportId, userId uint64) (result ResearchReportInfo, hasPermission bool, err error) {
	//获取报告详情
	reportInfo, err := research_report.GetByResearchReportId(researchReportId)
	if err != nil {
		return
	}
	reportType := reportInfo.Type
	//这些个报告需要做权限校验

	if utils.InArray(reportInfo.Type, []string{"month", "two_week", "other"}) {
		list, tmpErr := company_report_permission.GetReportVarietyList(userId, reportType)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list {
			if reportInfo.ResearchReportID == v.ReportChapterTypeId {
				hasPermission = true
				break
			}
		}
		if !hasPermission {
			//permissionName, tmpErr := company_report_permission.GetPermissionNameByReportId(reportInfo.ResearchReportID, reportType)
			//if tmpErr != nil {
			//	err = tmpErr
			//	return
			//}
			return
		}
	} else {
		hasPermission = true
	}

	researchReportTypeList := make([]*company_report_permission.ResearchReportTypeList, 0)
	tmpResearchReportTypeList, err := company_report_permission.GetResearchReportType(reportInfo.ResearchReportID, userId, reportInfo.Type)
	if err != nil {
		return
	}
	reportDate := reportInfo.ResearchReportDate
	for _, v := range tmpResearchReportTypeList {
		if reportDate.Before(v.PauseStartTime) || reportDate.After(v.PauseEndTime) {
			researchReportTypeList = append(researchReportTypeList, v)
		}
	}

	// 联系人信息
	strInt64 := strconv.FormatUint(userId, 10)
	id, _ := strconv.Atoi(strInt64)
	wxUserInfo, err := wx_user.GetByUserId(id)
	if err != nil {
		fmt.Println("GetByUserId:", err.Error())
		return
	}
	companyInfo, tmpErr := company.GetByCompanyId(wxUserInfo.CompanyID)
	if tmpErr != nil {
		err = tmpErr
		if tmpErr == utils.ErrNoRow {
			err = errors.New("找不到该客户")
			return
		}
		return
	}

	//查询是否读过这篇报告，如果未读过则阅读人数+1
	_, err = user_view_history.GetReportByUserId(userId, reportInfo.ResearchReportID)
	if err != nil {
		err = reportInfo.UpdateViewers()
		if err != nil {
			fmt.Println("UpdateViewers err:", err.Error())
		}
	}

	//新增userViewHistory记录
	userViewHistory := &user_view_history.UserViewHistory{
		ViewHistoryID:        0,
		UserID:               userId,
		Mobile:               wxUserInfo.Mobile,
		Email:                wxUserInfo.Email,
		RealName:             wxUserInfo.RealName,
		CompanyName:          companyInfo.CompanyName,
		ViewTitle:            "",
		ViewPage:             "",
		ReportChapterModule:  "",
		CreatedTime:          time.Now(),
		LastUpdatedTime:      time.Now(),
		Type:                 "weekly_report",
		ResearchReportID:     reportInfo.ResearchReportID,
		ResearchReportTypeID: 0,
	}
	err = userViewHistory.AddUserViewHistory()
	if err != nil {
		fmt.Println("AddUserViewHistory err", err.Error())
	}

	//添加阅读日志的数据加入到redis
	go PushViewRecordNewRedisData(userViewHistory, int(wxUserInfo.CompanyID))

	//查询点赞数
	likeNum, likeEnabled, _ := services.GetReportLikeByReportIdOldReportId(wxUserInfo.UserID, 0, 0, int(researchReportId), 0)

	reportInfoShow := &ResearchReportShow{
		ResearchReportID:    reportInfo.ResearchReportID,
		ResearchReportName:  reportInfo.ResearchReportName,
		ResearchReportTitle: reportInfo.ResearchReportTitle,
		ResearchReportImg:   reportInfo.ResearchReportImg,
		ResearchReportDate:  reportInfo.ResearchReportDate.Format(utils.FormatDate),
		Type:                reportInfo.Type,
		Author:              reportInfo.Author,
		ReportVariety:       reportInfo.ReportVariety,
		IsHasMenu:           reportInfo.IsHasMenu,
		IsSendedMsg:         reportInfo.IsSendedMsg,
		Periods:             reportInfo.Periods,
		Status:              reportInfo.Status,
		Enabled:             reportInfo.Enabled,
		CreatedTime:         reportInfo.CreatedTime.Format(utils.FormatDateTime),
		LastUpdatedTime:     reportInfo.LastUpdatedTime.Format(utils.FormatDateTime),
		Viewers:             reportInfo.Viewers,
	}

	result = ResearchReportInfo{
		ResearchReportInfo:     reportInfoShow,
		ResearchReportTypeList: researchReportTypeList,
		HasMenu:                1,
		LikeNum:                likeNum,
		LikeEnabled:            likeEnabled,
	}

	if len(researchReportTypeList) <= 0 {

	} else if len(researchReportTypeList) == 1 {
		//只有一个章节，即没有目录的时候，需要直接返回章节详情
		result.HasMenu = 0
		researchReportTypeContent, tmpErr := research_report.GetResearchReportTypeContentList(researchReportTypeList[0].ResearchReportTypeId)
		if tmpErr != nil {
			return
		}
		result.ResearchReportTypeContentList = researchReportTypeContent
	}
	return
}

type ResearchReportTypeContentInfo struct {
	ResearchReportTypeInfo        *research_report_type.ResearchReportTypeInfo `json:"research_report_type_info"`
	Add                           int                                          `json:"add"`
	ResearchReportTypeContentList []*research_report.ResearchReportTypeContent `description:"报告详情" json:"research_report_type_content_list"`
	LikeNum                       int64                                        `description:"点赞总数" json:"like_num"`
	LikeEnabled                   int8                                         `description:"是否已点赞： 0-未点赞 1-已点赞" json:"like_enabled"`
}

// GetResearchReportTypeContentInfo 获取报告章节详情
func GetResearchReportTypeContentInfo(researchReportTypeId, userId uint64) (result ResearchReportTypeContentInfo, hasPermission bool, err error) {
	//获取章节详情
	researchReportTypeContentList, err := research_report.GetResearchReportTypeContentList(researchReportTypeId)
	if err != nil {
		return
	}
	researchReportTypeInfo, err := research_report_type.GetResearchReportTypeInfo(researchReportTypeId)
	//获取报告详情
	reportInfo, err := research_report.GetByResearchReportId(researchReportTypeInfo.ResearchReportID)
	if err != nil {
		return
	}
	reportType := reportInfo.Type

	//这些个报告需要做权限校验
	if utils.InArray(reportInfo.Type, []string{"week", "month", "two_week", "other"}) {
		list, tmpErr := company_report_permission.GetReportVarietyList(userId, reportType)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		if reportInfo.Type == "week" {
			//周报校验章节是否在权限内
			for _, v := range list {
				if researchReportTypeInfo.ReportChapterTypeId == v.ReportChapterTypeId {
					hasPermission = true
					break
				}
			}
		} else {
			//双周报和月报校验 类型是否在权限内
			for _, v := range list {
				if reportInfo.ResearchReportID == v.ReportChapterTypeId {
					hasPermission = true
					break
				}
			}
		}

		if !hasPermission {
			//permissionName, tmpErr := company_report_permission.GetPermissionNameByReportId(reportInfo.ResearchReportID, reportType)
			//if tmpErr != nil {
			//	err = tmpErr
			//	return
			//}
			return
		}
	} else {
		hasPermission = true
	}
	add := 1
	if len(researchReportTypeContentList) > 0 {
		add = 0
	}
	// 联系人信息
	strInt64 := strconv.FormatUint(userId, 10)
	id, _ := strconv.Atoi(strInt64)
	wxUserInfo, err := wx_user.GetByUserId(id)
	if err != nil {
		fmt.Println("GetByUserId:", err.Error())
		return
	}
	companyInfo, tmpErr := company.GetByCompanyId(wxUserInfo.CompanyID)
	if tmpErr != nil {
		err = tmpErr
		if tmpErr == utils.ErrNoRow {
			err = errors.New("找不到该客户")
			return
		}
		return
	}

	//新增userViewHistory记录
	userViewHistory := &user_view_history.UserViewHistory{
		ViewHistoryID:        0,
		UserID:               userId,
		Mobile:               wxUserInfo.Mobile,
		Email:                wxUserInfo.Email,
		RealName:             wxUserInfo.RealName,
		CompanyName:          companyInfo.CompanyName,
		ViewTitle:            "",
		ViewPage:             "",
		ReportChapterModule:  "",
		CreatedTime:          time.Now(),
		LastUpdatedTime:      time.Now(),
		Type:                 "weekly_report",
		ResearchReportID:     reportInfo.ResearchReportID,
		ResearchReportTypeID: researchReportTypeId,
	}
	err = userViewHistory.AddUserViewHistory()
	if err != nil {
		fmt.Println("AddUserViewHistory err", err.Error())
	}

	//添加阅读日志的数据加入到redis
	go PushViewRecordNewRedisData(userViewHistory, int(wxUserInfo.CompanyID))

	//查询点赞数
	likeNum, likeEnabled, _ := services.GetReportLikeByReportIdOldReportId(wxUserInfo.UserID, 0, 0, int(researchReportTypeInfo.ResearchReportID), int(researchReportTypeInfo.ResearchReportTypeID))
	result = ResearchReportTypeContentInfo{
		ResearchReportTypeContentList: researchReportTypeContentList,
		ResearchReportTypeInfo:        researchReportTypeInfo,
		Add:                           add,
		LikeNum:                       likeNum,
		LikeEnabled:                   likeEnabled,
	}
	return
}

// UserViewRedisData 阅读数据
type UserViewRedisData struct {
	Mobile          string `json:"mobile"`
	Email           string `json:"email"`
	RealName        string `json:"real_name"`
	CompanyName     string `json:"company_name"`
	ViewTime        string `json:"view_time" description:"阅读时间，格式：2022-02-17 13:06:13"`
	ProductId       int    `json:"product_id" description:"报告所属产品，ficc：1，权益：2"`
	CompanyId       int    `json:"company_id" description:"客户id"`
	UserId          int    `json:"user_id" description:"用户id"`
	ReportId        int    `json:"report_id" description:"报告ID"`
	ReportChapterId int    `json:"report_chapter_id" description:"章节ID"`
	StopTime        int    `json:"stop_time" description:"停留时间"`
	OutId           int    `json:"out_id" description:"章节ID"`
}

// PushViewRecordNewRedisData 阅读数据加入到redis
func PushViewRecordNewRedisData(userViewHistory *user_view_history.UserViewHistory, companyId int) bool {
	data := &UserViewRedisData{
		Mobile:          userViewHistory.Mobile,
		Email:           userViewHistory.Email,
		RealName:        userViewHistory.RealName,
		CompanyName:     userViewHistory.CompanyName,
		ViewTime:        userViewHistory.CreatedTime.Format(utils.FormatDateTime),
		ProductId:       1,
		CompanyId:       companyId,
		UserId:          int(userViewHistory.UserID),
		ReportId:        int(userViewHistory.ResearchReportID),
		ReportChapterId: int(userViewHistory.ResearchReportTypeID),
		OutId:           int(userViewHistory.ViewHistoryID),
	}

	if global.Redis != nil {
		dataStr, _ := json.Marshal(data)
		_, err := global.Redis.LPush(context.TODO(), utils.CACHE_KEY_USER_VIEW, dataStr).Result()
		if err != nil {
			fmt.Println("PushViewRecordNewRedisData LPush Err:" + err.Error())
		}
		return true
	}
	return false
}
