package com.czg.controller.user;

import com.czg.market.dto.PpPackageOrderDTO;
import com.czg.market.entity.PpPackageOrder;
import com.czg.market.service.PpPackageOrderService;
import com.czg.market.vo.PpPackageVO;
import com.czg.order.dto.CommonRefundDTO;
import com.czg.order.dto.LtPayOtherDTO;
import com.czg.constants.PayTypeConstants;
import com.czg.resp.CzgResult;
import com.czg.sa.StpKit;
import com.czg.service.order.service.PayService;
import com.czg.utils.ServletUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户端/套餐推广
 *
 * @author yjjie
 * @date 2025/12/18 18:54
 */
@Slf4j
@RestController
@RequestMapping("/user/ppOrder")
public class UPpOrderController {

    @DubboReference
    private PpPackageOrderService ppPackageOrderService;

    @Resource
    private PayService payService;

    /**
     * 小程序支付
     * payType 必填  支付方式，ALIPAY 支付宝，WECHAT 微信
     * openId  必填
     */
    @PostMapping("/pay")
    @Transactional
    public CzgResult<Map<String, Object>> exchange(HttpServletRequest request, @Validated @RequestBody LtPayOtherDTO param) {
        param.setUserId(StpKit.USER.getLoginIdAsLong());
        param.setIp(ServletUtil.getClientIP(request));
        param.setRecordId(param.getParamId());

        PpPackageOrderDTO detail = ppPackageOrderService.getOrderDetailById(param.getRecordId(), StpKit.USER.getLoginIdAsLong());

        PpPackageVO packageInfo = detail.getPackageInfo();
        // 计算订单金额
        BigDecimal price = packageInfo.getPrice();
        // 如果存在优惠层级 并且 分享人数大于 0 则计算新的价格
        if (packageInfo.getTieredDiscount() != null && !packageInfo.getTieredDiscount().isEmpty() && detail.getShareNum() > 0) {
            // 倒序遍历优惠层级
            for (int i = packageInfo.getTieredDiscount().size() - 1; i >= 0; i--) {
                PpPackageVO.TieredDiscount tieredDiscount = packageInfo.getTieredDiscount().get(i);
                if (detail.getShareNum() >= tieredDiscount.getPeopleNum()) {
                    price = tieredDiscount.getPrice();
                    break;
                }
            }
        }
        param.setPrice(price);

        log.info("用户【{}】进行套餐推广支付， 分享人数【{}】，订单金额【{}】", StpKit.USER.getLoginIdAsLong(), detail.getShareNum(), price);

        CzgResult<Map<String, Object>> result = CzgResult.success();
        CzgResult<Map<String, Object>> mapCzgResult = payService.ltPayOther(param, PayTypeConstants.SourceType.PP, "套餐推广购买");
        if (200 != mapCzgResult.getCode()) {
            return mapCzgResult;
        }
        Map<String, Object> resultMap = new HashMap<>(1);
        resultMap.put("payInfo", mapCzgResult.getData());
        resultMap.put("record", detail.getId());
        result.setData(resultMap);

        PpPackageOrder order = ppPackageOrderService.getById(param.getRecordId());
        order.setFinalPrice(price);
        ppPackageOrderService.updateById(order);

        return result;
    }

    /**
     * 申请退单
     */
    @PostMapping("/applyRefund")
    public CzgResult<Boolean> applyRefund(@RequestBody @Validated CommonRefundDTO param) {
        return CzgResult.success(ppPackageOrderService.applyRefund(param.getRecordId(), StpKit.USER.getLoginIdAsLong(), param.getReason()));
    }

    /**
     * 取消退单
     */
    @PostMapping("/cancelRefund")
    public CzgResult<Boolean> cancelRefund(@RequestBody @Validated CommonRefundDTO param) {
        return CzgResult.success(ppPackageOrderService.cancelRefund(param.getRecordId(), StpKit.USER.getLoginIdAsLong(), ""));
    }
}
