package com.jeequan.jeepay.pay.ctrl.aqf;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.params.alipay.AlipayConfig;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.TransferInterfaceConfigEntity;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.service.impl.TransferInterfaceConfigService;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import com.jeequan.jeepay.service.impl.TransferSubjectService;
import com.jeequan.jeepay.thirdparty.channel.alipay.AliAqfV2Service;
import com.jeequan.jeepay.thirdparty.util.ChannelCertConfigKitBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
public class AliAqfController extends AbstractCtrl {


    @Autowired
    protected TransferInterfaceConfigService transferInterfaceConfigService;
    @Autowired
    private TransferSubjectService transferSubjectService;
    @Autowired
    private AliAqfV2Service aliAqfV2Service;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private TransferOrderService transferOrderService;

    /**
     * 解约回调方法
     * @param request
     * @throws AlipayApiException
     */
    @RequestMapping("/api/anf/reqUnsign")
    public String reqUnsign(HttpServletRequest request) {

        // TODO: 2024/4/25 回调参数暂时先不处理！！
      /*  logger.info("进入了安全发的解约回调！！！");
        JSONObject reqParamJSON = getReqParamJSON();
        TransferSubjectEntity subjectEntity = transferSubjectService.getOne(TransferSubjectEntity.gw().eq(TransferSubjectEntity::getExternalAgreementNo, reqParamJSON.getString("external_agreement_no")));
        try {
            //验签
            boolean resut = getcertAliPayRequest(reqParamJSON);
            if (!resut){
                logger.error("安全发回调验签失败："+ reqParamJSON.toJSONString());
                subjectEntity.setRemark("安全发解约回调验签失败");
            }else {
                logger.info("签约回调通知参数为："+ reqParamJSON.toJSONString());
                //已解约
                subjectEntity.setSignState(3);
            }
        }catch (Exception e){
            logger.error("安全发签约回调处理数据出现异常！！");
            subjectEntity.setRemark("安全发签约回调处理数据出现异常");
        }
        logger.info("解约回调通知参数为："+ reqParamJSON.toJSONString());
        transferSubjectService.updateById(subjectEntity);*/
        return "success";
    }

    /**
     * 资金专项拨入,代发回调
     * @param request
     * @return
     */
    @RequestMapping("/api/anf/orderChanged")
    public ApiRes orderChanged(String request) {
        JSONObject reqParamJSON = getReqParamJSON();
        log.info("【】回调参数"+reqParamJSON);

        String input = reqParamJSON.getString("input");
        String[] requestSplit = input.split("&");

        for (String requestSplitFor : requestSplit) {
            String[] real = requestSplitFor.split("=");
            if (real.length == 2){
                try {
                    reqParamJSON.put(URLDecoder.decode(real[0], "UTF-8"),URLDecoder.decode(real[1], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error("解析回调参数异常！！");
                    return ApiRes.customFail("解析回调参数异常!");
                }
            }else {
                return ApiRes.customFail("参数格式不正确!");
            }
        }
        log.info("解析后的回调参数"+reqParamJSON);
        JSONObject bizContent = reqParamJSON.getJSONObject("biz_content");
        TransferOrderEntity transferOrder = transferOrderService.getById(bizContent.getString("out_biz_no"));
        switch (bizContent.getString("status")){
            case "SUCCESS" :
                transferOrder.setState(TransferOrderEntity.STATE_SUCCESS);
                transferOrder.setSuccessTime(new Date());
                if (bizContent.containsKey("order_id")){
                    transferOrder.setChannelOrderNo(bizContent.getString("order_id"));
                }
                if (bizContent.containsKey("pay_fund_order_id")){
                    transferOrder.setFlowNo(bizContent.getString("pay_fund_order_id"));
                }
                break;
            case "WAIT_PAY" :
                transferOrder.setState(TransferOrderEntity.STATE_ING);
                break;
            case "CLOSED" :
                transferOrder.setState(TransferOrderEntity.STATE_CLOSED);
                break;
            case "FAIL" :
                transferOrder.setState(TransferOrderEntity.STATE_FAIL);
                break;
            case "DEALING" :
                transferOrder.setState(TransferOrderEntity.STATE_ING);
                break;
            default:
                transferOrder.setState(TransferOrderEntity.STATE_ING);
                break;
        }
        transferOrder.setChannelExtra(reqParamJSON.toJSONString());
        transferOrderService.updateById(transferOrder);
        return ApiRes.ok();
    }

    /**
     * 代发到户回调   暂时无用！
     * @param request
     * @return
     */
    @RequestMapping("/api/anf/accountOrderChanged")
    public ApiRes accountOrderChanged(String request) {

        logger.info("进入了代发到户回调！！！");
        log.info("代发到户回调参数"+request);
        JSONObject reqParamJSON = new JSONObject();

        String[] requestSplit = request.split("&");
        for (String requestSplitFor : requestSplit) {
            String[] real = requestSplitFor.split("=");
            if (real.length == 2){
                try {
                    reqParamJSON.put(URLDecoder.decode(real[0], "UTF-8"),URLDecoder.decode(real[1], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error("解析回调参数异常！！");
                    return ApiRes.customFail("解析回调参数异常!");
                }
            }
        }
        log.info("解析后的代发到户回调参数"+reqParamJSON);
        TransferOrderEntity transferOrder = transferOrderService.getOne(TransferOrderEntity.gw().eq(TransferOrderEntity::getChannelOrderNo, reqParamJSON.getJSONObject("biz_content").getString("order_id")));
        switch (reqParamJSON.getJSONObject("biz_content").getString("status")){
            case "SUCCESS" :
                transferOrder.setState((byte) 2);
                transferOrder.setSuccessTime(new Date());
                break;
            case "WAIT_PAY" :
                transferOrder.setState((byte) 1);
                break;
            case "CLOSED" :
                transferOrder.setState((byte) 4);
                break;
            case "FAIL" :
                transferOrder.setState((byte) 3);
                break;
            case "DEALING" :
                transferOrder.setState((byte) 1);
                break;
            default:
                transferOrder.setState((byte) 1);
                break;
        }
        transferOrder.setChannelExtra(reqParamJSON.toJSONString());
        transferOrderService.updateById(transferOrder);
        return ApiRes.ok();
    }

    /**
     * 代发到卡   暂时无用！
     * @param request
     * @return
     */
    @RequestMapping("/api/anf/cardOrderChanged")
    public ApiRes cardOrderChanged(String request) {

        logger.info("进入了资金专项拨入回调！！！");
        log.info("专项资金拨入回调参数"+request);
        JSONObject reqParamJSON = new JSONObject();

        String[] requestSplit = request.split("&");
        for (String requestSplitFor : requestSplit) {
            String[] real = requestSplitFor.split("=");
            if (real.length == 2){
                try {
                    reqParamJSON.put(URLDecoder.decode(real[0], "UTF-8"),URLDecoder.decode(real[1], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    log.error("解析回调参数异常！！");
                    return ApiRes.customFail("解析回调参数异常!");
                }
            }
        }
        log.info("解析后的专项资金拨入回调参数"+reqParamJSON);
        TransferOrderEntity transferOrder = transferOrderService.getOne(TransferOrderEntity.gw().eq(TransferOrderEntity::getChannelOrderNo, reqParamJSON.getJSONObject("biz_content").getString("order_id")));
        switch (reqParamJSON.getJSONObject("biz_content").getString("status")){
            case "SUCCESS" :
                transferOrder.setState((byte) 2);
                transferOrder.setSuccessTime(new Date());
                break;
            case "WAIT_PAY" :
                transferOrder.setState((byte) 1);
                break;
            case "CLOSED" :
                transferOrder.setState((byte) 4);
                break;
            case "FAIL" :
                transferOrder.setState((byte) 3);
                break;
            case "DEALING" :
                transferOrder.setState((byte) 1);
                break;
            default:
                transferOrder.setState((byte) 1);
                break;
        }
        transferOrder.setChannelExtra(reqParamJSON.toJSONString());
        transferOrderService.updateById(transferOrder);
        return ApiRes.ok();
    }

    public boolean getCertAliPayRequest(JSONObject reqParamJSON ){
        boolean resut= true;
        try {
            String externalAgreementNo = reqParamJSON.getString("external_agreement_no");
            TransferSubjectEntity subjectServiceOne = transferSubjectService.getOne(TransferSubjectEntity.gw().eq(TransferSubjectEntity::getTransApplyId, externalAgreementNo));
            TransferInterfaceConfigEntity transferInterfaceConfigEntity = transferInterfaceConfigService.list(TransferInterfaceConfigEntity.gw().eq(TransferInterfaceConfigEntity::getTransIfCode, "AQF")
                    .eq(TransferInterfaceConfigEntity::getInfoId, subjectServiceOne.getIsvNo())).stream().findFirst().orElse(null);
            if (transferInterfaceConfigEntity != null){
                ChannelCertConfigKitBean channelCertConfigKitBean = SpringBeansUtil.getBean(ChannelCertConfigKitBean.class);
                JSONObject jsonTransIfParams = JSONObject.parseObject(transferInterfaceConfigEntity.getTransIfParams());
                resut= AlipaySignature.rsaCertCheckV1(reqParamJSON.toJavaObject(Map.class), channelCertConfigKitBean.getCertFilePath(jsonTransIfParams.getString("alipayPublicKey")),
                        AlipayConfig.CHARSET, "RSA2");
            }
        }catch (Exception e){
            resut=false;
        }

        return resut;
    }
}
