package com.neusoft.smart.pos.trade.service;


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.trade.request.PostGrantPaySuccessNotifyRequest;
import com.neusoft.smart.pos.dto.trade.response.PostGrantPaySuccessNotifyResponse;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.MapBeanUtils;
import com.neusoft.smart.pos.framework.utils.SignUtils;
import com.neusoft.smart.pos.trade.persistent.domain.GrantOrderTransaction;
import com.neusoft.smart.pos.trade.repository.*;
import com.neusoft.smart.pos.payorder.repository.TradeSettlementRepository;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service("grantPayNotifyService")
public class GrantPayNotifyService {

    private final static Logger logger = LoggerFactory.getLogger(GrantPayNotifyService.class);

    @Autowired
    private GrantOrderMasterRepository grantOrderMasterRepository;

    @Autowired
    private GrantOrderTransactionRepository grantOrderTransactionRepository;

    @Autowired
    private TradeSettlementRepository tradeSettlementRepository;

    /**
     * 商户支付成功通知方法
     * @return
     */
    public PostGrantPaySuccessNotifyResponse grantPaySuccessNotify(PostGrantPaySuccessNotifyRequest grantPaySuccessNotifyRequest) {
        //1.校验参数信息
        if(StringUtils.isEmpty(grantPaySuccessNotifyRequest.getOrderNumber())){
            logger.error("支付成功回调业务订单编号不能为空");
            return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.FAIL);
        }

        //2.查询业务订单信息，并进行验证
        val grantOrderMaster = grantOrderMasterRepository.queryOrderByOrderNumber(grantPaySuccessNotifyRequest.getOrderNumber());
        if(null == grantOrderMaster){
            logger.error("支付成功回调业务订单编号错误，业务订单信息不存在");
            return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.FAIL);
        }

        //3.查询集团门店结算信息并进行签名校验
        val tradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfoByMcode(grantPaySuccessNotifyRequest.getMcode());
        val bool = SignUtils.isSignatureValid(MapBeanUtils.beanToMap(grantPaySuccessNotifyRequest),tradeSettlementInfo.getSecretKey());
        if(!bool){
            logger.error(grantPaySuccessNotifyRequest.getOrderNumber()+"支付成功回调签名验证失败");
            return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.FAIL);
        }

        //4.校验订单状态信息
        if(!grantOrderMaster.getGrantStatus().equals(DictionaryConstant.PAY_GRANT_STATUS_CLZ.getCode())){
            return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.SUCCESS);
        }

        //5.更新订单状态
        grantOrderMaster.setOuterOrderNumber(grantPaySuccessNotifyRequest.getOuterOrderNumber());
        grantOrderMaster.setAuthNo(grantPaySuccessNotifyRequest.getAuthNo());
        grantOrderMaster.setGrantTime(DateUtils.parse(grantPaySuccessNotifyRequest.getGrantTime(),DateUtils.FORMAT_LONG_UNMARK));
        grantOrderMaster.setGrantStatus(DictionaryConstant.PAY_GRANT_STATUS_YSQ.getCode());
        val updateBool = grantOrderMasterRepository.updateGrantOrderMasterInfo(grantOrderMaster);
        if(!updateBool){
            logger.error(grantPaySuccessNotifyRequest.getOrderNumber()+"支付成功回调业务订单支付状态更新失败");
            return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.FAIL);
        }

        //保存预授权订单操作明细数据
        GrantOrderTransaction grantOrderTransaction = new GrantOrderTransaction();
        grantOrderTransaction.setGrantOrderNumber(grantOrderMaster.getGrantOrderNumber());
        grantOrderTransaction.setOuterOrderNumber(grantPaySuccessNotifyRequest.getOuterOrderNumber());
        grantOrderTransaction.setOperationType(DictionaryConstant.GRANT_OPERATION_TYPE_2.getCode());
        grantOrderTransaction.setOperationName(DictionaryConstant.GRANT_OPERATION_TYPE_2.getValue());
        grantOrderTransaction.setOperationAmount(grantOrderMaster.getGrantAmount());
        grantOrderTransaction.setOperationTime(DateUtils.parse(grantPaySuccessNotifyRequest.getGrantTime(),DateUtils.FORMAT_LONG_UNMARK));
        grantOrderTransactionRepository.saveOrderTransaction(grantOrderTransaction);
        return new PostGrantPaySuccessNotifyResponse(ApplicationConstants.SUCCESS);
    }

}
