package roadshow

import (
	"fmt"
	"hongze/hz_crm_api/models/roadshow"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

func SetPublicMeetingUnionCode() (err error) {
	fmt.Println("start SetPublicMeetingUnionCode" + time.Now().Format(utils.FormatDateTime))
	now := time.Now().AddDate(-1, 0, 0).Format(utils.FormatDate)
	//清空现有分组
	err = roadshow.ClearCalendarUnionCode(now)
	if err != nil {
		return
	}
	list, err := roadshow.GetPublicMeetingList(now)
	if err != nil {
		return
	}
	for _, v := range list {
		calendarResearchItem, err := roadshow.GetRsCalendarById(v.RsCalendarId)
		if err != nil {
			fmt.Println("GetRsCalendarById Err:" + err.Error())
			return err
		}
		if calendarResearchItem == nil {
			continue
		}
		if calendarResearchItem.UnionCode != "" {
			continue
		}
		startDateTime := v.MinTime
		endDateTime := v.MaxTime

		var unionCode string
		unionCodeStr := strconv.Itoa(v.RsCalendarId) + "_" + strconv.Itoa(int(time.Now().Unix()))
		unionCode = utils.MD5(unionCodeStr)

		err = roadshow.ModifyCalendarUnionCode(unionCode, v.RsCalendarId)
		if err != nil {
			fmt.Println("ModifyCalendarUnionCode Err:" + err.Error())
			return err
		}
		fmt.Println("SetCoincideMeeting:", startDateTime, endDateTime)
		SetCoincideMeeting(startDateTime, endDateTime, unionCode)
	}
	fmt.Println("end SetPublicMeetingUnionCode" + time.Now().Format(utils.FormatDateTime))
	return
}

func SetCoincideMeeting(startDateTime, endDateTime, unionCode string) (err error) {
	coincideList, err := roadshow.GetCoincideMeeting(startDateTime, endDateTime)
	if err != nil {
		return err
	}
	for _, cv := range coincideList {
		calendarResearchItem, err := roadshow.GetRsCalendarById(cv.RsCalendarId)
		if err != nil {
			fmt.Println("GetRsCalendarById Err:" + err.Error())
			return err
		}
		if calendarResearchItem == nil {
			continue
		}
		if calendarResearchItem.UnionCode != "" {
			continue
		}
		fmt.Println("RsCalendarId:", cv.RsCalendarId)
		err = roadshow.ModifyCalendarUnionCode(unionCode, cv.RsCalendarId)
		if err != nil {
			fmt.Println("ModifyCalendarUnionCode Err:" + err.Error())
			return err
		}
	}
	minTime, maxTime, err := roadshow.GetCoincideMeetingMinAndMaxTime(startDateTime, endDateTime)
	if minTime == startDateTime && maxTime == endDateTime {
		return err
	} else {
		startDateTime = minTime
		endDateTime = maxTime
		SetCoincideMeeting(startDateTime, endDateTime, unionCode)
	}
	fmt.Println("结束循环")
	fmt.Println(startDateTime, endDateTime, minTime, maxTime)
	return err
}
