package cn.iocoder.yudao.module.app.apy;

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.order.service.RepairOrderInfoService;
import cn.iocoder.yudao.util.WechatPayConfig;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 维修模块 支付模块")
@RestController
@RequestMapping("/userClient/pay")
@Validated
public class RepairPayApi {
    @Resource
    private RepairOrderInfoService repairOrderInfoService;
    @Resource
    private WechatPayConfig wechatPayConfig;
    /**
     * 支付吊起接口
     * @param orderId 订单主键
     * @return
     */
    @GetMapping("/toPay")
    @TenantIgnore
    public CommonResult<Map<String, Object>> payTransactions(String orderId) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
        Map<String, Object> res = repairOrderInfoService.payTransactions(orderId);
        return success(res);
    }

    @GetMapping("/toPayCode")
    @TenantIgnore
    public CommonResult<Map<String, Object>> toPayCode(String orderId) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
        Map<String, Object> res = repairOrderInfoService.payTransactionsCode(orderId);
        return success(res);
    }
    private final ReentrantLock lock = new ReentrantLock();
    @PostMapping("/payNotify")
    @TenantIgnore
    public Map<String, String> payNotify(@RequestBody JSONObject jsonObject) {
        System.out.println("进入支付回调"+jsonObject.toString());
        try {
            String key = wechatPayConfig.getApiV3Key();
            String json = jsonObject.toString();
            String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
            String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
            String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");
            String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
            //验签成功
            JSONObject decryptDataObj = JSONObject.parseObject(decryptData, JSONObject.class);
            System.out.println("进入支付回调"+decryptDataObj.toString());
            if(lock.tryLock()) {
                try {
                    String orderNo = decryptDataObj.get("out_trade_no").toString();
                    repairOrderInfoService.rechargeCallback(orderNo);
                } catch (Exception ignored){

                }  finally{
                    //要主动释放锁
                    lock.unlock();
                }
            }
        }catch (Exception e){
            System.out.println("支付回调失败"+e.getMessage());
        }

        Map<String, String> res = new HashMap<>();
        res.put("code", "SUCCESS");
        res.put("message", "成功");
        return res;
    }

}
