package merchant

import (
	"context"
	"kami/internal/consts"
	"kami/internal/model/entity"
	"kami/internal/service"
	"kami/utility/utils"

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

	"kami/api/merchant/v1"
)

func (c *ControllerV1) OrderQuery(ctx context.Context, req *v1.OrderQueryReq) (res *v1.OrderQueryRes, err error) {
	res = &v1.OrderQueryRes{}
	record := make([]*v1.OrderQueryRecord, 0)

	orderInfo, err := service.OrderSummary().GetOneById(ctx, req.MerchantOrderNo)
	err = utils.HandleNoRowsError(err)
	if err != nil || pointer.IsNil(orderInfo) || orderInfo.Id == 0 {
		res.List = record
		res.Total = len(record)
		return
	}

	res.BankOrderId = orderInfo.BankOrderId
	res.CreateTime = orderInfo.CreateTime
	res.Amount = mathutil.TruncRound(orderInfo.OrderAmount.InexactFloat64(), 2)

	// 添加订单信息
	if orderInfo.PayTime != nil {
		record = append(record, &v1.OrderQueryRecord{
			CreatedAt: orderInfo.CreateTime,
			Operation: "拉取订单",
		})
		record = append(record, &v1.OrderQueryRecord{
			CreatedAt: orderInfo.PayTime,
			Operation: "用户提交卡密",
		})
	} else {
		record = append(record, &v1.OrderQueryRecord{
			CreatedAt: orderInfo.CreateTime,
			Operation: "拉取订单，未上传卡密",
		})
	}
	if orderInfo.IsBlock == 1 {
		record = append(record, &v1.OrderQueryRecord{
			CreatedAt: orderInfo.UpdateTime,
			Operation: "订单被禁用",
		})
	}
	appleRecord := queryAppleCard(ctx, req.MerchantOrderNo)
	record = append(record, appleRecord...)
	redeemRecord := queryRedeemCard(ctx, req.MerchantOrderNo)
	record = append(record, redeemRecord...)

	res.Total = len(record)
	res.List = record
	return
}

func queryAppleCard(ctx context.Context, merchantOrderNo string) (record []*v1.OrderQueryRecord) {
	record = make([]*v1.OrderQueryRecord, 0)

	redeemOrderInfo, err := service.AppleOrder().GetOneByMerchantId(ctx, merchantOrderNo)
	err = utils.HandleNoRowsError(err)
	if pointer.IsNil(redeemOrderInfo) || redeemOrderInfo.Id == 0 {
		return
	}

	_, list, err2 := service.AppleOrder().GetRechargeDetails(ctx, redeemOrderInfo.OrderNo)
	err2 = utils.HandleNoRowsError(err2)
	if err2 != nil {
		return
	}

	slice.SortBy(list, func(a, b entity.V1CardAppleHistoryInfo) bool {
		return b.Id > a.Id
	})

	//查询对应充值账户
	record = append(record, slice.Map(list, func(index int, item entity.V1CardAppleHistoryInfo) *v1.OrderQueryRecord {
		return &v1.OrderQueryRecord{
			AccountName: item.AccountName,
			CreatedAt:   item.CreatedAt,
			Operation:   item.Operation,
			OrderNo:     item.OrderNo,
			Remark:      item.Remark,
		}
	})...)

	if len(record) == 1 {
		//查询所有可用账号
		accountList, _ := service.AppleAccount().GetAllNormal(ctx)
		paymentList, _ := service.SysUserPayment().GetAllByMinAmount(ctx, redeemOrderInfo.CardAmount, nil)
		if len(accountList) == 0 && len(paymentList) == 0 {
			record = append(record, &v1.OrderQueryRecord{
				OrderNo:   redeemOrderInfo.OrderNo,
				Operation: "没有可用账户",
				Remark:    "",
				CreatedAt: redeemOrderInfo.CreatedAt,
			})
		}
	}
	return record
}

func queryRedeemCard(ctx context.Context, merchantOrderNo string) (record []*v1.OrderQueryRecord) {

	record = make([]*v1.OrderQueryRecord, 0)

	redeemOrderInfo, err := service.CardRedeemOrder().GetOneByMerchantId(ctx, merchantOrderNo, nil)

	err = utils.HandleNoRowsError(err)
	if pointer.IsNil(redeemOrderInfo) || redeemOrderInfo.OrderNo == "" {
		return
	}

	_, list, err2 := service.CardRedeemOrder().GetOrderDetail(ctx, redeemOrderInfo.OrderNo)
	err2 = utils.HandleNoRowsError(err2)
	if err2 != nil {
		return
	}

	slice.SortBy(list, func(a, b *entity.V1CardRedeemOrderHistory) bool {
		return b.Id > a.Id
	})

	record = append(record, slice.Map(list, func(index int, item *entity.V1CardRedeemOrderHistory) *v1.OrderQueryRecord {
		status := consts.RedeemOrderOperationStatus(item.OperationStatus)
		return &v1.OrderQueryRecord{
			CreatedAt: item.CreatedAt,
			Operation: status.String(),
			OrderNo:   item.OrderNo,
			Remark:    item.Remark,
		}
	})...)

	if len(record) == 1 {
		//查询所有可用账号
		accountList, _ := service.CardRedeemAccount().GetAllAvailableAccount(ctx, consts.CardRedeemAccountCategory(redeemOrderInfo.Category), redeemOrderInfo.OrderAmount, nil)
		paymentList, _ := service.SysUserPayment().GetAllByMinAmount(ctx, redeemOrderInfo.OrderAmount, nil)
		if len(accountList) == 0 && len(paymentList) == 0 {
			record = append(record, &v1.OrderQueryRecord{
				OrderNo:   redeemOrderInfo.OrderNo,
				Operation: "没有可用账户",
				Remark:    "",
				CreatedAt: redeemOrderInfo.CreatedAt,
			})
		}
	}

	return
}
