package cn.freemud.service;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.entities.db.OpenStoreIappWxappConfig;
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.VirtualStoreVo;
import cn.freemud.enums.AggregationTypeEnum;
import cn.freemud.enums.OrderTackCodeFactory;
import cn.freemud.enums.TakeCodeOrderType;
import cn.freemud.manager.OrderTackCodeManager;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.business.impl.OrderBusinessServiceImpl;
import cn.freemud.service.impl.PayServiceImpl;
import cn.freemud.utils.ResponseUtil;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformIappWxappStore;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.application.sdk.api.log.ErrorLog;
import lombok.RequiredArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @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 RedisCache redisCache;
    private final AssortmentCustomerInfoManager assortmentCustomerInfoManager;

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

    /**
     * 生成取餐码
     * @param partnerId 商户号
     * @param storeCode 门店号
     * @param orderType 订单类型 {@link com.freemud.application.sdk.api.ordercenter.enums.OrderType}
     * @param orderClient 订单渠道 {@link com.freemud.application.sdk.api.ordercenter.enums.OrderClientType}
     * @return 取餐码
     */
    public String genTakeCode(String partnerId, String storeCode, Integer orderType, Integer orderClient) {
        Integer type = TakeCodeOrderType.getTakeCodeOrderType(orderType);
        return orderTackCodeManager.generateTackCode(type,
                partnerId,
                storeCode,
                null,
                OrderTackCodeFactory.getByOrderClient(orderClient.toString()).getGenerateTackCodeFunc());
    }


    /**
     * 获取超时时间, 生成取餐码
     * @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());
        PaySuccessDataVo vo = new PaySuccessDataVo();
        vo.setTakeCode(takeCode);
        vo.setTimeout(orderBusinessService.getPaySuccessTimeout(reqVo.getPartnerId(), reqVo.getStoreId(), reqVo.getOrderType()));
        return vo;
    }


    /**
     * 新商城支付门店配置
     */
    public PayConfigVo getMallPayConfig(GetMallPayConfigVo req) {
        PayConfigVo vo = new PayConfigVo();
        vo.setPrincipalName(payService.getPaymentPrincipalName(req.getPartnerId(), req.getAppId()));
        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();
    }

    /**
     * 订单宝暂无appid，返回支付关联的appid用于储值校验记录支付退款用，
     * 后续有订单宝appid时，这个接口废弃
     */
    public VirtualStoreVo getPayVirtualStore(String partnerId, String type) {
        //订单宝购买储值卡支付虚拟门店，订单宝暂无appid
        AssortmentOpenPlatformIappWxappStore virtualStore = payService.getVirtualStore(partnerId, type);
        VirtualStoreVo resp = new VirtualStoreVo();
        resp.setStoreId(virtualStore == null ? "" : virtualStore.getStoreId());
        resp.setAppId(virtualStore == null ? "" : virtualStore.getWxAppId());
        return resp;

    }

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

    public BaseResponse getOpenStoreIappWxappConfig(OpenStoreIappWxappConfigRequestVo openStoreIappWxappConfigRequestVo){
        // 获取用户信息
        AssortmentCustomerInfoVo assortmentCustomerInfoVo = assortmentCustomerInfoManager.getCustomerInfoByObject(openStoreIappWxappConfigRequestVo.getSessionId());
        //缓存为空则初始化为展示备注,默认备注为空,
        OpenStoreIappWxappConfig defauleConfig = new OpenStoreIappWxappConfig();
        defauleConfig.setTakeInside(1);
        defauleConfig.setInsideRemark("");
        defauleConfig.setTakeOutRemark("");
        OpenStoreIappWxappConfig config;
        try {
            config = redisCache.hashGet(RedisKeyConstant.KGD_ORDER_OPEN_STORE_IAPP_WXAPP_CONFIG_WXAPPID_, assortmentCustomerInfoVo.getWxAppId());
            if (null == config) {
                config = new OpenStoreIappWxappConfig();
                BeanUtils.copyProperties(config,defauleConfig);
                return ResponseUtil.success(config);
            }else{
                return ResponseUtil.success(config);
            }
        }catch (Exception e){
            //异常打印日常日志，返回默认config
            ErrorLog.errorConvertJson(this.getClass(),"getOpenStoreIappWxappConfig",e);
            return ResponseUtil.success(defauleConfig);
        }
    }
}
