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

import com.alibaba.fastjson.JSON;
import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.utils.LocalDateTimeUtils;
import com.neusoft.smart.pos.framework.utils.MapBeanUtils;
import com.neusoft.smart.pos.payment.persistent.ext.domain.UnionPayNotify;
import com.neusoft.smart.pos.payment.repository.PayNotifyRepository;
import com.neusoft.smart.pos.payment.utils.LogUtils;
import com.neusoft.smart.pos.payment.utils.UnionPayUtils;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.repository.MchPayChannelRepository;
import com.neusoft.smart.pos.payorder.repository.MchPayInfoRepository;
import com.neusoft.smart.pos.payorder.repository.PayOrderRepository;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("unionPayNotifyService")
public class UnionPayNotifyService {

	@Autowired
    private MchPayChannelRepository mchPayChannelRepository;

    @Autowired
    private PayOrderRepository payOrderRepository;


    @Autowired
    private MchPayInfoRepository mchPayInfoRepository;

    @Autowired
    private PayNotifyRepository payNotifyRepository;

    /**
     * 银联支付完成通知数据处理方法
     * @param notifyMapData：银联回调数据
     * @return
     */
    public String unionPayNotifyDataHandle(Map<String,String> notifyMapData){
        if(null == notifyMapData){
            return getUnionPayResultData(ApplicationConstants.FALSE);
        }
        //1.转换数据格式
        val unionPayNotify = MapBeanUtils.mapToBean(notifyMapData,UnionPayNotify.class);  //将map转成bean对象

        //2.根据微信商户号查询微信商户信息
        String orderNumber;
        PayOrder payOrder;
        if(notifyMapData.containsKey("qrNo")){
            orderNumber = notifyMapData.get("orderNo");
            payOrder = payOrderRepository.queryPayOrderByNumber(orderNumber,DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode());
        }else{
            orderNumber = unionPayNotify.getOrderId();
            payOrder = payOrderRepository.queryPayOrderByTimeExpire(orderNumber,unionPayNotify.getTxnTime(),DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode());
        }
        if(null == payOrder || payOrder.getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            return getUnionPayResultData(ApplicationConstants.FALSE);
        }
        val mchPayChannel = mchPayChannelRepository.queryMchPayChannelByMcode(payOrder.getMcode(), DictionaryConstant.PAYMENT_PAY_TYPE_WXSM.getCode());

        //3.校验银联回调签名信息
        if(!notifyMapData.containsKey("qrNo")){
            if(!UnionPayUtils.isSignatureValid(notifyMapData)){
                LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),orderNumber, DictionaryConstant.PAYMENT_PAY_TYPE_WXSM.getCode(),LogUtils.LOG_DESCRIPTION_ZFCGHD,getUnionPayResultData(false),JSON.toJSONString(unionPayNotify),DictionaryConstant.PAYMENT_REQUEST_TYPE_BD.getCode());
                return getUnionPayResultData(false);
            }
        }

        //4.更新聚合支付平台订单支付状态信息
        if(notifyMapData.containsKey("qrNo")){
            if(notifyMapData.get("origRespCode").equalsIgnoreCase("00")){
                val payOrderTemp = new PayOrder();
                payOrderTemp.setPayTime(LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getNow()));
                payOrderTemp.setOuterOrderNumber(notifyMapData.get("voucherNum"));
                payOrderRepository.updateOrderPayStatus(payOrderTemp,mchPayChannel.getMcode(),orderNumber,DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode());
            }
        }else{
            if(unionPayNotify.getRespCode().equalsIgnoreCase("00")){
                val payOrderTemp = new PayOrder();
                payOrderTemp.setPayTime(LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getNow()));
                payOrderTemp.setOuterOrderNumber(unionPayNotify.getQueryId());
                payOrderRepository.updateOrderPayStatus(payOrderTemp,mchPayChannel.getMcode(),orderNumber,DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode());
            }
        }

        //5.回调业务系统通知方法(由于目前聚合支付平台不支持独立回调请求，所以暂时只做请求转发)
        val mchPayInfo = mchPayInfoRepository.queryMchPayInfoByMcode(mchPayChannel.getMcode(),DictionaryConstant.PAYMENT_MCH_STATUS_SHTG.getCode());
        val payOrderBiz = payOrderRepository.queryPayOrder(mchPayChannel.getMcode(),orderNumber,DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode());
        Boolean bool = payNotifyRepository.sendPayNotify(payOrderBiz,mchPayInfo.getSecretKey());
        LogUtils.savePaymentTradeLog(mchPayChannel.getMcode(),orderNumber, DictionaryConstant.PAYMENT_PAY_TYPE_YLSM.getCode(),LogUtils.LOG_DESCRIPTION_ZFCGHD,getUnionPayResultData(bool), JSON.toJSONString(notifyMapData),DictionaryConstant.PAYMENT_REQUEST_TYPE_ZD.getCode());
        return getUnionPayResultData(bool);
    }

    /**
     * 银联回调数据返回对象整理
     * @param bool
     * @return
     */
    private String getUnionPayResultData(Boolean bool){
        if(bool){
            return "ok";
        }else{
            return "error";
        }
    }

}
