package cn.freemud.service.store;

import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.StoreResponseDto;
import cn.freemud.entities.dto.store.BusinessInfoDto;
import cn.freemud.entities.dto.store.StoreMixResponseDto;
import cn.freemud.entities.dto.store.StoreBaseResponseDto;
import cn.freemud.entities.dto.store.StoreInfoRequestDto;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.thirdparty.StoreClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.function.Consumer;

/**
 * @author Clover.z
 * @Date 2021/10/20
 * @Desc
 */
@Service
@RequiredArgsConstructor
public class StoreManager {

    private final StoreClient storeClient;


    /**
     * 查询门店相关聚合信息
     * @param partnerId 商户号
     * @param storeCode 门店号
     * @param q 设置查询数据的func
     * @return 门店聚合信息
     */
    public StoreMixResponseDto queryStoreMixInfo(String partnerId, String storeCode, Consumer<StoreInfoRequestDto.QueryInfo> q) {
        StoreInfoRequestDto request = new StoreInfoRequestDto(partnerId, storeCode);
        StoreInfoRequestDto.QueryInfo query = new StoreInfoRequestDto.QueryInfo();
        q.accept(query);
        request.setQuery(query);
        StoreBaseResponseDto<StoreMixResponseDto> response = storeClient.getStoreInfoNew(request);
        if (null == response || !ResponseCodeConstant.RESPONSE_SUCCESS.equals(response.getStatusCode()) || null == response.getBizVO()) {
            throw new ServiceException(ResponseResult.STORE_DATE_ERROR);
        }
        return response.getBizVO();
    }


    /**
     * 查询门店信息
     * @param partnerId 商户号
     * @param storeCode 门店号
     * @return 门店信息
     */
    public StoreResponseDto queryStoreInfo(String partnerId, String storeCode) {
        StoreMixResponseDto mix = this.queryStoreMixInfo(partnerId, storeCode, query -> {
            query.setQueryStoreInfo(true);
        });
        if (null == mix.getStoreInfo()) {
            throw new ServiceException("门店不存在");
        }
        return mix.getStoreInfo();
    }


    /**
     * 查询门店业务配置信息
     * @param partnerId 商户号
     * @param storeCode 门店号
     * @return 门店业务配置信息
     */
    public BusinessInfoDto queryStoreBusiness(String partnerId, String storeCode) {
        StoreMixResponseDto mix = this.queryStoreMixInfo(partnerId, storeCode, query -> {
            query.setQueryBusinessInfo(true);
        });
        if (null == mix.getBusinessInfo()) {
            throw new ServiceException("门店未初始化业务配置");
        }
        return mix.getBusinessInfo();
    }
}
