package com.hys.app.controller.erp.use;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.model.erp.dos.OrderCustomerFee;
import com.hys.app.model.erp.dos.OrderDO;
import com.hys.app.model.erp.dto.PayTypeUrl;
import com.hys.app.pay.ali.AliPayService;
import com.hys.app.pay.ali.PayOrder;
import com.hys.app.pay.ali.WxService;
import com.hys.app.service.erp.OrderCustomerFeeManager;
import com.hys.app.service.erp.OrderManager;
import com.wechat.pay.java.core.auth.WechatPay2Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/erp/pay")
@Api(tags = "订单支付")
@Validated
@AllArgsConstructor
public class PayController {
    private OrderManager orderManager;
    private AliPayService aliPayService;
    private WxService wxService;
    private OrderCustomerFeeManager orderCustomerFeeManager;

    @ApiOperation(value = "扫描完获取拉起支付的url")
    @PostMapping("/getPayUrl")
    public Object getListByScan(@RequestBody @Validated PayTypeUrl payTypeUrl) {
        OrderDO aDo = orderManager.getById(payTypeUrl.getOrderId());
        if (ObjectUtil.isNull(aDo)) {
            throw new ServiceException("未查询到订单信息");
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setTraceNo(aDo.getId().toString());

        payOrder.setSubject("租赁订单支付金额");
        payOrder.setTimeExpire(LocalDateTime.now().plusMinutes(30));
        List<OrderCustomerFee> list = orderCustomerFeeManager.list(new LambdaQueryWrapper<OrderCustomerFee>().eq(OrderCustomerFee::getOrderId, payTypeUrl.getOrderId()));
        if (CollectionUtil.isNotEmpty(list)){
            payOrder.setTotalAmount(new BigDecimal(aDo.getRealPrice()).add(list.stream().map(OrderCustomerFee::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add)).doubleValue());
        }else {
            payOrder.setTotalAmount(aDo.getRealPrice());
        }

        switch (payTypeUrl.getPayType()) {
            case "ali":
                return aliPayService.pay(payOrder);
            case "wx":
                return "暂未开通";
            default:
                return "不支持的支付方式";
        }
    }

    @PostMapping("/aliReturnCall")
    public String aliReturnCall(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        if (aliPayService.checkReturnParam(params)) {
            OrderDO aDo = orderManager.getById(params.get("out_trade_no"));
            aDo.setHasPayReturn(true);
            orderManager.updateById(aDo);
        }
        return "success";
    }
}
