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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.JsonUtil;
import com.hys.app.framework.util.ScriptUtil;
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.wx.WxPayServiceMy;
import com.hys.app.service.erp.OrderCustomerFeeManager;
import com.hys.app.service.erp.OrderManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

    private static final Logger log = LoggerFactory.getLogger(ScriptUtil.class);


    @ApiOperation(value = "扫描完获取拉起支付的url")
    @PostMapping("/getPayUrl")
    public Object getListByScan(@RequestBody @Validated PayTypeUrl payTypeUrl) throws UnknownHostException, WxPayException {
        log.info("授权完成后带过来的openid-------------------------------------------------------------" + payTypeUrl.getOpenid() + "------------------------------------" + payTypeUrl.getOrderId());
        System.out.println("授权完成后带过来的openid-------------------------------------------------------------" + payTypeUrl.getOpenid() + "------------------------------------" + payTypeUrl.getOrderId());
        OrderDO aDo = orderManager.getById(payTypeUrl.getOrderId());
        if (ObjectUtil.isNull(aDo)) {
            throw new ServiceException("未查询到订单信息");
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setTraceNo(aDo.getId().toString());
        payOrder.setOpenId(payTypeUrl.getOpenid());

        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)).multiply(new BigDecimal(1 + aDo.getTaxRate() * 0.01)).doubleValue());
        } else {
            payOrder.setTotalAmount(aDo.getRealPrice() * (1 + aDo.getTaxRate() * 0.01));
        }

        switch (payTypeUrl.getPayType()) {
            case "ali":
                return aliPayService.pay(payOrder);
            case "wx":
                return wxPayServiceMy.pay(payOrder);
            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";
    }

    @PostMapping("/wxpay/notify")
    public String parseOrderNotify(@RequestBody String xmlData) {
        try {
            System.out.println("微信支付回调来了啊+11111111111111111111111111111111111111111111111111111111111");
            WxPayServiceImpl wxPayService = new WxPayServiceImpl();
            // 解析支付通知结果
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            // 处理订单逻辑
            if ("SUCCESS".equals(notifyResult.getResultCode().toUpperCase())) {
                // 支付成功
                OrderDO aDo = orderManager.getById(notifyResult.getOutTradeNo());
                aDo.setHasPayReturn(true);
                orderManager.updateById(aDo);
                // 返回成功响应给微信服务器
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }
        } catch (WxPayException e) {
            // 处理解析异常，记录日志
            e.printStackTrace();
        }
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[解析失败]]></return_msg></xml>";
    }

    @PostMapping("getOpenIdCode/{orderId}")
    public String getOpenIdCode(@PathVariable Long orderId, @RequestBody @Validated Map map) throws UnsupportedEncodingException {
        String openIdCode = wxPayServiceMy.getOpenIdCode(orderId, map.get("ip").toString());
        System.out.println("授权地址+“--------------------------------------------------------" + openIdCode + "ip-----------------" + map.get("ip").toString());
        return wxPayServiceMy.getOpenIdCode(orderId, map.get("ip").toString());
    }

    @GetMapping("/weixin/callback/openidCode")
    public void handleWeixinCallback(@RequestParam("code") String code, @RequestParam("state") String state, HttpSession session, HttpServletResponse response) throws Exception {
        System.out.println("授权回调来了啊    code=" + code + "111111111111111111111111111111111111111111111state=" + state);
        String[] split = state.split("--");
        String orderId = split[0];
        String ip = split[1];
        if (!state.equals((String) session.getAttribute("WEIXIN_OAUTH_STATE"))) {
            log.error("用户授权，state错误");
        }
        OrderDO aDo = orderManager.getById(Long.valueOf(orderId));
        if (ObjectUtil.isNull(aDo)) {
            log.error("用户授权完成后未找到订单信息：" + state);
        }
        String openId = wxPayServiceMy.getOpenId(code);
        aDo.setOpenId(openId);
        orderManager.updateById(aDo);

        double price;
        List<OrderCustomerFee> list = orderCustomerFeeManager.list(new LambdaQueryWrapper<OrderCustomerFee>().eq(OrderCustomerFee::getOrderId, aDo.getId()));
        if (CollectionUtil.isNotEmpty(list)) {
            price = new BigDecimal(aDo.getRealPrice()).add(list.stream().map(OrderCustomerFee::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add)).multiply(new BigDecimal(1 + aDo.getTaxRate() * 0.01)).doubleValue();
        } else {
            price = aDo.getRealPrice() * (1 + aDo.getTaxRate() * 0.01);
        }
        String url = ip + "#/payType?id=" + aDo.getId() + "&sn=" + aDo.getSn() + "&price=" + price + "&openid=" + openId;
        response.sendRedirect(url);



    }
    @GetMapping("/aa")
    public String handleWeixinCallback()  {
       return "aaa";
    }
}
