package cn.freemud.fuyou.service;

import cn.freemud.enums.PayChannelEnum;
import cn.freemud.enums.ResponseResult;
import cn.freemud.fuyou.controller.request.BaseRequest;
import cn.freemud.fuyou.controller.request.DiscountRequest;
import cn.freemud.fuyou.controller.request.PayQueryRequest;
import cn.freemud.fuyou.feign.ScoreFeignClient;
import cn.freemud.fuyou.service.processor.EventProcessorRegister;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.constant.ResponseConstant;
import com.freemud.application.sdk.api.ordercenter.request.PaySuccessReq;
import com.freemud.application.sdk.api.ordercenter.response.BaseResponse;
import com.freemud.application.sdk.api.ordercenter.response.PaySuccessResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.paymentcenter.client.request.PaymentQueryOrderRequest;
import com.freemud.application.sdk.api.paymentcenter.client.response.PaymentQueryOrderResponse;
import com.freemud.application.sdk.api.paymentcenter.client.service.PaymentNewService;
import com.freemud.sdk.api.assortment.order.enums.PayStatus;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;


/**
 * 订单优惠服务
 */
@Component(value = "orderPaymentService")
@Slf4j
public class PaymentService {


    private final EventProcessorRegister eventProcessorRegister;
    private final FuYouOrderService fuYouOrderService;
    private final PaymentNewService paymentNewService;
    protected final OrderSdkService orderSdkService;
    private final MapperFacade mapperFacade;

    public PaymentService(EventProcessorRegister eventProcessorRegister,
                          FuYouOrderService fuYouOrderService, PaymentNewService paymentNewService,
                          OrderSdkService orderSdkService, MapperFacade mapperFacade) {
        this.eventProcessorRegister = eventProcessorRegister;
        this.fuYouOrderService = fuYouOrderService;
        this.paymentNewService = paymentNewService;
        this.orderSdkService = orderSdkService;
        this.mapperFacade = mapperFacade;
    }

    /**
     * 付款 支持 svc,微信，支付宝
     *
     * @param request
     * @return
     */
    public BaseResponse payment(BaseRequest request) {
        //支持的支付方式
        Map<Integer, PayChannelEnum> channelEnumMap = ImmutableMap.of(PayChannelEnum.SVC.getCode(), PayChannelEnum.SVC,
                PayChannelEnum.WECHAT.getCode(), PayChannelEnum.WECHAT,
                PayChannelEnum.ALIPAY.getCode(), PayChannelEnum.ALIPAY
        );
        PayChannelEnum payChannelEnum = channelEnumMap.get(request.getPayChannel());
        if (Objects.isNull(payChannelEnum)) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setCode(ResponseResult.PAY_ERROR.getCode());
            baseResponse.setMessage(ResponseResult.PAY_ERROR.getMessage());
            return baseResponse;
        }
        DiscountRequest discountRequest = mapperFacade.map(request, DiscountRequest.class);
        return eventProcessorRegister.getEventProcessor(payChannelEnum.getCode()).process(discountRequest);
    }



    /**
     * 查询支付结果，微信，支付宝，svc
     *
     * @param request
     * @return
     */
    public BaseResponse paymentQuery(PayQueryRequest request) {

        QueryByCodeResponse queryByCodeResponse  = orderSdkService.getOrderInfo(request.getOrderClient(), null,request.getThirdOrderCode(),null, LogThreadLocal.getTrackingNo());
        if (ObjectUtils.notEqual(ResponseConstant.SUCCESS_RESPONSE_CODE, queryByCodeResponse.getCode())) {
            throw  new RuntimeException(queryByCodeResponse.getMessage());
        }
        OrderInfoReqs order = queryByCodeResponse.getResult();

        log.info("paymentQuery:request:{}", JSON.toJSONString(request));
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(ResponseConstant.SUCCESS_RESPONSE_CODE);
        PaymentQueryOrderRequest channelRequest = new PaymentQueryOrderRequest();
        channelRequest.setPartnerId(request.getPartnerId());
        channelRequest.setVer("2");
        channelRequest.setStoreId(request.getStoreId());
        channelRequest.setTransId(order.getOrderCode());
        channelRequest.setFrontTransId(order.getOrderCode());
        channelRequest.setStationId(request.getPosId());
        com.freemud.application.sdk.api.base.BaseResponse<PaymentQueryOrderResponse> query = paymentNewService.queryOrder(channelRequest, LogThreadLocal.getTrackingNo());
        baseResponse.setCode(query.getCode());
        baseResponse.setMessage(query.getMessage());
        if (ObjectUtils.notEqual(query.getCode(), ResponseConstant.SUCCESS_RESPONSE_CODE)) {
            log.error("scoreFeignClient.query,error:{},入参:{}", JSON.toJSONString(query), JSON.toJSONString(channelRequest));
            return baseResponse;
        }

        //final PayChannelEnum payChannelEnum = getPayChannelEnum(request.getPayChannel());
        PaySuccessReq req = new PaySuccessReq();
        req.setOrderCode(order.getOrderCode());
        req.setActualPayAmount(String.valueOf(query.getData().getAmount()));
        req.setPayChannel(query.getData().getPayCode());
        req.setPayRequestNo(query.getData().getTransactionCode());
        // (0-未支付,1-已支付,2-已冲正,3-已退款，4-已关闭)
        String tradeState = query.getData().getStatus();
        if (ObjectUtils.equals(tradeState, "1")) {
            // 订单状态已更改
            if (Objects.equals(order.getPayState(), PayStatus.HAVE_PAID.getCode())) {
                return baseResponse;
            }
            //更改订单状态
            BaseResponse<PaySuccessResp> paySuccessRespBaseResponse = orderSdkService.paySuccess(req, LogThreadLocal.getTrackingNo());
            if (ObjectUtils.notEqual(paySuccessRespBaseResponse.getCode(), ResponseConstant.SUCCESS_RESPONSE_CODE)) {
                log.error("orderSdkService.orderAffirm.query,error:{},入参:{}", JSON.toJSONString(query), JSON.toJSONString(channelRequest));
                baseResponse.setCode(paySuccessRespBaseResponse.getCode());
                baseResponse.setMessage(paySuccessRespBaseResponse.getMessage());
                return baseResponse;
            }
        } else if (ObjectUtils.equals(tradeState, "2") ||
                ObjectUtils.equals(tradeState, "3")) {
                 // 优惠冲正
             fuYouOrderService.rectification(order,"支付失败，已关单");
        } else {
            baseResponse.setCode(ResponseResult.PAY_BACKEND_CONFIG_ERROR.getCode());
            baseResponse.setCode("未支付");
            baseResponse.setResult(query);
        }
        return baseResponse;

    }


}
