package services

import (
	"errors"
	"fmt"
	"hongze/hongze_task/models"
	"hongze/hongze_task/utils"
	"strconv"
	"strings"
	"time"
)

//数据录入

//日度消息推送
func FrequencyByDay() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("FrequencyByDay Err:", err.Error())
			utils.FileLog.Info("FrequencyByDay err: %s", err.Error())
		}
	}()
	frequency := "日度"
	items, err := models.GetEdbInfoByFrequency(frequency)
	if err != nil {
		fmt.Println("GetFrequencyByDay err:", err.Error())
		return
	}
	if len(items) <= 0 {
		err = errors.New("没有需要推送的数据")
		return
	}

	for _, v := range items {
		noticeTime := v.NoticeTime
		if noticeTime == "" {
			err = errors.New("NoticeTime 参数错误:NoticeTime is empty ")
			return
		}
		noticeTimeArr := strings.Split(noticeTime, ":")
		if len(noticeTimeArr) < 3 {
			err = errors.New("NoticeTime 参数错误,noticeTime:" + noticeTime)
			return
		}
		noticeHour, err := strconv.Atoi(noticeTimeArr[0])
		if err != nil {
			return err
		}
		noticeMinute, err := strconv.Atoi(noticeTimeArr[1])
		if err != nil {
			return err
		}
		noticeSecond, err := strconv.Atoi(noticeTimeArr[2])
		if err != nil {
			return err
		}

		noticeSecondTotal := noticeHour*3600 + noticeMinute*60 + noticeSecond

		mbefor, _ := time.ParseDuration("-1m")
		mafter, _ := time.ParseDuration("1m")
		nowBefor := time.Now().Add(mbefor)
		nowAfter := time.Now().Add(mafter)
		nowBeforSecond := nowBefor.Hour()*3600 + nowBefor.Minute()*60 + nowBefor.Second()
		nowAfterSecond := nowAfter.Hour()*3600 + nowAfter.Minute()*60 + nowAfter.Second()

		if noticeSecondTotal >= nowBeforSecond && noticeSecondTotal <= nowAfterSecond {
			//获取用户信息
			var openId string
			isAdmin := true
			admin, err := models.GetAdminByAdminId(v.UserId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					isAdmin = false
				} else {
					return err
				}
			}
			if admin == nil {
				isAdmin = false
			}
			if isAdmin {
				if admin.Mobile == "" {

				} else {
					wxUser, err := models.GetWxUserByMobile(admin.Mobile)
					if err != nil {
						return err
					}
					if wxUser == nil {
						err = errors.New("用户信息不存在：mobile:" + admin.Mobile)
						return err
					}
					openId = wxUser.OpenId
				}
			} else {
				wxUser, err := models.GetWxUserByUserId(v.UserId)
				if err != nil {
					return err
				}
				if wxUser == nil {
					err = errors.New("用户信息不存在：userId:" + strconv.Itoa(v.UserId))
					return err
				}
				openId = wxUser.OpenId
			}
			//发送消息
			if openId == "" {
				err = errors.New("openId is empty")
				return err
			}
			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = openId
			openIdList = append(openIdList, openIdItem)

			first := "数据录入提醒"
			keyword1 := v.SecName
			keyword2 := "每日 " + v.NoticeTime
			remark := v.SecName + "该更新了"
			err = SendWxMsgWithFrequency(first, keyword1, keyword2, remark, openIdList)
			if err != nil {
				return err
			}
		}
	}
	return
}

//周度消息推送
func FrequencyByWeek() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("FrequencyByWeek Err:", err.Error())
			utils.FileLog.Info("FrequencyByWeek err: %s", err.Error())
		}
	}()
	frequency := "周度"
	nowWeekDay := utils.GetWeekDay()
	fmt.Println("nowWeekDay:", nowWeekDay)
	items, err := models.GetEdbInfoByFrequencyWeek(frequency, nowWeekDay)
	if err != nil {
		fmt.Println("GetFrequencyByDay err:", err.Error())
		return
	}
	if len(items) <= 0 {
		err = errors.New("没有需要推送的数据，FrequencyByWeek")
		return
	}

	nowDate := time.Now().Format(utils.FormatDate)
	for _, v := range items {
		//判断指标当天数据是否已录入
		dataCount, err := models.GetEdbdataCount(v.TradeCode, nowDate)
		if err != nil {
			return err
		}
		if dataCount > 0 {
			utils.FileLog.Info("%s", v.TradeCode+" :当天数据已录入，无需提醒")
			continue
		}
		count, err := models.GetEdbinfoSendMsgCount(v.UserId, v.TradeCode)
		if err != nil {
			fmt.Println("GetEdbinfoSendMsgCount Err:" + err.Error())
			return err
		}
		if count > 0 {
			fmt.Println(v.UserId, v.TradeCode, "当天已发送")
			continue
		}
		noticeTime := v.NoticeTime
		if noticeTime == "" {
			err = errors.New("NoticeTime 参数错误:NoticeTime is empty ")
			return err
		}
		weekArr := strings.Split(noticeTime, " ")
		if len(weekArr) < 2 {
			err = errors.New("NoticeTime 参数错误: " + noticeTime)
			return err
		}
		weekVal := weekArr[0]
		weekVal = strings.Trim(weekVal, " ")
		if weekVal == "" {
			err = errors.New("weekVal 参数错误: weekVal:" + weekVal)
			return err
		}
		fmt.Println("weekVal:", weekVal, " nowWeek:", nowWeekDay)
		if weekVal != nowWeekDay {
			err = errors.New("不是当前日期，不需要发送消息: weekVal:" + weekVal + "; nowWeek:" + nowWeekDay)
			return err
		}
		noticeStr := weekArr[1]
		if noticeStr == "" {
			err = errors.New("noticeStr 参数错误: noticeStr:" + noticeStr)
			return err
		}
		noticeTimeArr := strings.Split(noticeStr, ":")
		if len(noticeTimeArr) < 3 {
			err = errors.New("NoticeTime 参数错误,noticeTime:" + noticeTime)
			return err
		}
		noticeHour, err := strconv.Atoi(noticeTimeArr[0])
		if err != nil {
			return err
		}
		noticeMinute, err := strconv.Atoi(noticeTimeArr[1])
		if err != nil {
			return err
		}
		noticeSecond, err := strconv.Atoi(noticeTimeArr[2])
		if err != nil {
			return err
		}

		noticeSecondTotal := noticeHour*3600 + noticeMinute*60 + noticeSecond

		mbefor, _ := time.ParseDuration("-1m")
		mafter, _ := time.ParseDuration("1m")
		nowBefor := time.Now().Add(mbefor)
		nowAfter := time.Now().Add(mafter)
		nowBeforSecond := nowBefor.Hour()*3600 + nowBefor.Minute()*60 + nowBefor.Second()
		nowAfterSecond := nowAfter.Hour()*3600 + nowAfter.Minute()*60 + nowAfter.Second()

		if noticeSecondTotal >= nowBeforSecond && noticeSecondTotal <= nowAfterSecond {
			//获取用户信息
			var openId string
			isAdmin := true
			admin, err := models.GetAdminByAdminId(v.UserId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					isAdmin = false
				} else {
					return err
				}
			}
			if admin == nil {
				isAdmin = false
			}
			if isAdmin {
				if admin.Mobile == "" {

				} else {
					wxUser, err := models.GetWxUserByMobile(admin.Mobile)
					if err != nil {
						return err
					}
					if wxUser == nil {
						err = errors.New("用户信息不存在：mobile:" + admin.Mobile)
						return err
					}
					openId = wxUser.OpenId
				}
			} else {
				wxUser, err := models.GetWxUserByUserId(v.UserId)
				if err != nil {
					return err
				}
				if wxUser == nil {
					err = errors.New("用户信息不存在：userId:" + strconv.Itoa(v.UserId))
					return err
				}
				openId = wxUser.OpenId
			}
			//发送消息
			if openId == "" {
				err = errors.New("openId is empty")
				return err
			}
			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = openId
			openIdList = append(openIdList, openIdItem)

			first := "数据录入提醒"
			keyword1 := v.SecName
			keyword2 := "每周 " + v.NoticeTime
			remark := v.SecName + "该更新了"

			err = SendWxMsgWithFrequency(first, keyword1, keyword2, remark, openIdList)
			if err != nil {
				return err
			}
			//发送成功，记录发送日志
			{
				sendRecord := new(models.EdbinfoSendMsgRecord)
				sendRecord.UserId = v.UserId
				sendRecord.TradeCode = v.TradeCode
				sendRecord.CreateTime = time.Now()
				err = models.AddEdbinfoSendMsgRecord(sendRecord)
				if err != nil {
					return err
				}
			}
		} else {
			utils.FileLog.Info("%s", v.TradeCode+":不在推送消息时间范围内")
		}
	}
	return
}

//周度消息推送
func FrequencyByMonth() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("FrequencyByMonth Err:", err.Error())
			utils.FileLog.Info("FrequencyByMonth err: %s", err.Error())
		}
	}()
	frequency := "月度"
	items, err := models.GetEdbInfoByFrequency(frequency)
	if err != nil {
		fmt.Println("GetFrequencyByDay err:", err.Error())
		return
	}
	if len(items) <= 0 {
		err = errors.New("没有需要推送的数据")
		return
	}
	for _, v := range items {
		noticeTime := v.NoticeTime
		if noticeTime == "" {
			err = errors.New("NoticeTime 参数错误:NoticeTime is empty ")
			return
		}
		monthArr := strings.Split(noticeTime, " ")
		if len(monthArr) < 2 {
			err = errors.New("NoticeTime 参数错误: " + noticeTime)
			return
		}
		monthStr := monthArr[0]
		if monthStr == "" {
			err = errors.New("NoticeTime 参数错误: NoticeTime:" + noticeTime + ";monthStr:" + monthStr)
			return
		}
		monthVal := strings.Replace(monthStr, "日", "", -1)
		monthVal = strings.Trim(monthVal, " ")
		if monthVal == "" {
			err = errors.New("weekVal 参数错误: monthVal:" + monthVal)
			return
		}
		monthValInt, err := strconv.Atoi(monthVal)
		if err != nil {
			return err
		}
		nowDay := time.Now().Day()
		if monthValInt != nowDay {
			err = errors.New("不是当前日期，不需要发送消息: monthVal:" + monthVal + "; nowWeek:" + strconv.Itoa(nowDay))
			return err
		}
		noticeStr := monthArr[1]
		if noticeStr == "" {
			err = errors.New("noticeStr 参数错误: noticeStr:" + noticeStr)
			return err
		}
		noticeTimeArr := strings.Split(noticeStr, ":")
		if len(noticeTimeArr) < 3 {
			err = errors.New("NoticeTime 参数错误,noticeTime:" + noticeTime)
			return err
		}
		noticeHour, err := strconv.Atoi(noticeTimeArr[0])
		if err != nil {
			return err
		}
		noticeMinute, err := strconv.Atoi(noticeTimeArr[1])
		if err != nil {
			return err
		}
		noticeSecond, err := strconv.Atoi(noticeTimeArr[2])
		if err != nil {
			return err
		}

		noticeSecondTotal := noticeHour*3600 + noticeMinute*60 + noticeSecond

		mbefor, _ := time.ParseDuration("-1m")
		mafter, _ := time.ParseDuration("1m")
		nowBefor := time.Now().Add(mbefor)
		nowAfter := time.Now().Add(mafter)
		nowBeforSecond := nowBefor.Hour()*3600 + nowBefor.Minute()*60 + nowBefor.Second()
		nowAfterSecond := nowAfter.Hour()*3600 + nowAfter.Minute()*60 + nowAfter.Second()

		if noticeSecondTotal >= nowBeforSecond && noticeSecondTotal <= nowAfterSecond {
			//获取用户信息
			var openId string
			isAdmin := true
			admin, err := models.GetAdminByAdminId(v.UserId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					isAdmin = false
				} else {
					return err
				}
			}
			if admin == nil {
				isAdmin = false
			}
			if isAdmin {
				if admin.Mobile == "" {

				} else {
					wxUser, err := models.GetWxUserByMobile(admin.Mobile)
					if err != nil {
						return err
					}
					if wxUser == nil {
						err = errors.New("用户信息不存在：mobile:" + admin.Mobile)
						return err
					}
					openId = wxUser.OpenId
				}
			} else {
				wxUser, err := models.GetWxUserByUserId(v.UserId)
				if err != nil {
					return err
				}
				if wxUser == nil {
					err = errors.New("用户信息不存在：userId:" + strconv.Itoa(v.UserId))
					return err
				}
				openId = wxUser.OpenId
			}
			//发送消息
			if openId == "" {
				err = errors.New("openId is empty")
				return err
			}
			openIdList := make([]*models.OpenIdList, 0)
			openIdItem := new(models.OpenIdList)
			openIdItem.OpenId = openId
			openIdList = append(openIdList, openIdItem)

			first := "数据录入提醒"
			keyword1 := v.SecName
			keyword2 := "每月 " + v.NoticeTime
			remark := v.SecName + "该更新了"

			err = SendWxMsgWithFrequency(first, keyword1, keyword2, remark, openIdList)
			if err != nil {
				return err
			}
		}
	}
	return
}
