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

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.payment.response.PostQueryOrderResponse;
import com.neusoft.smart.pos.dto.payorder.request.PutSetPayOrderStatusRequest;
import com.neusoft.smart.pos.dto.payorder.response.PutSetPayOrderStatusResponse;
import com.neusoft.smart.pos.dto.order.response.GetOrderPayStatusResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.*;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.order.repository.OrderMasterRepository;
import com.neusoft.smart.pos.payment.persistent.ext.domain.ThirdPlatformCancelOrder;
import com.neusoft.smart.pos.payment.persistent.ext.domain.ThirdPlatformQueryOrder;
import com.neusoft.smart.pos.payment.service.PaymentService;
import com.neusoft.smart.pos.payorder.constants.PayErrorCode;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.repository.*;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service("payOrderService")
public class PayOrderService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private PayOrderRepository payOrderRepository;



    @Autowired
    private PayChannelRepository payChannelRepository;

    @Autowired
    private PayTypeDictRepository payTypeDictRepository;

    @Autowired
    private TradeMchPayDetailRepository tradeMchPayDetailRepository;

    @Autowired
    private MchPayChannelRepository mchPayChannelRepository;

    @Autowired
    private MchPayInfoRepository mchPayInfoRepository;

    @Autowired
    private PaymentService paymentService;

//    /**
//     * 支付单生成方法
//     *
//     * @return
//     */
//    public PostPayOrderResponse createPayOrder(PostCreatePayOrderRequest createPayOrderRequest) {
//        createPayOrderRequest.setPayType(DictionaryConstant.PAY_STATUS_WFK.getCode());
//        PayOrder payOrder = savePayOrder(createPayOrderRequest, null, null, null, null, null, null);
//        val payOrderResponse = new com.neusoft.smart.pos.dto.payorder.response.PostPayOrderResponse();
//        BeanUtils.copyProperties(payOrder, payOrderResponse);
//        return payOrderResponse;
//    }

    /**
     * 取消支付订单使用方法
     *
     * @param tradeId
     * @return
     */
    public boolean cancelPayOrder(String tradeId) {
        //获得支付订单
        val payOrder = payOrderRepository.getPayOrder(tradeId);
        ThirdPlatformCancelOrder thirdPlatformCancelOrder = paymentService.canclePayOrder(payOrder);
        if ("1".equals(thirdPlatformCancelOrder.getCancelStatus())) {
            return payOrderRepository.updatePayOrderStatusByTradeId(tradeId, DictionaryConstant.PAY_STATUS_YQX.getCode());
        } else {
            throw new BusinessCommonException(PayErrorCode.THIRD_PLATFORM_CANCEL_PAY_ORDER_FAIL);
        }
    }

    /**
     * 查询支付结果使用方法
     *
     * @param tradeId
     * @return
     */
    public PostQueryOrderResponse queryPayResult(String tradeId) {
        val payOrder = payOrderRepository.getPayOrder(tradeId);
//        if(paymentService.isSupportQueryPayOrder(payOrder.getPayType())){
//            throw new BusinessCommonException(PayErrorCode.PAY_TYPE_NO_SUPPORT_FUNC);
//        }
        //4.查询预付单信息
        val thirdPlatformQueryOrder = paymentService.queryPayOrder(payOrder);


        //5.判断订单状态是否有变化,更新聚合平台订单状态
        val payOrderTemp = new PayOrder();
//        payOrderTemp.setOrderStatus(thirdPlatformQueryOrder.getTradeStatus());
        if (thirdPlatformQueryOrder.getTradeStatus().equals(DictionaryConstant.PAYMENT_ORDER_STATUS_YZF.getCode())) {
            payOrderTemp.setPayStatus(DictionaryConstant.PAY_STATUS_YFK.getCode());
            payOrderTemp.setPayTime(LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.convertStringToLocalDateTime(thirdPlatformQueryOrder.getTimeEnd(), LocalDateTimeUtils.SIMPLE_DATETIME_FORMAT)));
            payOrderRepository.updatePayOrder(payOrder.getMcode(), payOrder.getTradeId(), payOrder.getmOrderNumber(), payOrderTemp);
        }

        //6.返回数据信息
        val postQueryOrderResponse = new PostQueryOrderResponse(thirdPlatformQueryOrder.getMcode(), payOrder.getPayType(), payOrder.getCodeUrl(), payOrder.getTimeExpire(), payOrder.getTradeId(), thirdPlatformQueryOrder.getOuterTradeNumber(), thirdPlatformQueryOrder.getMOrderNumber(), thirdPlatformQueryOrder.getTradeStatus());
        //val sign = SignUtils.generateSign(MapBeanUtils.beanToMap(postQueryOrderResponse),mchPayInfo.getSecretKey());
        //postQueryOrderResponse.setSign(sign);
        //LogUtils.saveMchPaymentTradeLog(thirdPlatformQueryOrder.getMcode(),thirdPlatformQueryOrder.getMOrderNumber(),queryOrderRequest.getPayType(),LogUtils.LOG_DESCRIPTION_DDCS,JSON.toJSONString(postQueryOrderResponse), JSON.toJSONString(queryOrderRequest),DictionaryConstant.PAYMENT_REQUEST_TYPE_BD.getCode());
        return postQueryOrderResponse;
    }

    /**
     * 设置支付结果方法
     *
     * @return
     */
    public boolean setPayResult(String tradeId, boolean isSuccess) {
        val payOrder = payOrderRepository.getPayOrder(tradeId);
//        if(paymentService. isSupportSetPayResult(payOrder.getPayType())){
//            throw new BusinessCommonException(PayErrorCode.PAY_TYPE_NO_SUPPORT_FUNC);
//        }
        boolean bResult = false;
        if (isSuccess) {
            bResult = payOrderRepository.updatePayOrderStatusByTradeId(tradeId, DictionaryConstant.PAY_STATUS_YFK.getCode());
        } else {
            bResult = payOrderRepository.updatePayOrderStatusByTradeId(tradeId, DictionaryConstant.PAY_STATUS_YQX.getCode());
        }
        return bResult;
    }

    /**
     * 支付订单更新状态方法
     *
     * @return
     */
    public PutSetPayOrderStatusResponse updatePayOrderStatus(PutSetPayOrderStatusRequest putSetPayOrderStatusRequest) {
        boolean bResult = payOrderRepository.updatePayOrderStatusByTradeId(putSetPayOrderStatusRequest.getTradeId(), putSetPayOrderStatusRequest.getPayOrderStatus());
        val setOrderStatusResponse = new PutSetPayOrderStatusResponse(bResult);
        return setOrderStatusResponse;
    }

    /**
     * 支付订单更新状态方法
     *
     * @return
     */
    public boolean computePayOrderStatus(String trideId) {

        return false;
    }

    /**
     * 根据订单号获得支付订单列表方法
     * @param orderNumber
     * @return
     */
    public List<PayOrder> queryPayOrderList(String orderNumber){
        return payOrderRepository.queryPayOrderByOrderNumber(orderNumber);
    }

    /**
     * 订单信息创建方法（含普通订单、充值订单、微信点餐订单）
     */
    public PayOrder createPayOrder(PayOrder payOrder) {
        //1.根据订单类型校验参数信息,并获取集团及门店ID
        validateCreatePayOrderParams(payOrder);

        //2.生成当前订单号
        if (StringUtils.isEmpty(payOrder.getTradeId())) {
            payOrder.setTradeId(IdGenerateUtils.generateTradeId());    //当前时间毫秒数+5位随机数
        }

//        val orderMaster = orderMasterRepository.queryOrderByOrderNumber(payOrder.getmOrderNumber());
//        //3.查询商户结算及聚合支付平台商户信息
//        TradeSettlementInfo tradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orderMaster.getOrgId(), orderMaster.getShopId());
//        if (null == tradeSettlementInfo) {
//            throw new BusinessCommonException(PayErrorCode.TRADE_SETTLEMENT_INFO_EMPTY);
//        }
//
//        //4.查询商户是否开通此支付方式渠道
//        Integer shopIdTemp = 0;
//        if (DictionaryConstant.SETTLEMENT_TYPE_MD.getCode().equals(tradeSettlementInfo.getSettlementType())) {
//            shopIdTemp = orderMaster.getShopId();
//        } else {
//            tradeSettlementInfo = tradeSettlementRepository.queryTradeSettlementInfo(orderMaster.getOrgId(), shopIdTemp);
//        }
//        val tradeMchPayChannel = payChannelRepository.queryShopPayChannelByPayType(orderMaster.getOrgId(), shopIdTemp, createPayOrderRequest.getPayType());
//        if (null == tradeMchPayChannel) {
//            throw new BusinessCommonException(PayErrorCode.PAY_CHANNEL_IS_NOT_OPEN);
//        }
//
//        //5.根据支付方式查询支付信息
//        val payTypeDict = payTypeDictRepository.queryEnablePayTypeDict(createPayOrderRequest.getPayType());
//        if (null == payTypeDict) {
//            throw new BusinessCommonException(PayErrorCode.DICT_PAY_TYPE_NOT_EXIST);
//        }
//
//        //7.获得openId
//        String openIdTemp;
//        if (!StringUtils.isEmpty(openIdCode) && StringUtils.isEmpty(openId)) {
//            openIdTemp = WXTokenUtils.getOpenId(tradeMchPayChannel.getAppid(), tradeMchPayChannel.getAppSecretKey(), openIdCode);
//        } else {
//            openIdTemp = openId;
//        }
//
//        TradeMchPayDetail tradeMchPayDetail = tradeMchPayDetailRepository.queryOrderByOrderNumber(orderMaster.getOrgId(), orderMaster.getShopId(), createPayOrderRequest.getPayType());
//
//        payOrder.setMcode(tradeSettlementInfo.getMcode());
//        payOrder.setDescription("商品支付订单");
//        payOrder.setPayTypeName(DictionaryConstant.getEnumByCode(DictionaryConstant.PAY_TYPE.getCode(), createPayOrderRequest.getPayType()).getValue());
//        payOrder.setNotifyUrl(payTypeDict.getNotifyUrl());
//        payOrder.setTimeExpire(DateUtils.format(orderMaster.getTimeExpire()));
//        payOrder.setScanCode(scanCode);
//        payOrder.setPayIp(ip);
//        payOrder.setOpenId(openIdTemp);
//        payOrder.setTradeType(tradeType);
//        payOrder.setDeviceId(orderMaster.getSerialNo());
//        payOrder.setDeviceName(orderMaster.getDeviceName());
//        if (null != tradeMchPayDetail) {
//            payOrder.setStoreId(tradeMchPayDetail.getStoreId());
//            payOrder.setPid(tradeMchPayDetail.getPid());
//        }

//        val returnString = paymentService.createPayOrder(payOrder);
//        if (thirdPlatformOrder != null) {
//            payOrder.setOuterOrderNumber(thirdPlatformOrder.getOuterOrderNumber());
//            payOrder.setCodeUrl(thirdPlatformOrder.getOuterCodeUrl());
//        }

        //10.创建支付单
        payOrderRepository.createPayOrder(payOrder);
        return payOrder;
    }


//    /**
//     * 普通订单订单取消方法
//     *
//     * @return
//     */
//    public PutCancelOrderResponse cancleOrder(PutCancelOrderRequest cancleOrderRequest) {
//        boolean bResult = orderMasterRepository.updateOrderStatusByOrderNumber(cancleOrderRequest.getOrderNumber(), DictionaryConstant.ORDER_UPDATE_STATUS_DFK.getCode());
//        val cancelOrderResponse = new com.neusoft.smart.pos.dto.order.response.PutCancelOrderResponse(bResult);
//        return cancelOrderResponse;
//    }
//
//    /**
//     * 普通订单自动计算并更新订单状态方法
//     *
//     * @return
//     */
//    public PutUpdateOrderStatusResponse updateOrderStatus(PutUpdateOrderStatusRequest updateOrderStatusRequest) {
//        String orderStatus = orderMasterRepository.computeOrderStatus(updateOrderStatusRequest.getOrderNumber());
//        boolean bResult = orderMasterRepository.updateOrderStatusByOrderNumber(updateOrderStatusRequest.getOrderNumber(), orderStatus);
//        val updateOrderStatusResponse = new com.neusoft.smart.pos.dto.order.response.PutUpdateOrderStatusResponse(bResult);
//        return updateOrderStatusResponse;
//    }
//
//    /**
//     * 设置订单指定状态方法
//     *
//     * @return
//     */
//    public PutSetOrderStatusResponse setOrderStatus(PutSetOrderStatusRequest setOrderStatusRequest) {
//        boolean bResult = orderMasterRepository.updateOrderStatusByOrderNumber(setOrderStatusRequest.getOrderNumber(), setOrderStatusRequest.getOrderStatus());
//        val setOrderStatusResponse = new com.neusoft.smart.pos.dto.order.response.PutSetOrderStatusResponse(bResult);
//        return setOrderStatusResponse;
//    }
//
//    /**
//     * 获得订单全部信息方法
//     *
//     * @return
//     */
//    public GetAllOrderInfoResponse getOrderInfoByOrderNumber(String orderNumber) {
//        OrderMaster orderMaster = orderMasterRepository.queryOrderByOrderNumber(orderNumber);
//        val orderInfoResponse = new com.neusoft.smart.pos.dto.order.response.GetAllOrderInfoResponse();
//        BeanUtils.copyProperties(orderMaster, orderInfoResponse);
//        return orderInfoResponse;
//    }
//
//    /**
//     * 获得订单全部商品信息方法
//     *
//     * @return
//     */
//    public GetOrderDetailsResponse getOrderGoodsListByOrderNumber(String orderNumber) {
//        GetOrderDetailsResponse orderDetailsResponse = new GetOrderDetailsResponse();
//        List<OrderTransaction> orderDetailsList = orderTransactionRepository.queryOrderDetails(orderNumber);
//        List<GetOrderDetailsModelResponse> orderDetailsModelList = ListUtils.convertListToList(orderDetailsList,GetOrderDetailsModelResponse.class);
//        orderDetailsResponse.setOrderDetails(orderDetailsModelList);
//        return orderDetailsResponse;
//    }
//
//    public PostDoPayOrderResponse doPay(PostDoPayOrderRequest doPayOrderRequest) {
//        return null;
//    }
//
//

    /**
     * 根据订单类型校验创建订单相关参数信息,并存入集团ID、门店ID
     */
    private void validateCreatePayOrderParams(PayOrder createPayOrderRequest) {
        //支付类型：现金 银行卡 微信 支付宝 云闪付 虚拟货币
        if (StringUtils.isEmpty(createPayOrderRequest.getPayType())) {
            //订单类型不能为空
            throw new BusinessCommonException(PayErrorCode.PAY_TYPE_IS_EMPTY);
        }
        if (null == createPayOrderRequest.getPayAmount()) {
            //订单支付金额不能为空
            throw new BusinessCommonException(PayErrorCode.PAY_AMOUNT_IS_EMPTY);
        }
//        if (createPayOrderRequest.getPayAmount().doubleValue() < 0) {
//            //订单支付金额输入错误
//            throw new BusinessCommonException(PayErrorCode.PAY_AMOUNT_ERROR);
//        }
    }

    /**
     * 根据支付订单ID 获得支付订单方法
     * @param tradeId
     * @return
     */
    public PayOrder getPayOrder(String tradeId) {
        return payOrderRepository.queryPayOrderByTradeId(tradeId);
    }

    /**
     * 更新支付订单信息
     * @param payOrder
     * @return
     */
    public boolean updatePayOrder(PayOrder payOrder) {
        return payOrderRepository.updatePayOrder(payOrder.getTradeId(),payOrder.getmOrderNumber(),payOrder);
    }

    /**
     * 更新支付状态接口
     * @param tradeId
     * @param status
     * @return
     */
    public boolean updatePayOrderStatus(String tradeId, String status) {
        return payOrderRepository.updatePayOrderStatusByTradeId(tradeId, status);
    }

    /**
     * 支付成功接口
     * @param tradeId
     * @param orderNumber
     * @param payTime
     * @return
     */
    public boolean paySuccess(String tradeId,String orderNumber, Date payTime) {
        PayOrder payOrder = new PayOrder();
        payOrder.setPayStatus(DictionaryConstant.PAY_STATUS_YFK.getCode());
        payOrder.setPayTime(payTime);
        return payOrderRepository.updatePayOrder(tradeId,orderNumber,payOrder);
    }

    /**
     * 支付成功接口
     * @param tradeId
     * @param orderNumber
     * @param payTime
     * @return
     */
    public boolean paySuccess(String tradeId,String orderNumber, Date payTime, String traceNo, String batchNo, String refNo, String transDate, String responseDetailInfo) {
        PayOrder payOrder = new PayOrder();
        payOrder.setPayStatus(DictionaryConstant.PAY_STATUS_YFK.getCode());
        payOrder.setPayTime(payTime);
        payOrder.setOriTraceNo(traceNo);
        payOrder.setOriBatchNo(batchNo);
        payOrder.setRetrvlRefNo(refNo);
        payOrder.setTransDate(transDate);
        payOrder.setResponseDetailInfo(responseDetailInfo);
        return payOrderRepository.updatePayOrder(tradeId,orderNumber,payOrder);
    }


    /**
     * 通过聚合支付平台查询订单支付状态查询方法
     *
     * @param serialNo
     * @param tradeId
     * @return
     */
    public GetOrderPayStatusResponse queryOrderPayStatusByThirdPlatform(String serialNo, String tradeId) {
        //1.查询订单信息，并进行校验
        val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(serialNo);
        if (null == deviceInfo) {
            throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
        }
        val orgId = deviceInfo.getOrganizationId();
        val shopId = deviceInfo.getStoreId();
        val payOrder = payOrderRepository.queryPayOrderByTradeId(tradeId);
        if (null == payOrder) {
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_INFO_NOT_EXIST);
        } else {
            val response = new com.neusoft.smart.pos.dto.order.response.GetOrderPayStatusResponse(payOrder.getPayStatus(), payOrder.getPayType());
            //2.未支付，调用聚合支付平台查询预付单信息
            if (payOrder.getPayStatus().equals(DictionaryConstant.PAY_STATUS_WFK.getCode())) {//未付款
                //3.查询商户结算及聚合支付平台商户信息

                ThirdPlatformQueryOrder outOrder = paymentService.queryPayOrder(payOrder);
                if (outOrder.getTradeStatus().equals(DictionaryConstant.PAYMENT_ORDER_STATUS_YZF.getCode())) {
                    response.setPayStatus(DictionaryConstant.PAY_STATUS_YFK.getCode());
                    response.setPaidTime(outOrder.getTimeEnd());
                }else if(outOrder.getTradeStatus().equals(DictionaryConstant.PAYMENT_ORDER_STATUS_JYGB.getCode())) {
                    response.setPayStatus(DictionaryConstant.PAY_STATUS_YQX.getCode());
                }
                return response;
            } else {
                throw new BusinessCommonException(TradeErrorCode.TRADE_STATUS_COMPUTE_ERROR);
            }
        }
    }

    public boolean updatePayOrderInfo(String tradeId){
        Long hasRefuntAmountSum = orderMasterRepository.queryHasRefundAmountSumByTradeId(tradeId);
        val payOrder = payOrderRepository.queryPayOrderByTradeId(tradeId);

        PayOrder updatePayOrder = new PayOrder();
        updatePayOrder.setRefundedAmount(hasRefuntAmountSum);
        return payOrderRepository.updatePayOrder(payOrder.getTradeId(),payOrder.getmOrderNumber(),updatePayOrder);
    }

    public PayOrder getPayOrderByOuterOrderNumber(String transNo) {
        return payOrderRepository.getPayOrderByOuterOrderNumber(transNo);
    }
}
