package com.jeequan.jeepay.thirdparty.channel.alipay;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.converter.TransferConverter;
import com.jeequan.jeepay.core.beans.RequestKitBean;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import com.jeequan.jeepay.thirdparty.channel.AbstractTransferNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

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

/**
 * TODO
 *
 * @author deng
 * @since 2024/5/8
 */
@Service
@Slf4j
public class AliaqfTransferNoticeService extends AbstractTransferNoticeService {

    @Autowired
    private RequestKitBean requestKitBean;

    @Autowired
    private TransferOrderService transferOrderService;

    @Autowired
    private TransferConverter transferConverter;

    @Override
    public String getIfCode() {
        return CS.IF_CODE.ALIAQF;
    }

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId) {
        JSONObject reqParamJSON = requestKitBean.getReqParamJSON();
        log.info("【支付宝安全发接口回调】, 原始参数为{}", reqParamJSON);

        String input = reqParamJSON.getString("input");
        if (ObjUtil.isEmpty(input)) {
            return new MutablePair<>();
        }

        String[] params = input.split("&");

        JSONObject decryptParam = new JSONObject();
        for (String paramItem : params) {
            String[] real = paramItem.split("=");
            if (real.length != 2) {
                log.info("回调参数格式不正确, {}", paramItem);
                return new MutablePair<>();
            }

            try {
                decryptParam.put(URLDecoder.decode(real[0], "UTF-8"),URLDecoder.decode(real[1], "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("参数解析异常, {}", real[1], e);
            }
        }

        JSONObject bizContent = decryptParam.getJSONObject("biz_content");
        log.info("【支付宝安全发接口回调】, 解密后业务参数为{}", bizContent);

        String outBizNo = bizContent.getString("out_biz_no");
        return new MutablePair<>(outBizNo, bizContent);
    }

    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, TransferOrder transferOrder) {
        JSONObject bizContent = ((JSONObject) params);
        ChannelRetMsg result = new ChannelRetMsg();
        result.setChannelOrderId(bizContent.getString("order_id"));
        result.setPlatformOrderNo(bizContent.getString("pay_fund_order_id"));
        result.setChannelOriginResponse(bizContent.toJSONString());
        switch (bizContent.getString("status")){
            case "SUCCESS" :
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                break;
            case "CLOSED" :
            case "FAIL" :
                result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                result.setChannelErrMsg(bizContent.getString("sub_order_fail_reason"));
                break;
            default:
                result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                transferOrder.setState(TransferOrderEntity.STATE_ING);
                break;
        }

        ResponseEntity<Object> ok = ResponseEntity.ok(retOk(null));
        result.setResponseEntity(ok);

        return result;
    }
}
