package api

import (
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/utils"
	"strconv"
	"strings"
	"time"
)

// 获取节假日信息
func getHolidays(ctx iris.Context) {
	yearParam := ctx.URLParam("year")
	if yearParam == "" {
		yearParam = strconv.Itoa(time.Now().Year())
	}
	logrus.Infoln("假期查询年份：", yearParam)
	year, err := strconv.Atoi(yearParam)
	var res []utils.ResHolidays
	if utils.ErrHandle(ctx, err) {
		return
	}
	if utils.ErrHandle(ctx, err) {
		return
	}
	startDate := time.Date(year, 1, 1, 0, 0, 0, 0, time.Local)
	for startDate.Year() == year {
		isHoliday, name := utils.CheckHoliday(startDate.Format("2006-01-02"))
		if startDate.Weekday() == time.Saturday || startDate.Weekday() == time.Sunday {
			res = append(res, utils.ResHolidays{
				Date:          startDate.Format("2006-01-02"),
				HolidayNameCn: "周末",
			})
		} else if isHoliday {
			res = append(res, utils.ResHolidays{
				Date:          startDate.Format("2006-01-02"),
				HolidayNameCn: name,
			})
		}
		startDate = startDate.AddDate(0, 0, 1)
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if err != nil {
		return
	}
}

// 获取IP归属地
func getIpLocation(ctx iris.Context) {
	var ip string
	if ctx.URLParam("ip") != "" {
		ip = ctx.URLParam("ip")
	} else {
		ip = utils.GetRequestIp(ctx)
	}
	ipLocation, err := utils.GetIpLocation(ip)
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", ipLocationData{
		Ip:       ip,
		Location: ipLocation,
	}))
	if err != nil {
		return
	}
}

// 邮件发送
func sendEmail(ctx iris.Context) {
	receiver := strings.Split(ctx.URLParam("receiver"), ";")
	subject := ctx.URLParam("subject")
	content := ctx.URLParam("content")
	err := utils.SendEmail(receiver, subject, content)
	if utils.ErrHandle(ctx, err) {
		logrus.Errorln(err)
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "发送成功"))
	if err != nil {
		return
	}
}

func getSudokuCheck(ctx iris.Context) {

}
