package business_trip

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

// BusinessTripCalendar
// @Title 出差日历表
// @Description 出差日历表接口
// @Param   AdminId   query   string  false       "用户id,多个用英文逗号分开"
// @Param   WeekQuery   query   int  false       "周查询: 0-本期(本周及下周); 1-前两周; 2-后两周"
// @Param   BaseQueryDate   query   string  false       "周查询时的开始日期"
// @Success 200 {object} roadshow.BusinessTripResp
// @router /calendar [get]
func (this *BusinessTrip) BusinessTripCalendar() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	adminId := this.GetString("AdminId")
	weekQuery, _ := this.GetInt("WeekQuery")
	baseQueryDate := this.GetString("BaseQueryDate")

	approveAdminId := 66 // 测试、生产都是这个审批人id

	groupList := make([]*business_trip.BusinessTripCalendarGroup, 0)
	researcherGroup := new(business_trip.BusinessTripCalendarGroup)
	researcherGroup.GroupId = 1
	researcherGroup.GroupName = "研究员"
	researcherGroup.DepartmentId = "1"
	groupList = append(groupList, researcherGroup)

	sellerGroup := new(business_trip.BusinessTripCalendarGroup)
	sellerGroup.GroupId = 2
	sellerGroup.GroupName = "销售"
	if utils.RunMode == "debug" {
		sellerGroup.DepartmentId = "2,5"
	} else {
		sellerGroup.DepartmentId = "2,4,5,9"
	}
	groupList = append(groupList, sellerGroup)

	otherGroup := new(business_trip.BusinessTripCalendarGroup)
	otherGroup.GroupId = 3
	otherGroup.GroupName = "其他"
	if utils.RunMode == "debug" {
		otherGroup.DepartmentId = "3,7"
	} else {
		otherGroup.DepartmentId = "3,6,7,8"
	}
	groupList = append(groupList, otherGroup)

	groupLen := len(groupList)

	//fmt.Println("groupLen:", groupLen)

	var nowWeekStart time.Time
	if baseQueryDate == "" {
		now := time.Now()
		weekDay := int(now.Weekday())
		if weekDay == 6 {
			nowWeekStart, _ = time.ParseInLocation(utils.FormatDate, now.Format(utils.FormatDate), time.Local)
		} else {
			nowWeekStart, _ = time.ParseInLocation(utils.FormatDate, now.AddDate(0, 0, -(weekDay+1)).Format(utils.FormatDate), time.Local)
		}
	}
	// 查询需求是可以无限往前后两周查询, 以入参为本周开始日期
	if baseQueryDate != "" {
		t, e := time.ParseInLocation(utils.FormatDate, baseQueryDate, time.Local)
		if e != nil {
			br.Msg = "查询开始日期格式有误"
			return
		}
		nowWeekStart = t
	}

	// 前/后两周
	if weekQuery == 1 {
		nowWeekStart = nowWeekStart.AddDate(0, 0, -14)
	}
	if weekQuery == 2 {
		nowWeekStart = nowWeekStart.AddDate(0, 0, +14)
	}
	//nowWeekEnd := utils.GetNowWeekLastDay()
	//获取基于开始周的下周日期
	nextWeekStart := nowWeekStart.AddDate(0, 0, +7)
	nextWeekEnd := nowWeekStart.AddDate(0, 0, +13)

	//获取出差信息
	businessTripList, err := business_trip.GetBusinessTripList(adminId, nowWeekStart.Format(utils.FormatDate), nextWeekEnd.Format(utils.FormatDate))
	if err != nil {
		br.Msg = "获取信息失败!"
		br.ErrMsg = "获取路演信息失败!,GetBusinessTripList Err:" + err.Error()
		return
	}

	adminIdList := make([]string, 0)
	if adminId != `` {
		adminIdList = strings.Split(adminId, ",")
	}
	lenAdminIdList := len(adminIdList)

	btMap := make(map[int][]business_trip.BusinessApplyView)

	for _, v := range businessTripList {
		fmt.Println(v.ApplyRealName, v.Status, v.ArriveDate, v.ReturnDate, approveAdminId)
		// 只有沛总/admin才需要看 “待审批” 的出差, 但admin无审批权
		if v.Status == `待审批` && (sysUser.AdminId != approveAdminId && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN) {
			continue
		}
		if lenAdminIdList > 0 {
			if utils.InArrayByStr(adminIdList, strconv.Itoa(v.ApplyAdminId)) {
				findValList, ok := btMap[v.ApplyAdminId]
				if !ok {
					findValList = make([]business_trip.BusinessApplyView, 0)
				}
				btMap[v.ApplyAdminId] = append(findValList, *v)
			}
		} else {
			findValList, ok := btMap[v.ApplyAdminId]
			if !ok {
				findValList = make([]business_trip.BusinessApplyView, 0)
			}
			btMap[v.ApplyAdminId] = append(findValList, *v)
		}

		// 如果出差申请已通过,同时存在出行人的情况
		if v.Status == "已通过" && v.PeerPeopleId != `` {
			peerPeopleIdList := strings.Split(v.PeerPeopleId, ",")
			for _, peerPeopleIdStr := range peerPeopleIdList {
				peerPeopleId, err := strconv.Atoi(peerPeopleIdStr)
				if err != nil {
					br.Msg = "获取信息失败!"
					br.ErrMsg = "获取路演信息失败!,随行人异常:" + v.PeerPeopleId + "; Err:" + err.Error()
					return
				}

				// 如果不是筛选,或者,该用户在随行人名单中,那么就插入到数据中
				if lenAdminIdList <= 0 || utils.InArrayByStr(adminIdList, strconv.Itoa(peerPeopleId)) {
					findpeerPeopleValList, peerPeoPleOk := btMap[peerPeopleId]
					if !peerPeoPleOk {
						findpeerPeopleValList = make([]business_trip.BusinessApplyView, 0)
					}
					btMap[peerPeopleId] = append(findpeerPeopleValList, *v)
				}
			}
		}
	}

	for i := 0; i < groupLen; i++ {
		group := groupList[i]
		fmt.Println("group:", group.DepartmentId)

		adminList, err := business_trip.GetBusinessTripCalendar(group.DepartmentId)
		if err != nil {
			br.Msg = "获取信息失败!"
			br.ErrMsg = "获取分组信息失败!,GetBusinessTripCalendar Err:" + err.Error()
			return
		}

		setAdminList := make([]*business_trip.BusinessTripCalendarAdmin, 0)

		for _, v := range adminList {
			if findTripList, ok := btMap[v.AdminId]; ok {
				tripList := make([]*business_trip.BusinessTripCalendar, 0)
				for day := 0; day < 7; day++ {
					newDay, _ := time.ParseInLocation(utils.FormatDate, nowWeekStart.AddDate(0, 0, day).Format(utils.FormatDate), time.Local)
					weekDate := newDay.Format(utils.FormatDate)

					tripItem := new(business_trip.BusinessTripCalendar)
					for _, r := range findTripList {
						startDateT, _ := time.ParseInLocation(utils.FormatDate, r.ArriveDate, time.Local)
						endDateT, _ := time.ParseInLocation(utils.FormatDate, r.ReturnDate, time.Local)
						if r.BusinessApplyId > 0 && (newDay.Equal(startDateT) || (newDay.Equal(endDateT)) || (newDay.Before(endDateT) && newDay.After(startDateT))) {
							tripItem.City = r.City
							tripItem.BusinessApplyId = r.BusinessApplyId
							tripItem.Status = r.Status
							tripItem.Reason = r.Reason
						}
					}

					tripItem.WeekDate = weekDate
					tripItem.WeekType = "current"
					tripItem.Week = newDay.Weekday().String()
					tripList = append(tripList, tripItem)
				}

				for day := 0; day < 7; day++ {
					newDay := nextWeekStart.AddDate(0, 0, day)
					weekDate := newDay.Format(utils.FormatDate)

					tripItem := new(business_trip.BusinessTripCalendar)
					for _, r := range findTripList {
						startDateT, _ := time.ParseInLocation(utils.FormatDate, r.ArriveDate, time.Local)
						endDateT, _ := time.ParseInLocation(utils.FormatDate, r.ReturnDate, time.Local)

						if r.BusinessApplyId > 0 && (newDay.Equal(startDateT) || (newDay.Equal(endDateT)) || (newDay.Before(endDateT) && newDay.After(startDateT))) {
							tripItem.City = r.City
							tripItem.BusinessApplyId = r.BusinessApplyId
							tripItem.Status = r.Status
							tripItem.Reason = r.Reason
						}
					}
					tripItem.WeekDate = weekDate
					tripItem.WeekType = "next"
					tripItem.Week = newDay.Weekday().String()
					tripList = append(tripList, tripItem)
				}
				v.BusinessTripList = tripList
				setAdminList = append(setAdminList, v)
			}
		}
		groupList[i].AdminList = setAdminList
	}
	resp := new(business_trip.BusinessTripCalendarResp)
	resp.GroupList = groupList
	resp.BaseDate = nowWeekStart.Format(utils.FormatDate)
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
	return
}