package controllers

import (
	"merchant/internal/models/account"
	"merchant/internal/models/merchant"
	"merchant/internal/models/order"
	"merchant/internal/sys/enum"
	"strconv"
	"strings"
)

type History struct {
	KeepSession
}

type AccountHistoryListInfo struct {
	account.AccountHistoryInfo
	OrderInfo order.OrderInfo `json:"orderInfo"`
}

// ShowHistoryListUI 账户资产变动列表
func (c *History) ShowHistoryListUI() {
	us := c.GetSession(enum.UserSession)
	u := us.(merchant.MerchantInfo)

	ranMd5 := encrypt.EncodeMd5([]byte(pubMethod.RandomString(46)))
	c.Ctx.SetCookie(enum.UserCookie, ranMd5, enum.CookieExpireTime)
	c.Ctx.SetSecureCookie(ranMd5, enum.UserCookie, ranMd5, enum.CookieExpireTime)
	_ = c.SetSession(enum.UserCookie, ranMd5)

	c.Data["payType"] = enum.GetHistoryStatus()
	c.Data["userName"] = u.MerchantName
	c.TplName = "history_record.html"
}

func (c *History) HistoryQueryAndListPage() {
	us := c.GetSession(enum.UserSession)
	u := us.(merchant.MerchantInfo)

	// 分页参数
	page, _ := strconv.Atoi(c.GetString("page"))
	limit, _ := strconv.Atoi(c.GetString("limit"))
	if limit == 0 {
		limit = 15
	}

	// 查询参数
	in := make(map[string]string)
	start := strings.TrimSpace(c.GetString("start"))
	end := strings.TrimSpace(c.GetString("end"))
	status := strings.TrimSpace(c.GetString("status"))

	in["type"] = status
	in["account_uid"] = u.MerchantUid

	if start != "" {
		in["create_time__gte"] = start
	}
	if end != "" {
		in["create_time__lte"] = end
	}

	// 计算分页数
	count := account.GetAccountHistoryLenByMap(in)
	totalPage := count / limit
	if count%limit != 0 {
		totalPage++
	}

	// 数据获取
	var list []account.AccountHistoryInfo
	if page <= totalPage {
		list = account.GetAccountHistoryByMap(in, limit, (page-1)*limit)
	}

	var resList []AccountHistoryListInfo
	for _, info := range list {
		orderInfo := order.GetOrderByMerchantOrderId(info.OrderId)
		resList = append(resList, AccountHistoryListInfo{
			AccountHistoryInfo: info,
			OrderInfo:          orderInfo,
		})
	}

	// 数据回显
	out := make(map[string]any)
	out["limit"] = limit // 分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["root"] = resList // 显示数据

	c.Data["json"] = out
	_ = c.ServeJSON()
	c.StopRun()
}
