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

import com.jeequan.jeepay.core.entity.MchApp;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.rqrs.transfer.TransferOrderRQ;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.pay.ctrl.ApiController;
import com.jeequan.jeepay.pay.service.TransferOrderReissueService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import com.jeequan.jeepay.service.impl.RateConfigService;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
* 转账接口
*
* @author terrfly
*
* @date 2021/8/11 11:07
*/
@Slf4j
@RestController
public class TransferOrderController extends ApiController {

    @Autowired private IConfigContextQueryService configContextQueryService;
    @Autowired private TransferOrderService transferOrderService;
    @Autowired private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired private TransferOrderReissueService transferOrderReissueService;
    @Autowired private RateConfigService rateConfigService;


//    /**
//     * 转账
//     * **/
//    @MethodLog(remark = "发起转账订单API")
//    @PostMapping("/api/transferOrder")
//    public ApiRes transferOrder(){
//
//        TransferOrderEntity transferOrder = null;
//
//        //获取参数 & 验签
//        TransferOrderRQ bizRQ = getRQByWithMchSign(TransferOrderRQ.class);
//
//        try {
//
//
//            String mchNo = bizRQ.getMchNo();
//            String appId = bizRQ.getAppId();
//            String ifCode = bizRQ.getIfCode();
//
//            // 商户订单号是否重复
//            if(transferOrderService.count(TransferOrderEntity.gw().eq(TransferOrderEntity::getMchNo, mchNo).eq(TransferOrderEntity::getMchOrderNo, bizRQ.getMchOrderNo())) > 0){
//                throw new BizException("商户订单["+bizRQ.getMchOrderNo()+"]已存在");
//            }
//
//            if(StringUtils.isNotEmpty(bizRQ.getNotifyUrl()) && !StringKit.isAvailableUrl(bizRQ.getNotifyUrl())){
//                throw new BizException("异步通知地址协议仅支持http:// 或 https:// !");
//            }
//
//            // 商户配置信息
//            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfoV2(mchNo, appId,bizRQ.getMchNo());
//            if(mchAppConfigContext == null){
//                throw new BizException("获取商户应用信息失败");
//            }
//
//            MchInfo mchInfo = mchAppConfigContext.getMchInfo();
//            MchApp mchApp = mchAppConfigContext.getMchApp();
//
//            // 是否已正确配置
//            if(!payInterfaceConfigService.mchAppHasAvailableIfCode(appId, ifCode)){
//                throw new BizException("应用未开通此接口配置!");
//            }
//
//
//            ITransferService transferService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(ifCode) + "TransferService", ITransferService.class);
//            if(transferService == null){
//                throw new BizException("无此转账通道接口");
//            }
//
//            if(!transferService.isSupport(bizRQ.getEntryType())){
//                throw new BizException("该接口不支持该入账方式");
//            }
//
//            // 查询商户的转账费率
//            PaywayFee paywayFee = rateConfigService.queryTransferCreateOrderPaywayFee(mchAppConfigContext.getMchApplyment().getApplyId(), mchAppConfigContext.getMchApplyment().getIsvNo(), mchAppConfigContext.getAppId(), ifCode, CS.PAY_WAY_CODE.TRANSFER);
//
//            transferOrder = genTransferOrder(bizRQ, mchInfo, mchApp, ifCode, paywayFee);
//
//            //预先校验
//            String errMsg = transferService.preCheck(bizRQ, transferOrder);
//            if(StringUtils.isNotEmpty(errMsg)){
//                throw new BizException(errMsg);
//            }
//
//            // 入库
//            transferOrderService.save(transferOrder);
//
//            // 调起上游接口
//            ChannelRetMsg channelRetMsg = transferService.transfer(bizRQ, transferOrder);
//
//            //处理转账单状态
//            transferOrderReissueService.processChannelMsg(channelRetMsg, transferOrder);
//
//            TransferOrderRS bizRes = TransferOrderRS.buildByRecord(transferOrder);
//
//            return ApiResKit.okWithSign(bizRes, mchApp, bizRQ.getSignType());
//
//        }  catch (BizException e) {
//            return ApiRes.customFail(e.getMessage());
//
//        } catch (ChannelException e) {
//
//            //处理上游返回数据
//            transferOrderReissueService.processChannelMsg(e.getChannelRetMsg(), transferOrder);
//
//            if(e.getChannelRetMsg().getChannelState() == ChannelRetMsg.ChannelState.SYS_ERROR ){
//                return ApiRes.customFail(e.getMessage());
//            }
//
//            TransferOrderRS bizRes = TransferOrderRS.buildByRecord(transferOrder);
//
//            return ApiResKit.okWithSign(bizRes, configContextQueryService.queryMchApp(bizRQ.getMchNo(), bizRQ.getAppId()), bizRQ.getSignType());
//
//        } catch (Exception e) {
//            log.error("系统异常：{}", e);
//            return ApiRes.customFail("系统异常");
//        }
//    }


    private TransferOrderEntity genTransferOrder(TransferOrderRQ rq, MchInfo mchInfo, MchApp mchApp, String ifCode, PaywayFee paywayFee){

        TransferOrderEntity transferOrder = new TransferOrderEntity();
        transferOrder.setTransferId(SeqKit.genTransferId()); //生成转账订单号
        transferOrder.setMchNo(mchInfo.getMchNo()); //商户号
//        transferOrder.setIsvNo(mchInfo.getIsvNo()); //服务商号
        transferOrder.setAgentNo(mchInfo.getAgentNo()); // 服务商号
        transferOrder.setAppId(mchApp.getAppId()); //商户应用appId
        transferOrder.setMchName(mchInfo.getMchShortName()); //商户名称（简称）
        transferOrder.setMchType(mchInfo.getType()); //商户类型
        transferOrder.setMchOrderNo(rq.getMchOrderNo()); //商户订单号
        transferOrder.setIfCode(ifCode); //接口代码
        transferOrder.setEntryType(rq.getEntryType()); //入账方式
        transferOrder.setAmount(rq.getAmount()); //订单金额
        transferOrder.setCurrency(rq.getCurrency()); //币种
        transferOrder.setClientIp(StringUtils.defaultIfEmpty(rq.getClientIp(), getClientIp())); //客户端IP
        transferOrder.setState(TransferOrderEntity.STATE_INIT); //订单状态, 默认订单生成状态
        transferOrder.setAccountNo(rq.getAccountNo()); //收款账号
        transferOrder.setAccountName(rq.getAccountName()); //账户姓名
        transferOrder.setBankName(rq.getBankName()); //银行名称
        transferOrder.setTransferDesc(rq.getTransferDesc()); //转账备注
        transferOrder.setExtParam(rq.getExtParam()); //商户扩展参数
        transferOrder.setNotifyUrl(rq.getNotifyUrl()); //异步通知地址

        // 转账手续费，  可以为空。
        if(paywayFee != null){
            MutablePair<String, Long> feeAndSnapshot = paywayFee.calFeeAndSnapshot(transferOrder.getAmount());
            transferOrder.setMchFeeRate(feeAndSnapshot.left);
            transferOrder.setMchOrderFeeAmount(feeAndSnapshot.right); //商户手续费,单位分
        }

        transferOrder.setCreatedAt(new Date()); //订单创建时间
        return transferOrder;

    }

}
