package controllers

import (
	"fmt"
	"math"
	"merchant/internal/models/account"
	merchant2 "merchant/internal/models/merchant"
	order2 "merchant/internal/models/order"
	"merchant/internal/models/road"
	"merchant/internal/sys/enum"
	"strconv"

	"github.com/duke-git/lancet/v2/mathutil"
	"github.com/duke-git/lancet/v2/slice"
)

type Index struct {
	KeepSession
}

// ShowUI 首页
func (c *Index) ShowUI() {
	us := c.GetSession(enum.UserSession)
	u := us.(merchant2.MerchantInfo)
	c.Data["userName"] = u.MerchantName
	c.TplName = "index.html"
}

// LoadUserAccountInfo 加载用户账户金额信息
func (c *Index) LoadUserAccountInfo() {
	us := c.GetSession(enum.UserSession)
	ctx := c.Ctx.Request.Context()
	u := us.(merchant2.MerchantInfo)

	ac := account.GetAccountByUid(u.MerchantUid)

	info := make(map[string]any)
	// 账户余额
	info["balanceAmt"] = pubMethod.FormatFloat64ToString(ac.Balance)

	type TotalSummary struct {
		TodayAmount        float64 `json:"todayAmount"`        // 今日订单金额
		TodayNum           int     `json:"todayNum"`           // 今日订单数
		TodaySucNum        int     `json:"todaySucNum"`        // 今日成功订单数
		TodaySucAmount     float64 `json:"todaySucAmount"`     // 今日成功订单金额
		YesterdayAmount    float64 `json:"yesterdayAmount"`    // 昨日订单金额
		YesterdayNum       int     `json:"yesterdayNum"`       // 昨日订单数
		YesterdaySucNum    int     `json:"yesterdaySucNum"`    // 昨日成功订单数
		YesterdaySucAmount float64 `json:"yesterdaySucAmount"` // 昨日成功订单金额
		TodaySucRate       float64 `json:"todaySucRate"`       // 今日成功率
		YesterdaySucRate   float64 `json:"yesterdaySucRate"`   // 昨日成功率
		TotalAmount        float64 `json:"totalAmount"`        // 总订单金额
		TotalNum           int     `json:"totalNum"`           // 总订单数
		TotalSucNum        int     `json:"totalSucNum"`        // 总成功订单数
		TotalSucRate       float64 `json:"totalSucRate"`       // 总成功率
		TotalSucAmount     float64 `json:"totalSucAmount"`     // 总成功订单金额
	}

	totalSummary := TotalSummary{}

	totalSummaryList := order2.GetSummaryByMerchant(ctx, u.MerchantUid)
	if len(totalSummaryList) > 0 {
		totalSummary.TodayAmount = totalSummaryList[0].TotalAmount
		totalSummary.TodayNum = totalSummaryList[0].TotalNum
		totalSummary.TodaySucNum = totalSummaryList[0].SuccessNum
		totalSummary.TodaySucAmount = totalSummaryList[0].SuccessAmount
		totalSummary.TodaySucRate = totalSummaryList[0].Rate
	}
	if len(totalSummaryList) > 1 {
		totalSummary.YesterdayAmount = totalSummaryList[1].TotalAmount
		totalSummary.YesterdayNum = totalSummaryList[1].TotalNum
		totalSummary.YesterdaySucNum = totalSummaryList[1].SuccessNum
		totalSummary.YesterdaySucAmount = totalSummaryList[1].SuccessAmount
		totalSummary.YesterdaySucRate = totalSummaryList[1].Rate
	}

	for _, v := range totalSummaryList {
		totalSummary.TotalAmount += v.TotalAmount
		totalSummary.TotalNum += v.TotalNum
		totalSummary.TotalSucNum += v.SuccessNum
		totalSummary.TotalSucAmount += v.SuccessAmount
	}

	if totalSummary.TotalNum != 0 {
		totalSummary.TotalSucRate = mathutil.RoundToFloat(float64(totalSummary.TotalSucNum)/float64(totalSummary.TotalNum)*100, 2)
	}

	// 可用余额
	info["settAmount"] = pubMethod.FormatFloat64ToString(totalSummary.TodaySucAmount)
	// 冻结金额
	info["freezeAmt"] = pubMethod.FormatFloat64ToString(totalSummary.TotalSucAmount)
	info["yesterdayAmount"] = pubMethod.FormatFloat64ToString(totalSummary.YesterdaySucAmount)
	// 押款金额
	info["amountFrozen"] = pubMethod.FormatFloat64ToString(totalSummary.TotalSucRate)

	c.Data["json"] = info
	c.ServeJSON(true)
}

// LoadCountOrder 加载总订单信息
func (c *Index) LoadCountOrder() {
	ctx := c.Ctx.Request.Context()
	us := c.GetSession(enum.UserSession)
	u := us.(merchant2.MerchantInfo)

	md := merchant2.GetMerchantDeployByUid(ctx, u.MerchantUid)

	type orderInPayWay struct {
		PayWayName    string // 支付方式名
		OrderCount    int    // 订单数
		SucOrderCount int    // 成功订单数
		SucRate       string // 成功率
	}

	ways := make([]orderInPayWay, len(md))

	for k, v := range md {
		in := make(map[string]string)
		in["merchant_uid"] = u.MerchantUid

		ways[k].PayWayName = road.GetRoadInfoByRoadUid(ctx, v.SingleRoadUid).ProductName

		in["road_uid"] = v.SingleRoadUid
		ways[k].OrderCount = order2.GetOrderLenByMap(in)

		in["status"] = enum.SUCCESS
		ways[k].SucOrderCount = order2.GetOrderLenByMap(in)

		if ways[k].OrderCount == 0 {
			ways[k].SucRate = "0"
			continue
		}
		ways[k].SucRate = fmt.Sprintf("%0.4f", float64(ways[k].SucOrderCount)/float64(ways[k].OrderCount))
	}

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

// LoadOrderCount 加载总订单数
func (c *Index) LoadOrderCount() {
	ctx := c.Ctx.Request.Context()

	us := c.GetSession(enum.UserSession)
	u := us.(merchant2.MerchantInfo)
	in := make(map[string]string)
	out := make(map[string]any)

	in["merchant_uid"] = u.MerchantUid
	out["orders"] = order2.GetOrderLenByMap(in)

	in["status"] = enum.SUCCESS
	out["suc_orders"] = order2.GetOrderLenByMap(in)

	supplierAll := 0.0
	platformAll := 0.0
	agentAll := 0.0
	allAmount := 0.0
	TodaySuccessNum := 0
	dataInfo := order2.GetOrderProfitByMap(ctx, in, -1, 0)

	for _, v := range dataInfo {
		if v.Status != "success" {
			continue
		}
		allAmount += v.OrderAmount
		supplierAll += v.SupplierProfit
		platformAll += v.PlatformProfit
		agentAll += v.AgentProfit
		TodaySuccessNum += 1
	}

	out["TadaySupplierProfit"], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", supplierAll), 64)
	out["TadayPlatformProfit"], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", platformAll), 64)
	out["TadayAgentProfit"], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", agentAll), 64)
	out["TadayAllAmount"], _ = strconv.ParseFloat(fmt.Sprintf("%.2f", allAmount), 64)

	out["TodaySuccessNum"] = TodaySuccessNum
	out["TadayAllNum"] = len(dataInfo)

	if out["orders"].(int) == 0 {
		out["suc_rate"] = 0
	} else {
		out["suc_rate"] = fmt.Sprintf("%0.4f", math.Round(float64(out["suc_orders"].(int))/float64(out["orders"].(int))*10000)/10000)
	}

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

// LoadUserPayWayUI 加载用户支付配置
func (c *Index) LoadUserPayWayUI() {
	us := c.GetSession(enum.UserSession)
	u := us.(merchant2.MerchantInfo)

	c.Data["userName"] = u.MerchantName
	c.TplName = "pay_way.html"
}

func (c *Index) LoadUserPayWay() {
	ctx := c.Ctx.Request.Context()
	us := c.GetSession(enum.UserSession)

	u := us.(merchant2.MerchantInfo)
	md := merchant2.GetMerchantDeployByUid(ctx, u.MerchantUid)

	type payConfig struct {
		No                 string  `json:"no"`                 // 通道编号
		Name               string  `json:"name"`               // 产品名
		Rate               float64 `json:"rate"`               // 通道费率
		Status             string  `json:"status"`             // 通道状态
		TodayAmount        float64 `json:"todayAmount"`        // 今日订单金额
		TodayNum           int     `json:"todayNum"`           // 今日订单数
		TodaySucNum        int     `json:"todaySucNum"`        // 今日成功订单数
		TodaySucAmount     float64 `json:"todaySucAmount"`     // 今日成功订单金额
		YesterdayAmount    float64 `json:"yesterdayAmount"`    // 昨日订单金额
		YesterdayNum       int     `json:"yesterdayNum"`       // 昨日订单数
		YesterdaySucNum    int     `json:"yesterdaySucNum"`    // 昨日成功订单数
		YesterdaySucAmount float64 `json:"yesterdaySucAmount"` // 昨日成功订单金额
		TodaySucRate       float64 `json:"todaySucRate"`       // 今日成功率
		YesterdaySucRate   float64 `json:"yesterdaySucRate"`   // 昨日成功率
		TotalAmount        float64 `json:"totalAmount"`        // 总订单金额
		TotalNum           int     `json:"totalNum"`           // 总订单数
		TotalSucNum        int     `json:"totalSucNum"`        // 总成功订单数
		TotalSucRate       float64 `json:"totalSucRate"`       // 总成功率
		TotalSucAmount     float64 `json:"totalSucAmount"`     // 总成功订单金额
	}

	type TotalSummary struct {
		TodayAmount        float64 `json:"todayAmount"`        // 今日订单金额
		TodayNum           int     `json:"todayNum"`           // 今日订单数
		TodaySucNum        int     `json:"todaySucNum"`        // 今日成功订单数
		TodaySucAmount     float64 `json:"todaySucAmount"`     // 今日成功订单金额
		YesterdayAmount    float64 `json:"yesterdayAmount"`    // 昨日订单金额
		YesterdayNum       int     `json:"yesterdayNum"`       // 昨日订单数
		YesterdaySucNum    int     `json:"yesterdaySucNum"`    // 昨日成功订单数
		YesterdaySucAmount float64 `json:"yesterdaySucAmount"` // 昨日成功订单金额
		TodaySucRate       float64 `json:"todaySucRate"`       // 今日成功率
		YesterdaySucRate   float64 `json:"yesterdaySucRate"`   // 昨日成功率
		TotalAmount        float64 `json:"totalAmount"`        // 总订单金额
		TotalNum           int     `json:"totalNum"`           // 总订单数
		TotalSucNum        int     `json:"totalSucNum"`        // 总成功订单数
		TotalSucRate       float64 `json:"totalSucRate"`       // 总成功率
		TotalSucAmount     float64 `json:"totalSucAmount"`     // 总成功订单金额
	}

	totalSummary := TotalSummary{}

	ways := slice.Map(md, func(index int, item merchant2.MerchantDeployInfo) payConfig {

		road_ := road.GetRoadInfoByRoadUid(ctx, item.SingleRoadUid)
		config := payConfig{
			No:   item.SingleRoadUid,
			Name: road_.RoadName,
			Rate: item.RollRoadPlatformRate,
		}

		rates := slice.Map(item.PlatformRate(ctx), func(index int, item merchant2.ProfitMargin) float64 {
			return item.Value
		})
		if len(rates) > 0 {
			config.Rate = mathutil.Average(rates...)
		}

		summary := order2.GetSummaryByRoadAndMerchant(ctx, item.SingleRoadUid, u.MerchantUid)
		if len(summary) == 0 {
			return config
		}
		config.TodayAmount = summary[0].TotalAmount
		config.TodayNum = summary[0].TotalNum
		config.TodaySucNum = summary[0].SuccessNum
		config.TodaySucAmount = summary[0].SuccessAmount
		config.TodaySucRate = summary[0].Rate

		if len(summary) > 1 {
			config.YesterdayAmount = summary[1].TotalAmount
			config.YesterdayNum = summary[1].TotalNum
			config.YesterdaySucNum = summary[1].SuccessNum
			config.YesterdaySucAmount = summary[1].SuccessAmount
			config.YesterdaySucRate = summary[1].Rate
		}

		config.TotalAmount = mathutil.Sum(slice.Map(summary, func(index int, item order2.Summary) float64 {
			return item.TotalAmount
		})...)
		config.TotalNum = mathutil.Sum(slice.Map(summary, func(index int, item order2.Summary) int {
			return item.TotalNum
		})...)
		config.TotalSucNum = mathutil.Sum(slice.Map(summary, func(index int, item order2.Summary) int {
			return item.SuccessNum
		})...)
		config.TotalSucAmount = mathutil.Sum(slice.Map(summary, func(index int, item order2.Summary) float64 {
			return item.SuccessAmount
		})...)
		if config.TotalNum != 0 {
			config.TotalSucRate = mathutil.RoundToFloat(float64(config.TotalSucNum)/float64(config.TotalNum)*100, 2)
		}
		return config
	})

	totalSummaryList := order2.GetSummaryByMerchant(ctx, u.MerchantUid)
	if len(totalSummaryList) > 0 {
		totalSummary.TodayAmount = totalSummaryList[0].TotalAmount
		totalSummary.TodayNum = totalSummaryList[0].TotalNum
		totalSummary.TodaySucNum = totalSummaryList[0].SuccessNum
		totalSummary.TodaySucAmount = totalSummaryList[0].SuccessAmount
		totalSummary.TodaySucRate = totalSummaryList[0].Rate
	}
	if len(totalSummaryList) > 1 {
		totalSummary.YesterdayAmount = totalSummaryList[1].TotalAmount
		totalSummary.YesterdayNum = totalSummaryList[1].TotalNum
		totalSummary.YesterdaySucNum = totalSummaryList[1].SuccessNum
		totalSummary.YesterdaySucAmount = totalSummaryList[1].SuccessAmount
		totalSummary.YesterdaySucRate = totalSummaryList[1].Rate
	}
	for _, v := range totalSummaryList {
		totalSummary.TotalAmount += v.TotalAmount
		totalSummary.TotalNum += v.TotalNum
		totalSummary.TotalSucNum += v.SuccessNum
		totalSummary.TotalSucAmount += v.SuccessAmount
	}

	if totalSummary.TotalNum != 0 {
		totalSummary.TotalSucRate = mathutil.RoundToFloat(float64(totalSummary.TotalSucNum)/float64(totalSummary.TotalNum)*100, 2)
	}

	response := struct {
		Ways         []payConfig  `json:"ways"`
		TotalSummary TotalSummary `json:"totalSummary"`
	}{
		Ways:         ways,
		TotalSummary: totalSummary,
	}
	c.Data["json"] = response
	c.ServeJSON()
}
