package api

import (
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"io"
	"main/database"
	"main/model"
	"main/utils"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 获取location
func getLocation(ctx iris.Context) {
	param := ctx.URLParam("location")
	res, err := http.Get(fmt.Sprintf("https://wis.qq.com/city/like?source=pc&city=%s", param))
	if utils.ErrHandle(ctx, err) {
		return
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if utils.ErrHandle(ctx, err) {
			return
		}
	}(res.Body)
	body, _ := io.ReadAll(res.Body)
	var r resLocation
	//解析json结构
	err = json.Unmarshal(body, &r)
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(200, "", r.Data))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 获取天气方法
func getWeather(ctx iris.Context) {
	user := utils.GetLoginUser(ctx)
	if utils.DataIsNil(user) {
		return
	}
	var info model.Userinfo
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ?", user.Username).First(&info).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	var location []string
	if info.Location == "" {
		location = []string{"北京", "北京", "顺义"}
	} else {
		info.Location = strings.ReplaceAll(info.Location, " ", "")
		location = strings.Split(info.Location, ",")
		if len(location) < 3 {
			location = append(location, "")
		}
	}
	res, err := getMyWeather(location[0], location[1], location[2])
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(200, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 获取地点对应地址天气
func getMyWeather(province string, city string, county string) (string, error) {
	var weather []model.Weather
	var respWeather string
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where(&model.Weather{Date: time.Now().Format("2006-01-02"), Location: fmt.Sprintf("%s,%s,%s", province, city, county)}).Find(&weather).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if len(weather) == 0 {
		resp, err := http.Get(fmt.Sprintf("https://wis.qq.com/weather/common?"+
			"source=pc&weather_type=forecast_24h&province=%s&city=%s&county=%s", url.QueryEscape(province), url.QueryEscape(city), url.QueryEscape(county)))
		if err != nil {
			return "", err
		}
		defer func(Body io.ReadCloser) {
			err = Body.Close()
			if err != nil {
			}
		}(resp.Body)
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			fmt.Println(err)
		}
		var r resWeather
		//解析json结构
		err = json.Unmarshal(body, &r)
		if err != nil {
			//fmt.Println(fmt.Sprintf("https://wis.qq.com/weather/common?"+
			//	"source=pc&weather_type=forecast_24h&province=%s&city=%s&county=%s", url.QueryEscape(province), url.QueryEscape(city), url.QueryEscape(county)))
			//fmt.Println(resp.Body, "----------", string(body), "----------", err)
			return "", err
		}
		todayWeather := formatWeather(r.Data.Forecast24h.D0)
		tomWeather := formatWeather(r.Data.Forecast24h.D1)
		respWeather = fmt.Sprintf("%s;%s", todayWeather, tomWeather)
		if err1 := db.Create(&model.Weather{
			Date:     time.Now().Format("2006-01-02"),
			Location: fmt.Sprintf("%s,%s,%s", province, city, county),
			Weather:  respWeather,
		}).Error; err1 != nil {
			logrus.Errorln("sql执行失败：", err1)
		}
	} else {
		respWeather = weather[0].Weather
	}
	return respWeather, nil
}

// 天气格式化
func formatWeather(data res24h) string {
	var weather string
	var windPower string
	var windDirection string
	var degree string
	if data.DayWeather == data.NightWeather {
		weather = data.DayWeather
	} else {
		weather = fmt.Sprintf("%s转%s", data.NightWeather, data.DayWeather)
	}
	if data.DayWindDirection == data.NightWindDirection {
		windDirection = data.DayWindDirection
	} else {
		windDirection = fmt.Sprintf("%s转%s", data.NightWindDirection, data.DayWindDirection)
	}
	if data.DayWindPower == data.NightWindPower {
		windPower = data.DayWindPower + "级"
	} else {
		windPower = fmt.Sprintf("%s~%s级", data.NightWindPower, data.DayWindPower)
	}
	degree = fmt.Sprintf("%s~%s℃", data.MinDegree, data.MaxDegree)
	return fmt.Sprintf("%s, %s, %s %s", weather, degree, windDirection, windPower)
}

func testWeather(ctx iris.Context) {
	var location []string
	loc := ctx.URLParam("location")
	fmt.Println(loc)
	if loc == "" {
		location = []string{"北京", "北京", "顺义"}
		fmt.Println(location)
	} else {
		loc = strings.ReplaceAll(loc, " ", "")
		location = strings.Split(loc, ",")
		if len(location) < 3 {
			location = append(location, "")
		}
		fmt.Println(location)
	}
	res, err := getMyWeather(location[0], location[1], location[2])
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(200, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}
