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

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.beans.RequestKitBean;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.interfaces.transfer.IChannelTransferSubjectService;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.service.impl.TransferSubjectService;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 转账主体功能开通回调
 *
 * @author deng
 * @since 2024/5/8
 */
@Slf4j
@RestController
public class TransferSubjectChannelNotifyController extends AbstractCtrl {

    @Autowired
    private RequestKitBean requestKitBean;
    @Autowired
    private TransferSubjectService transferSubjectService;

    @ResponseBody
    @RequestMapping(value = {"/api/transferSubject/notify/{ifCode}", "/api/transferSubject/notify/{ifCode}/{customApplyId}"})
    public ResponseEntity doNotify(HttpServletRequest request, @PathVariable("ifCode") String ifCode, @PathVariable(value = "customApplyId", required = false) String customApplyId) {

        JSONObject reqParamJSON = requestKitBean.getReqParamJSON();

        IChannelTransferSubjectService channelTransferSubjectService = SpringUtil.getBean(ifCode + "ChannelTransferSubjectService", IChannelTransferSubjectService.class);
        if (channelTransferSubjectService == null) {
            return ResponseEntity.ok("SUCCESS");
        }

        MutablePair<String, Object> mutablePair = channelTransferSubjectService.parseParam(request, customApplyId);

        //解析到订单号
        String applyId = mutablePair.left;
        log.info("解析数据为：applyId:{}, params:{}", applyId, mutablePair.getRight());
        log.info("代付参数, {}", reqParamJSON);

        TransferSubjectEntity transferSubject = transferSubjectService.getById(applyId);
        if (Objects.equals(transferSubject.getSignState(), (int) TransferSubjectEntity.SIGN_STATE_SUCCESS)) {
            log.info("已经完成签约，本次不再处理");
            return ResponseEntity.ok(channelTransferSubjectService.retOk(mutablePair.right));
        }

        Object result = channelTransferSubjectService.callback(mutablePair.right);
        return ResponseEntity.ok(result);
    }
}
