package cn.freemud.service.business.impl;

import cn.freemud.entities.dto.GetMemberExtendInfoRequestDto;
import cn.freemud.entities.dto.GetMemberExtendInfoResponseDto;
import cn.freemud.service.business.OrderBusinessService;
import cn.freemud.service.thirdparty.CustomerClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.membercenter.request.GetMemberExtendInfoRequest;
import com.freemud.application.sdk.api.membercenter.response.GetMemberExtendInfoResponse;
import com.freemud.application.sdk.api.ordercenter.enums.OrderSettlementType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.PaySuccessReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderSettlementCreateReq;
import com.freemud.application.sdk.api.ordercenter.response.PaySuccessResp;
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.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
import com.freemud.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.OldOrderType;
import com.freemud.sdk.api.assortment.order.enums.PaySuccessTimeoutEnum;
import com.freemud.sdk.api.assortment.order.request.order.ConfirmOrderRequest;
import com.freemud.sdk.api.assortment.order.response.order.PayAccessResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.freemud.application.sdk.api.membercenter.constant.InterfaceAddressConstant.MEMBER_EXTEND_INFO;

/**
 * @ClassName: OrderBusinessServiceImpl
 * @Description:
 * @Author: freemud
 * @Date: 2021/6/9 下午4:12
 */
@Service
public class OrderBusinessServiceImpl implements OrderBusinessService {

    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private CustomerClient customerClient;

    @Override
    public PayAccessResponse payAccess(ConfirmOrderRequest confirmOrderRequest) {
        PaySuccessReq request = new PaySuccessReq();
        request.setPayRequestNo(confirmOrderRequest.getPayVoucher());
        request.setCompleteOrderCode(confirmOrderRequest.getCompleteOrderCode());
        request.setOrderCode(confirmOrderRequest.getOrderId());
        request.setMealCodeRule(confirmOrderRequest.getMealCodeRule());
        request.setPickUpGoodsNo(confirmOrderRequest.getPickUpGoodsNo());
        // 引入门店基础服务 查询自动制作完成配置时间，预约单单独超时任务设置
        request.setTimeout(getPaySuccessTimeout(confirmOrderRequest, request));

        if (!org.springframework.util.CollectionUtils.isEmpty(confirmOrderRequest.getOrderSettlements())) {
            List<OrderSettlementCreateReq> orderSettlementCreateReqs = new ArrayList<>();
            int size = confirmOrderRequest.getOrderSettlements().size();
            OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
            for (int i = 0; i < size; i++) {
                ConfirmOrderRequest.OrderSettlement orderSettlement = confirmOrderRequest.getOrderSettlements().get(i);
                orderSettlementCreateReq.setPlatformDiscountAmount(orderSettlement.getPlatformDiscountAmount());
                orderSettlementCreateReq.setShopDiscountAmount(orderSettlement.getShopDiscountAmount());
                orderSettlementCreateReq.setSettlementAmount(orderSettlement.getSettlementAmount());
                orderSettlementCreateReq.setNote(orderSettlement.getNote());
                orderSettlementCreateReq.setSettlementType(this
                        .convertAssortmentSettlementTypeToNewOrderSettlementType(orderSettlement.getSettlementType()));
                orderSettlementCreateReqs.add(orderSettlementCreateReq);
            }
            request.setOrderSettlementDetailList(orderSettlementCreateReqs);
        }
        request.setActualPayAmount(confirmOrderRequest.getActualPayAmount());
        request.setOperator(confirmOrderRequest.getOperator());
        if (StringUtils.isNotBlank(confirmOrderRequest.getPayChannel())) {
            request.setPayChannel(confirmOrderRequest.getPayChannel());
            request.setPayChannelName(confirmOrderRequest.getPayChannelName());
        }
        QueryOrderByIdResponse orderByIdResponse = new QueryOrderByIdResponse();
        BaseResponse<GetMemberExtendInfoResponseDto> extendInfo = new BaseResponse();
        try {
            QueryByCodeResponse codeResponse = orderSdkService.getOrderInfo(confirmOrderRequest.getProductOrderCode(),
                    0, confirmOrderRequest.getTrackingNo());
            orderByIdResponse = orderSdkAdapter.convent2QueryOrderByIdResponse(codeResponse);

            GetMemberExtendInfoRequestDto extendInfoRequest = new GetMemberExtendInfoRequestDto();
            extendInfoRequest.setMemberId(orderByIdResponse.getData().getUserId());
            extendInfoRequest.setPartnerId(orderByIdResponse.getData().getCompanyId());
            extendInfoRequest.setIsQueryGrade(1);
            extendInfoRequest.setIsQueryLabel(0);
            extendInfoRequest.setIsQueryPaid(1);
            extendInfo = customerClient.getMemberExtendInfo(extendInfoRequest);
            OrderExtInfoDto extInfoDTO = JSONObject.parseObject(orderByIdResponse.getData().getExtInfo(),
                    OrderExtInfoDto.class);
            extInfoDTO.setMemberLevel(
                    extendInfo.getData().getMemberGrade() != null ? extendInfo.getData().getMemberGrade().getRuleName()
                            : "");
            extInfoDTO.setPaidMember(CollectionUtils.isNotEmpty(extendInfo.getData().getMemberPaids()));
            extInfoDTO.setPayTransId(confirmOrderRequest.getPayTransId());
            extInfoDTO.setPayDate(confirmOrderRequest.getPayDate());
            extInfoDTO.setEndTransId(confirmOrderRequest.getEndTransId());
            request.setExtInfo(JSON.toJSONString(extInfoDTO));
            if (!StringUtils.isEmpty(confirmOrderRequest.getSpellGroupCode())) {
                request.setSpellGroupCode(confirmOrderRequest.getSpellGroupCode());
            }
        } catch (Exception e) {
            ErrorLog.printErrorLog("getMemberExtendInfoError", MEMBER_EXTEND_INFO, confirmOrderRequest, e);
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<PaySuccessResp> response = orderSdkService
                .paySuccess(request, confirmOrderRequest.getTrackingNo());
        // 获取会员信息直接返回，非空判断
        if (extendInfo.getData() == null) {
            return orderSdkAdapter.convent2PayAccessResponse(response);
        }
        return orderSdkAdapter.convent2PayAccessResponse(response);
    }

    @Override
    public Integer getPaySuccessTimeout(ConfirmOrderRequest confirmOrderRequest, PaySuccessReq request) {
        // 合阔pos 商户未接单退款超时时间
        if (confirmOrderRequest.getNotAutomaticTwistTime() != null) {
            return confirmOrderRequest.getNotAutomaticTwistTime();
        }

        Integer timeout = 0;
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest();
        storeInfoRequest.setPartnerId(confirmOrderRequest.getPartnerId());
        storeInfoRequest.setStoreCode(confirmOrderRequest.getStoreId());
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest,
                confirmOrderRequest.getTrackingNo());
        if (storeResponse != null && storeResponse.getBizVO() != null) {
            StoreResponse.Configuration configuration = storeResponse.getBizVO().getStoreConfig();
            // 配置为空超时取消订单
            if (configuration == null
                    || org.apache.commons.lang.StringUtils.isBlank(configuration.getOverTimeCloseOrder())) {
                timeout = 30;
            }
            // 超时关单开启
            if (configuration != null && ObjectUtils.equals("1", configuration.getOverTimeCloseOrder())
                    && StringUtils.isNotBlank(configuration.getOverTimeCloseOrderTime())) {
                timeout = Integer.parseInt(configuration.getOverTimeCloseOrderTime());
            }
            // isAutoTakeOrder = 3为服务端超时接单
            if ("3".equals(storeResponse.getBizVO().getIsAutoTakeOrder())) {
                // 外卖订单
                if (confirmOrderRequest.getOrderType() == OldOrderType.TAKE_OUT.getCode()) {
                    timeout = PaySuccessTimeoutEnum.getMin(configuration.getTakeOutAutomaticOrderTime());
                } else {
                    timeout = PaySuccessTimeoutEnum.getMin(configuration.getPickUpAutomaticOrderTime());
                }
            }
        }
        return timeout;
    }

    private Integer convertAssortmentSettlementTypeToNewOrderSettlementType(OldOrderAccountType settlementType) {
        if (settlementType == OldOrderAccountType.WEIXIN) {
            return OrderSettlementType.WEIXIN.getIndex();
        }
        return -1;
    }
}
