package activity

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/response/purchase"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/research_report"
	"hongze/hongze_yb/models/tables/yb_activity"
	"hongze/hongze_yb/models/tables/yb_activity_permission"
	"hongze/hongze_yb/models/tables/yb_activity_register"
	"hongze/hongze_yb/models/tables/yb_activity_remind"
	"hongze/hongze_yb/models/tables/yb_activity_voice"
	"hongze/hongze_yb/models/tables/yb_config"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"log"
	"strings"
	"time"
)

// ActivityList 活动列表
type ActivityList struct {
	yb_activity.ActivityItem                                      // 活动信息
	VoiceList                []*yb_activity_voice.YbActivityVoice // 音频列表
}

// PageList 活动分页列表
func PageList(condition string, pars []interface{}, page, limit int, order string, userInfo user.UserInfo) (list []ActivityList, err error) {
	activities, err := yb_activity.GetPageListByWhere(condition, pars, page, limit, order, int(userInfo.UserID))
	if err != nil {
		log.Print(err.Error())
		return
	}
	if activities != nil {
		var defaultSpeakerHeadPic string
		// 获取默认演讲人头像
		{
			configCond := `config_code = ?`
			configPars := make([]interface{}, 0)
			configPars = append(configPars, yb_config.DefaultSpeakerHeadPic)
			confOB := new(yb_config.YbConfig)
			conf, e := confOB.Fetch(configCond, configPars)
			if e != nil {
				err = e
				return
			}
			defaultSpeakerHeadPic = conf.ConfigValue
		}

		var activityIds []int
		for _, item := range activities {
			activityIds = append(activityIds, item.ActivityID)
		}

		// 录音
		voices, queryErr := yb_activity_voice.GetVoicesByActivityIds(activityIds)
		if queryErr != nil {
			log.Print(queryErr.Error())
			return
		}
		// 提醒
		reminds, queryErr := yb_activity_remind.GetRemindsByUserIdAndActivityIds(int(userInfo.UserID), activityIds)
		if queryErr != nil {
			log.Print(queryErr.Error())
			return
		}
		remindMap := make(map[int]int, 0)
		for _, remind := range reminds {
			remindMap[remind.ActivityId] = 1
		}
		// 报名
		registers, queryErr := yb_activity_register.GetRegistersByUserIdAndActivityIds(int(userInfo.UserID), activityIds)
		if queryErr != nil {
			log.Print(queryErr.Error())
			return
		}
		registerMap := make(map[int]int, 0)
		for _, register := range registers {
			if register.RegisterState == 1 {
				registerMap[register.ActivityId] = 1
			}
		}

		var temp ActivityList
		for _, activity := range activities {
			temp.ActivityItem = activity
			temp.WeekString = utils.StrDateTimeToWeek(activity.StartTime.Weekday().String())
			temp.ActivityState = getActivityStateByTime(activity.StartTime, activity.EndTime)
			// 音频列表
			var voiceMap []*yb_activity_voice.YbActivityVoice
			for _, voice := range voices {
				if temp.ActivityID == int(voice.ActivityID) {
					voiceMap = append(voiceMap, voice)
					temp.HasPlayBack = 1 // 有回放
				}
			}
			temp.VoiceList = voiceMap
			// 是否有提醒
			_, ok := remindMap[temp.ActivityID]
			if ok {
				temp.HasRemind = 1
			}
			// 是否已报名
			_, ok = registerMap[temp.ActivityID]
			if ok {
				temp.RegisterState = 1
			}
			// 如果是多图，那么是默认头像
			if strings.Count(temp.SpeakerHeadPic, ",") > 0 {
				temp.SpeakerHeadPic = defaultSpeakerHeadPic
			}
			list = append(list, temp)
		}
	}
	return
}

// getActivityStateByTime 根据时间生成活动枚举值
func getActivityStateByTime(startTime, endTime time.Time) (state int) {
	nowTime := time.Now().Format(utils.FormatDateTime)
	timeNow, _ := time.ParseInLocation(utils.FormatDateTime, nowTime, time.Local)
	if timeNow.Before(endTime) && timeNow.After(startTime) {
		// 进行中
		state = 2
	} else if timeNow.After(endTime) {
		// 已结束
		state = 3
	} else if timeNow.Before(startTime) {
		// 未开始
		state = 1
	}
	return
}

// GetActivityDetail 活动详情
func GetActivityDetail(activityId, userId int) (detail *yb_activity.ActivityDetail, err error) {
	detail, err = yb_activity.GetDetailById(activityId)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return
		}
	}
	if detail == nil {
		return
	}
	registeredNum, err := yb_activity_register.CountRegistedNumByActivityId(activityId)
	if err != nil {
		log.Print(err.Error())
		return
	}
	detail.RegisteredNum = int(registeredNum)
	detail.WeekString = utils.StrDateTimeToWeek(detail.StartTime.Weekday().String())
	detail.ActivityState = getActivityStateByTime(detail.StartTime, detail.EndTime)
	_, remindErr := yb_activity_remind.RemindExist(userId, activityId)
	if remindErr != gorm.ErrRecordNotFound {
		detail.HasRemind = 1
	}
	_, registerErr := yb_activity_register.RegisterExist(userId, activityId)
	if registerErr != gorm.ErrRecordNotFound {
		detail.RegisterState = 1
	}
	// 判断报告链接对应的报告发布状态，若为未发布则报告链接置空
	if detail.ReportId > 0 && detail.ReportLink != "" {
		if detail.IsNewReport == 1 {
			// 去新报告表中查询
			newReport, e := report.GetByReportId(detail.ReportId)
			if e != nil {
				err = errors.New("获取新报告详情失败, Err: " + e.Error())
				return
			}
			if newReport.State != 2 && newReport.State != 6 {
				detail.ReportLink = ""
			}
		} else {
			// 查询老报告表
			oldReport, e := research_report.GetByResearchReportId(uint64(detail.ReportId))
			if e != nil {
				err = errors.New("获取老报告详情失败, Err: " + e.Error())
				return
			}
			if oldReport.Status != "report" {
				detail.ReportLink = ""
			}
		}
	}

	return
}

// CheckActivityPermission 验证用户的活动参与权限
func CheckActivityPermission(userInfo user.UserInfo, activityId int) (ok bool, permissionCheckInfo company.PermissionCheckInfo, err error) {
	companyId := userInfo.CompanyID
	activity, err := yb_activity.GetOneById(activityId)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return
		}
	}
	if activity == nil {
		return
	}
	// 查询活动权限集合
	permissions, err := yb_activity_permission.GetPermissionsByActivityId(activityId)
	if err != nil {
		return
	}
	var permissionIds []int
	for _, item := range permissions {
		pid := int(item.PermissionID)
		permissionIds = append(permissionIds, pid)
	}
	ok, permissionCheckInfo, err = company.CheckPermissionByPermissionIdList2Ficc(companyId, int(userInfo.UserID), permissionIds)
	return
}

// GetUserAuthActivityIds 获取用户有权限参与的活动Ids
func GetUserAuthActivityIds(userInfo user.UserInfo) (acrivityIds []int, err error) {
	productId := 1
	// 查询用户产品状态是否正常
	companyProduct, err := company_product.GetByCompany2ProductId(userInfo.CompanyID, int64(productId))
	if err != nil {
		return
	}
	statusMatch := "正式,试用,永续"
	if !strings.Contains(statusMatch, companyProduct.Status) || companyProduct.IsSuspend == 1 {
		acrivityIds = append(acrivityIds, 0)
		return
	}
	// 获取用户有效权限
	validPermissionIdList, err := company.GetValidPermissionIdListByCompany2ProductId(userInfo.CompanyID, int64(productId))
	if err != nil {
		return
	}
	// 获取用户权限可参与的活动ID
	permissions, err := yb_activity_permission.GetPermissionsByPermissionIds(validPermissionIdList)
	if err != nil {
		return
	}
	for _, v := range permissions {
		acrivityIds = append(acrivityIds, int(v.ActivityID))
	}

	return
}

// GetLatestActivity 从用户有权限参与的活动中，筛选出最新的活动
func GetLatestActivity(permissionIds []int, userId uint64) (purchaseItem *purchase.PurchaseListItem, err error) {
	var errMsg string
	defer func() {
		if sysErr := recover(); sysErr != nil {
			err = errors.New("系统错误")
			global.LOG.Critical(fmt.Sprintf("GetLatestClassReport: userId=%d, err:%s，sysErr:%s", userId, err.Error(), sysErr))
		}
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetLatestClassReport: userId=%d, err:%s， errMsg:%s", userId, err.Error(), errMsg))
		}
	}()
	// 获取用户权限可参与的活动ID
	var activityIds []int
	permissions, err := yb_activity_permission.GetPermissionsByPermissionIds(permissionIds)
	if err != nil {
		return
	}
	for _, v := range permissions {
		activityIds = append(activityIds, int(v.ActivityID))
	}

	activityItem, err := yb_activity.GetLatestByIds(activityIds)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询活动错误")
		return
	}
	//统计未读数
	unRead, err := GetUnRead(activityIds, userId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询活动未读数错误")
		return
	}
	purchaseItem = new(purchase.PurchaseListItem)
	if activityItem.ActivityID > 0 {
		purchaseItem.ActivityId = activityItem.ActivityID
		purchaseItem.Title = activityItem.ActivityName
		purchaseItem.Content = fmt.Sprintf("主讲：%s", activityItem.Speaker)
		purchaseItem.Time = activityItem.ModifyTime
		purchaseItem.Unread = unRead
		// 添加活动icon
		purchaseItem.ImgUrl = utils.ALIYUN_YBIMG_HOST + "purchase_icon_xj_two_week.png"
	}
	return
}

// GetList 从用户有权限参与的活动中，筛选出最新的活动
func GetPurchaseDetail(permissionIds []int, userId uint64, pageIndex, pageSize int) (ret *purchase.DetailResp, err error) {
	// 获取用户权限可参与的活动ID
	var activityIds []int
	permissions, err := yb_activity_permission.GetPermissionsByPermissionIds(permissionIds)
	if err != nil {
		return
	}
	for _, v := range permissions {
		activityIds = append(activityIds, int(v.ActivityID))
	}
	offset := (pageIndex - 1) * pageSize
	activityList, err := yb_activity.GetListByIds(activityIds, offset, pageSize)
	if err != nil {
		return
	}

	total, err := yb_activity.GetListCountByIds(activityIds)
	if err != nil {
		return
	}
	var WeekDayMap = map[string]string{
		"Monday":    "周一",
		"Tuesday":   "周二",
		"Wednesday": "周三",
		"Thursday":  "周四",
		"Friday":    "周五",
		"Saturday":  "周六",
		"Sunday":    "周日",
	}

	ret = new(purchase.DetailResp)
	var list []*purchase.Detail
	for _, item := range activityList {
		temp := new(purchase.Detail)
		temp.ActivityId = item.ActivityID
		temp.Title = fmt.Sprintf("主讲：%s", item.Speaker)
		// 时间处理
		activityDate := item.StartTime.Format("2006-01-02")
		activityStart := item.StartTime.Format("15:04")
		activityEnd := item.EndTime.Format("15:04")
		activityWeek := item.StartTime.Weekday().String()
		weekStr := WeekDayMap[activityWeek]
		timeStr := activityDate + " " + activityStart + "-" + activityEnd + " " + weekStr
		temp.Content = fmt.Sprintf("活动时间：%s", timeStr)
		temp.Time = item.ModifyTime
		temp.TopName = item.ActivityName
		temp.ImgUrl = utils.ALIYUN_YBIMG_HOST + "purchase_bg_activity.png"
		list = append(list, temp)
	}
	ret.List = list
	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	num, tErr := BatchInsertActivityView(activityIds, userId)
	log.Printf("新增活动浏览记录：%d", num)
	if tErr != nil {
		err = tErr
		return
	}
	return
}
