/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CouponService
 * @Package cn.freemud.service
 * @Description:
 * @author: pengfei.liu
 * @date: 2020/11/23
 * @version V1.0
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.delivery.impl;

import cn.freemud.entities.dto.store.GetEstimateDeliveryRequest;
import cn.freemud.entities.dto.store.StoreCBaseResponse;
import cn.freemud.entities.dto.store.StoreCBaseResponseDto;
import cn.freemud.entities.vo.ShoppingCartGoodsResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.delivery.DeliveryService;
import cn.freemud.service.store.StoreBaseApiClient;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.membercenter.request.QueryReceiveAddressRequest;
import com.freemud.application.sdk.api.membercenter.response.QueryReceiveAddressResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.storecenter.request.QueryDeliveryRequest;
import com.freemud.application.sdk.api.storecenter.response.QueryDeliverDetailResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("gradDeliveryService")
public class GradDeliveryServiceImpl extends AbstractDeliveryServiceImpl implements DeliveryService {

    @Autowired
    private MemberCenterService memberCenterService;

    @Autowired
    private StoreCenterService storeCenterService;

    @Autowired
    private StoreBaseApiClient storeBaseApiClient;

    @Override
    public Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {

        String trackingNo = LogThreadLocal.getTrackingNo();

        QueryReceiveAddressRequest queryReceive = new QueryReceiveAddressRequest(receiveId, partnerId);
        //查询会员收获地址经纬度
        com.freemud.application.sdk.api.base.BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(queryReceive, trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
            throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
        }
        // fisherman  新配送费计算 调用门店接口
        StoreCBaseResponseDto deliveryDataMsg = getDeliveryDataMsg(queryReceiveAddressResponse.getData().getLatitude(),
                queryReceiveAddressResponse.getData().getLongitude(),
                partnerId,
                storeId);
        if (Objects.isNull(deliveryDataMsg.getDeliveryAmount())) {
            throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
        }

        shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(deliveryDataMsg.getDeliveryFeeZeroReason() != null ? deliveryDataMsg.getDeliveryFeeZeroReason() : 0);
        return deliveryDataMsg.getDeliveryAmount();

//        // 查询运费详情
//        QueryDeliveryRequest queryDeliveryRequest = new QueryDeliveryRequest();
//        queryDeliveryRequest.setPartnerId(partnerId);
//        queryDeliveryRequest.setStoreCode(storeId);
//        queryDeliveryRequest.setUserLatitude(queryReceiveAddressResponse.getData().getLatitude());
//        queryDeliveryRequest.setUserLongitude(queryReceiveAddressResponse.getData().getLongitude());
//        com.freemud.application.sdk.api.base.BaseResponse<QueryDeliverDetailResponse> queryDeliverDetailResponse = storeCenterService.queryDeliverDetail(queryDeliveryRequest, trackingNo);
//        if (queryDeliverDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(queryDeliverDetailResponse.getCode()) || queryDeliverDetailResponse.getData() == null) {
//            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
//        }
//        if(queryDeliverDetailResponse.getData().getDeliveryAmount() == null) {
//            throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
//        }
//        shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() != null ? queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() : 0);
//
//        return queryDeliverDetailResponse.getData().getDeliveryAmount();
    }

    @Override
    public Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId) {

        String trackingNo = LogThreadLocal.getTrackingNo();

        QueryReceiveAddressRequest queryReceive = new QueryReceiveAddressRequest(receiveId, partnerId);
        //查询会员收获地址经纬度
        com.freemud.application.sdk.api.base.BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(queryReceive, trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
            throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
        }

        // 查询运费详情
        QueryDeliveryRequest queryDeliveryRequest = new QueryDeliveryRequest();
        queryDeliveryRequest.setPartnerId(partnerId);
        queryDeliveryRequest.setStoreCode(storeId);
        queryDeliveryRequest.setUserLatitude(queryReceiveAddressResponse.getData().getLatitude());
        queryDeliveryRequest.setUserLongitude(queryReceiveAddressResponse.getData().getLongitude());
        com.freemud.application.sdk.api.base.BaseResponse<QueryDeliverDetailResponse> queryDeliverDetailResponse = storeCenterService.queryDeliverDetail(queryDeliveryRequest, trackingNo);
        if (queryDeliverDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(queryDeliverDetailResponse.getCode()) || queryDeliverDetailResponse.getData() == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
        }
        if(queryDeliverDetailResponse.getData().getDeliveryAmount() == null) {
            throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
        }

        return queryDeliverDetailResponse.getData().getDeliveryAmount();
    }
    /**
     * 获取 配送费 及预计送达时间接口
     * @param userLat       用户纬度
     * @param userLong      用户经度
     * @param partnerId     商户号
     * @param storeCode     门店号
     * @return
     */
    private StoreCBaseResponseDto getDeliveryDataMsg(String userLat,
                                                     String userLong,
                                                     String partnerId,
                                                     String storeCode) {
        boolean check = StringUtils.isEmpty(userLat) ||
                StringUtils.isEmpty(userLong) ||
                StringUtils.isEmpty(partnerId) ||
                StringUtils.isEmpty(storeCode);
        if (check) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING);
        }
        // 调用门店接口 获取时间  Fisherman
        GetEstimateDeliveryRequest request = GetEstimateDeliveryRequest.builder().latitude(userLat).longitude(userLong).build();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeCode);
        StoreCBaseResponse<StoreCBaseResponseDto> responseDto = storeBaseApiClient.queryDeliverDetail(request);
        ApiLog.info("fisherman 获取门店预计送达时间",request,responseDto);
        if (responseDto == null) {
            throw new ServiceException(ResponseResult.SYSTEM_BUSINESS_ERROR);
        }

        if(!ResponseResult.SUCCESS.getCode().equals(responseDto.getCode()) || responseDto.getResult() == null){
            throw new ServiceException(ResponseResult.STORE_QUERYEXPECTARRIVETIME);
        }
        return responseDto.getResult();
    }

}
