package services

import (
	"errors"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"time"
)

//我的日程 GetScheduleAndSpecilList
func GetScheduleAndSpecilList(user *models.WxUserItem, condition string, startSize, pageSize int) (items []*models.ActivityDetail, err error) {
	var conditionSpecil string
	var pars, parsSpecil []interface{}
	condition += ` AND my.user_id = ?`
	pars = append(pars, user.UserId)
	conditionSpecil += ` AND my.user_id = ? AND my.is_cancel = 0 `
	parsSpecil = append(parsSpecil, user.UserId)
	list, e := models.GetScheduleAndSpecilList(condition, pars, conditionSpecil, parsSpecil, startSize, pageSize)
	if e != nil {
		err = errors.New("GetScheduleAndSpecilList, Err: " + e.Error())
		return
	}
	var activityIds []int
	var activitySpecilalIds []int
	for k, v := range list {
		if v.SourceType == 2 {
			activitySpecilalIds = append(activitySpecilalIds, v.ActivityId)
			//把专项调研的线下改为活动的线下类型
			if v.ActivityType == 2 {
				list[k].ActivityType = 0
			}
			list[k].IsShowSignup = true
		} else {
			activityIds = append(activityIds, v.ActivityId)
		}
	}
	//处理活动
	if len(activityIds) > 0 {
		//处理用户是否报名
		mapSignUp, e := GetActivitySignUpUserMap(activityIds, user)
		if e != nil {
			err = errors.New("GetActivitySignUpUserMap, Err: " + e.Error())
			return
		}
		for k, v := range list {
			if v.SourceType != 2 {
				if _, ok := mapSignUp[v.ActivityId]; ok {
					list[k].IsSignup = 1
				}
			}
		}
		//处理用户是否预约纪要
		mapAppointment, e := GetActivityAppointmentUserMap(activityIds, user)
		if e != nil {
			err = errors.New("GetActivityAppointmentUserMap, Err: " + e.Error())
			return
		}
		for k, v := range list {
			if v.SourceType != 2 {
				if _, ok := mapAppointment[v.ActivityId]; ok {
					list[k].IsAppointment = 1
				}
			}
		}
		//处理用户是否预约会议提醒
		mapReminder, e := GetActivityReminderUserMasp(activityIds, user)
		if e != nil {
			err = errors.New("GetActivityReminderUserMasp, Err: " + e.Error())
			return
		}
		for k, v := range list {
			if v.SourceType != 2 {
				if _, ok := mapReminder[v.ActivityId]; ok {
					list[k].IsCancelMeetingReminder = 1
				}
			}
		}
	}

	//处理专项产业调研
	if len(activitySpecilalIds) > 0 {
		//处理用户是否报名
		UserMap, e := GetSpecialTripUserMap(activitySpecilalIds, user.UserId)
		if e != nil {
			err = errors.New("GetSpecialTripUserMap, Err: " + e.Error())
			return
		}
		for k, v := range list {
			if v.SourceType == 2 {
				if _, ok := UserMap[v.ActivityId]; ok {
					list[k].IsSignup = 1
				}
			}
		}

		for k, v := range list {
			if v.SourceType == 2 {
				resultTimeStart := utils.StrTimeToTime(v.ActivityTime)  //时间字符串格式转时间格式
				resultTimeEnd := utils.StrTimeToTime(v.ActivityTimeEnd) //时间字符串格式转时间格式
				if resultTimeStart.After(time.Now()) {
					list[k].ActiveState = strconv.Itoa(1)
				} else if time.Now().After(resultTimeEnd) {
					list[k].ActiveState = strconv.Itoa(3)
				} else {
					list[k].ActiveState = strconv.Itoa(2)
				}
			}
		}
	}
	items = list
	return
}
