package com.gree.mall.miniapp.controller.common;

import com.gree.mall.miniapp.annotation.ApiNotAuth;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.user.PayLogic;
import com.gree.mall.miniapp.utils.CommonUtils;
import com.gree.mall.miniapp.utils.WeChatUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
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 java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@RequestMapping(value = "/pay", produces = "application/json; charset=utf-8")
public class PayController {

    @Autowired
    PayLogic payLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;
    static ExecutorService threadPool = Executors.newFixedThreadPool(4);



    @ApiNotAuth
    @PostMapping("/payCall")
    @ApiOperation(value = "支付回调", notes = "支付回调 ", httpMethod = "POST")
    public String payCall(@RequestBody String body) throws RemoteServiceException, JDOMException, IOException {

        Map<String, String> params = CommonUtils.doXMLParse(body);
        //String id = params.get("out_trade_no");//订单号
        String id = params.get("attach");
        String transactionId = params.get("transaction_id");//微信支付单号
        BigDecimal totalFee = new BigDecimal(params.get("total_fee")).divide(BigDecimal.valueOf(100));//
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + id);

        threadPool.submit(() -> {
            try {
                log.info("==========支付回调开始：{}", body);
                if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
                    log.error("【支付回调】，请勿重复请求，orderId:{}",id);
                }else{
                    if ("XM,XP".contains(id.substring(0, 2))) {
                        // 辅材、配件
                        payLogic.payCall2(id, transactionId, totalFee, params);
                    } else if ("BS".contains(id.substring(0, 2))) {
                        // 软件服务
                        payLogic.payCall3(id, transactionId, totalFee, params);

                    } else if ("YB".contains(id.substring(0, 2))) {
                        //延保
                        payLogic.payCall4(id, transactionId, totalFee, params);
                    } else if ("ZP".contains(id.substring(0, 2))) {
                        // 租赁
                        payLogic.payCall5(id, transactionId, totalFee, params);
                    } else if ("ES".contains(id.substring(0, 2))) {
                        // 二手订单
                        payLogic.payCall6(id, transactionId, totalFee, params);
                    } else {
                        //商城订单支付回调
                        payLogic.payCall(id, transactionId, totalFee);
                    }
                }
            }catch(Exception e) {
                log.error("处理支付回调失败",e);
            }finally {
                if(obtain != null) {
                    obtain.unlock();
                }
            }
        });

        SortedMap<Object, Object> returnData = new TreeMap<>();
        returnData.put("return_code", "SUCCESS");
        returnData.put("return_msg", "OK");
        return WeChatUtils.getRequestXml(returnData);
    }


    @ApiNotAuth
    @PostMapping("/refundCall")
    @ApiOperation(value = "退款回调", notes = "退款回调 ", httpMethod = "POST")
    public String refundCall(@RequestBody String body) throws Exception {

       // String s = payLogic.refundCall(body);

        SortedMap<Object, Object> returnData = new TreeMap<>();
        returnData.put("return_code", "SUCCESS");
        returnData.put("return_msg", "OK");
        return WeChatUtils.getRequestXml(returnData);
    }

    @ApiNotAuth
    @PostMapping("/allinpay/callback")
    @ApiOperation(value = "通联回调")
    public String allinpayCallback(HttpServletRequest request) throws Exception {
        payLogic.allinpayCallback(request);
        return "success";
    }

}
