package cn.freemud.service;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.order.PayConfigVo;
import cn.freemud.entities.vo.order.PaySuccessDataVo;
import cn.freemud.entities.vo.order.QueryByKeysReq;
import cn.freemud.entities.vo.order.QueryByKeysResp;
import cn.freemud.enums.AggregationTypeEnum;
import cn.freemud.enums.OrderTackCodeFactory;
import cn.freemud.enums.TakeCodeOrderType;
import cn.freemud.manager.OrderTackCodeManager;
import cn.freemud.service.business.impl.OrderBusinessServiceImpl;
import cn.freemud.service.impl.PayServiceImpl;
import cn.freemud.service.thirdparty.OrderServiceClient;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformIappWxappStore;
import com.freemud.application.sdk.api.ordercenter.adapter.OrderCenterSdkAdapter;
import com.freemud.application.sdk.api.ordercenter.enums.BizTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.MarketTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author Clover.z
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class ExposureOrderService {

    private final PayServiceImpl payService;
    private final OrderTackCodeManager orderTackCodeManager;
    private final OrderBusinessServiceImpl orderBusinessService;
    private final OrderCenterSdkAdapter orderCenterSdkAdapter;
    private final OrderServiceClient orderServiceClient;

    public PayConfigVo getPayConfig(GetPayConfigVo req) {
        PayConfigVo vo = new PayConfigVo();
        vo.setPrincipalName(payService.getPaymentPrincipalName(req.getPartnerId(), req.getAppId()));
        vo.setPayTimeOut(payService.getPartnerPayOvertime(req.getPartnerId()));
        vo.setPayCode(payService.getPayCodeByCondition(req.getAppId(), req.getStoreId(), req.getChannel()));
        return vo;
    }

    public PaySuccessDataVo getPaySuccessData(GetPaySuccessDataRequest reqVo) {
        Integer type = TakeCodeOrderType.getTakeCodeOrderType(reqVo.getOrderType());
        String takeCode = orderTackCodeManager.generateTackCode(type,
                reqVo.getPartnerId(),
                reqVo.getStoreId(),
                null,
                OrderTackCodeFactory.getByOrderClient(reqVo.getOrderClient()).getGenerateTackCodeFunc());

        Integer v1Type = orderCenterSdkAdapter.getOldOrderType(reqVo.getOrderType());
        Integer timeout = orderBusinessService.getPaySuccessTimeout(reqVo.getPartnerId(),
                reqVo.getStoreId(),
                v1Type);
        PaySuccessDataVo vo = new PaySuccessDataVo();
        vo.setTakeCode(takeCode);
        vo.setTimeout(timeout);
        return vo;
    }

    /**
     * 获取超时时间, 生成取餐码，上线后删除getPaySuccessData
     * @param reqVo
     * @return
     */
    public PaySuccessDataVo getPaySuccessDataV2(GetPaySuccessDataV2Request reqVo) {
        Integer type = TakeCodeOrderType.getTakeCodeOrderType(reqVo.getOrderType());
        String takeCode = orderTackCodeManager.generateTackCode(type,
                reqVo.getPartnerId(),
                reqVo.getStoreId(),
                null,
                OrderTackCodeFactory.getByOrderClient(reqVo.getOrderClient()).getGenerateTackCodeFunc());

        Integer timeout = 0;
        //查询待支付订单时效配置
        BaseResponse<List<QueryByKeysResp>> listBaseResponse = orderServiceClient.queryByKeys(new QueryByKeysReq(reqVo.getPartnerId()));
        if (listBaseResponse == null || !Objects.equals("100", listBaseResponse.getCode())) {
            timeout = 30;
        }
        Integer v1Type = orderCenterSdkAdapter.getOldOrderType(reqVo.getOrderType());
        for(QueryByKeysResp resp : listBaseResponse.getResult()){
            // 外卖订单
            if (Objects.equals(v1Type, OrderTypeV1.TAKE_OUT.getCode()) && Objects.equals("UNPAID_TIMEOUT_CLOSE_TIME_WMXF",resp.getConfigName())) {
                timeout = Integer.valueOf(resp.getConfigValue());
            }else if(Objects.equals(reqVo.getBizType(), BizTypeEnum.ORDINARY.getBizType()) && (Objects.equals(reqVo.getMarketingType(), MarketTypeEnum.ORDER.getIndex()) || Objects.equals(reqVo.getMarketingType(), MarketTypeEnum.CASHIER.getIndex()) )
                && Objects.equals("UNPAID_TIMEOUT_CLOSE_TIME_TSXF",resp.getConfigName())){
                //堂食先付
                timeout = Integer.valueOf(resp.getConfigValue());
            }else if(Objects.equals(reqVo.getBizType(), BizTypeEnum.ORDINARY.getBizType()) && Objects.equals(reqVo.getMarketingType(), MarketTypeEnum.POST_ORDER.getIndex())
                    && Objects.equals("UNPAID_TIMEOUT_CLOSE_TIME_TSHF",resp.getConfigName())){
                //堂食后付
                timeout = Integer.valueOf(resp.getConfigValue());
            }
        }
        PaySuccessDataVo vo = new PaySuccessDataVo();
        vo.setTakeCode(takeCode);
        vo.setTimeout(timeout);
        return vo;
    }


    /**
     * 新商城支付门店配置
     */
    public PayConfigVo getMallPayConfig(GetMallPayConfigVo req) {
        PayConfigVo vo = new PayConfigVo();
        vo.setPrincipalName(payService.getPaymentPrincipalName(req.getPartnerId(), req.getAppId()));
        vo.setPayTimeOut(payService.getPartnerPayOvertime(req.getPartnerId()));
        AssortmentOpenPlatformIappWxappStore wxAppStore = payService.getIappWxappStoreInfo(req.getAppId(), AggregationTypeEnum.TYPE_7.getCode());
        if (wxAppStore == null) {
            wxAppStore = new AssortmentOpenPlatformIappWxappStore();
        }
        vo.setPayCode(StringUtils.isEmpty(wxAppStore.getClientCode()) ? "9" : wxAppStore.getClientCode());
        vo.setStoreId(wxAppStore.getStoreId());
        return vo;
    }

    /**
     * 查询支付虚拟门店配置
     * @param appId 小程序应用appId
     * @param type 虚拟门店类型 {@link AggregationTypeEnum}
     * @return 虚拟门店号
     */
    public String getVirtualStore(String appId, String type) {
        AssortmentOpenPlatformIappWxappStore wxAppStore = payService.getIappWxappStoreInfo(appId, type);
        return wxAppStore == null ? "" : wxAppStore.getStoreId();
    }

    /**
     * 查询支付配置paycode
     */
    public String getPayCode(GetPayCodeVo req) {
        return payService.getPayCode(req.getAppId(), req.getStoreId(), req.getChannel());
    }
}
