package api

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/model"
	"main/utils"
	"math"
	"sort"
	"strings"
	"time"
)

// 按月返回余额
func monthLog(ctx iris.Context) {
	var balanceLogs []model.BalanceLogs
	var res []dateLog
	username := utils.GetLoginUser(ctx).Username
	if username == "" {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ?", username).Order("id").Find(&balanceLogs).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if len(balanceLogs) == 0 {
		err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
		if err != nil {
			return
		}
		return
	}
	monthList := getMonthList(balanceLogs)
	cardList := getCardList(balanceLogs)
	for index, month := range monthList {
		var cardLogs []cardLog
		var balanceTmp float64
		for _, card := range cardList {
			b := getMonthBalance(balanceLogs, month, card)
			if index == 0 {
				cardLogs = append(cardLogs, cardLog{
					Card:    card,
					Balance: b,
					Changes: 0,
				})
			} else {
				bTmp := getMonthBalance(balanceLogs, monthList[index-1], card)
				cardLogs = append(cardLogs, cardLog{
					Card:    card,
					Balance: b,
					Changes: utils.Round(b-bTmp, 2),
				})
			}
			balanceTmp += b
		}
		//cardLogs 排序
		sort.Slice(cardLogs, func(i, j int) bool {
			return math.Abs(cardLogs[i].Changes) > math.Abs(cardLogs[j].Changes)
		})
		if index == 0 {
			res = append(res, dateLog{
				Date:     month,
				Duration: "",
				Changes:  0,
				Balance:  utils.Round(balanceTmp, 2),
				Detail:   cardLogs,
			})
		} else {
			res = append(res, dateLog{
				Date:     month,
				Duration: fmt.Sprintf("%s~%s", res[index-1].Date, month),
				Changes:  utils.Round(balanceTmp-res[index-1].Balance, 2),
				Balance:  utils.Round(balanceTmp, 2),
				Detail:   cardLogs,
			})
		}
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if err != nil {
		return
	}
}

// 获取时间段内详情
func detailLog(ctx iris.Context) {
	username := utils.GetLoginUser(ctx).Username
	if username == "" {
		return
	}
	startDate := ctx.URLParam("start")
	endDate := ctx.URLParam("end")
	var res []dateLog
	var balanceLogs []model.BalanceLogs
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ? ", username).Find(&balanceLogs).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if len(balanceLogs) == 0 {
		err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
		if utils.ErrHandle(ctx, err) {
			return
		}
		return
	}
	dateList := getDateList(balanceLogs, startDate, endDate)
	cardList := getCardList(balanceLogs)
	for index, date := range dateList {
		var cardLogs []cardLog
		var balanceTmp float64
		for _, card := range cardList {
			b := getMonthBalance(balanceLogs, date, card)
			if index == 0 {
				cardLogs = append(cardLogs, cardLog{
					Card:    card,
					Balance: b,
					Changes: 0,
				})
			} else {
				bTmp := getMonthBalance(balanceLogs, dateList[index-1], card)
				cardLogs = append(cardLogs, cardLog{
					Card:    card,
					Balance: b,
					Changes: utils.Round(b-bTmp, 2),
				})
			}
			balanceTmp += b
		}
		//cardLogs 排序
		sort.Slice(cardLogs, func(i, j int) bool {
			return math.Abs(cardLogs[i].Changes) > math.Abs(cardLogs[j].Changes)
		})
		if index == 0 {
			res = append(res, dateLog{
				Date:     date,
				Duration: "",
				Changes:  0,
				Balance:  utils.Round(balanceTmp, 2),
				Detail:   cardLogs,
			})
		} else {
			res = append(res, dateLog{
				Date:     date,
				Duration: fmt.Sprintf("%s~%s", res[index-1].Date, date),
				Changes:  utils.Round(balanceTmp-res[index-1].Balance, 2),
				Balance:  utils.Round(balanceTmp, 2),
				Detail:   cardLogs,
			})
		}
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 获取数据中card截至month时的余额
func getMonthBalance(data []model.BalanceLogs, month string, card string) float64 {
	var res float64
	for _, v := range data {
		if v.Card == card && v.Date <= month {
			res = v.Balance
		} else if v.Date > month {
			break
		}
	}
	return utils.Round(res, 2)
}

// 获取card列表
func getCardList(data []model.BalanceLogs) []string {
	var resTmp []string
	var res []string
	for _, v := range data {
		card := v.Card
		if !utils.CheckListItem(resTmp, card) {
			resTmp = append(resTmp, card)
			res = append(res, card)
		}
	}
	return res
}

// 获取月份列表
func getMonthList(data []model.BalanceLogs) []string {
	var resTmp []string
	var res []string
	for _, v := range data {
		month := fmt.Sprintf("%s-%s-01", strings.Split(v.Date, "-")[0], strings.Split(v.Date, "-")[1])
		if !utils.CheckListItem(resTmp, month) {
			resTmp = append(resTmp, month)
			res = append(res, month)
		}
	}
	t, _ := time.Parse("2006-01-02", data[len(data)-1].Date)
	res = append(res, t.AddDate(0, 1, 0).Format("2006-01")+"-01")
	return res
}

// 获取日期列表
func getDateList(data []model.BalanceLogs, start string, end string) []string {
	var resTmp []string
	var res []string
	res = append(res, start)
	for _, v := range data {
		date := v.Date
		if date <= start {
			continue
		} else if date >= end {
			break
		}
		if !utils.CheckListItem(resTmp, date) {
			resTmp = append(resTmp, date)
			res = append(res, date)
		}
	}
	res = append(res, end)
	return res
}
