package com.tmerclub.cloud.delivery.feign;

import com.tmerclub.cloud.api.delivery.dto.CalculateAndGetDeliverInfoDTO;
import com.tmerclub.cloud.api.delivery.dto.DeliveryOrderDTO;
import com.tmerclub.cloud.api.delivery.dto.DeliveryOrderItemDTO;
import com.tmerclub.cloud.api.delivery.feign.DeliveryFeignClient;
import com.tmerclub.cloud.api.delivery.vo.ShopTransportVO;
import com.tmerclub.cloud.api.user.feign.UserAddrFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.api.delivery.dto.CurOderReturnsDTO;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.delivery.manager.DeliveryManager;
import com.tmerclub.cloud.delivery.manager.DeliveryPrintManager;
import com.tmerclub.cloud.delivery.service.DeliveryOrderService;
import com.tmerclub.cloud.delivery.service.TransportService;
import com.tmerclub.cloud.order.model.OrderAddr;
import com.tmerclub.cloud.order.service.OrderAddrService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author tmerclub
 * @date 2020/12/14
 */
@DubboService
public class DeliveryFeignController implements DeliveryFeignClient {
    private static final Logger logger = LoggerFactory.getLogger(DeliveryFeignController.class);
    private static final long TWO = -2;
    @Autowired
    DeliveryPrintManager deliveryPrintManager;
    @DubboReference
    private UserAddrFeignClient userAddrFeignClient;
    @Autowired
    private TransportService transportService;
    @Autowired
    private DeliveryOrderService deliveryOrderService;
    @Autowired
    private DeliveryManager deliveryManager;
    @Autowired
    private OrderAddrService orderAddrService;

    @Override
    public ServerResponseEntity<UserDeliveryInfoVO> calculateAndGetDeliverInfo(CalculateAndGetDeliverInfoDTO param) {
        return deliveryManager.calculateAndGetDeliverInfo(param);
    }

    @Override
    public ServerResponseEntity<List<ShopTransportVO>> listTransportByShopId(Long shopId) {
        List<TransportVO> list = transportService.listTransport(shopId);
        return ServerResponseEntity.success(BeanUtil.mapAsList(list, ShopTransportVO.class));
    }

    @Override
    public ServerResponseEntity<List<ShopTransportVO>> listTransportByIds(List<Long> transportIds) {
        List<ShopTransportVO> list = transportService.listTransportByIds(transportIds);
        return ServerResponseEntity.success(list);
    }

    @Override
    public ServerResponseEntity<Boolean> checkAddr(Long deliveryTemplateId, Long userId, Long addrId) {
        if (deliveryTemplateId == null || addrId == null) {
            logger.info("模板id或地址id为空，不校验");
            return ServerResponseEntity.success(false);
        }
        if (deliveryTemplateId == -1 || deliveryTemplateId == 0) {
            logger.info("固定运费或包邮，不校验");
            return ServerResponseEntity.success(true);
        }
        TransportVO transportVO = transportService.getTransportAndAllItemsById(deliveryTemplateId);
        return ServerResponseEntity.success(deliveryOrderService.checkAddr(transportVO, userId, addrId));
    }

    @Override
    public ServerResponseEntity<Boolean> checkDeliveryRange(Long deliveryTemplateId, Long addrId) {
        if (deliveryTemplateId == null || addrId == null) {
            return ServerResponseEntity.success(false);
        }
        // 查询用户地址
        UserAddrVO addrVO = userAddrFeignClient.getUserAddrByAddrId(addrId).getData();
        if (addrVO == null) {
            return ServerResponseEntity.success(false);
        }
        // 取出区域id，优先 区id -> 市id -> 省id
        Long areaId;
        if (addrVO.getAreaId() != null) {
            areaId = addrVO.getAreaId();
        } else if (addrVO.getCityId() != null) {
            areaId = addrVO.getCityId();
        } else if (addrVO.getProvinceId() != null) {
            areaId = addrVO.getProvinceId();
        } else {
            return ServerResponseEntity.success(false);
        }
        // 查询配送模板，并初步校验
        TransportVO transportVO = transportService.getTransportAndAllItemsById(deliveryTemplateId);
        if (transportVO == null || transportVO.getTransFees() == null) {
            return ServerResponseEntity.success(false);
        }
        if (transportVO.getIsFreeFee() == 1) {
            return ServerResponseEntity.success(true);
        }
        // 获取可配送的区域id集合
        List<AreaVO> areaList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (TransfeeVO transFee : transportVO.getTransFees()) {
            areaList.addAll(transFee.getCityList());
        }
        Set<Long> areaIds = areaList.stream().map(AreaVO::getAreaId).collect(Collectors.toSet());
        // 校验数据
        if (areaIds.contains(areaId)) {
            return ServerResponseEntity.success(true);
        }
        return ServerResponseEntity.success(false);
    }

    @Override
    public TransportVO getTransportAndAllItemsById(Long deliveryTemplateId) {
        return transportService.getTransportAndAllItemsById(deliveryTemplateId);
    }

    @Override
    public ServerResponseEntity<String> curOderReturns(CurOderReturnsDTO curOderReturnsDTO) {
        DeliveryOrderDTO deliveryOrderDTO = new DeliveryOrderDTO();
        // 网点id
        deliveryOrderDTO.setOutletConfigId(curOderReturnsDTO.getOutletConfigId());
        // 打印机id
        deliveryOrderDTO.setPrinterId(curOderReturnsDTO.getPrinterId());

        // 根据订单地址id查询详情
        OrderAddr orderAddr = orderAddrService.getById(curOderReturnsDTO.getOrderAddrId());

        // 收件人姓名
        deliveryOrderDTO.setConsignee(orderAddr.getConsignee());
        // 收件人手机号
        deliveryOrderDTO.setMobile(orderAddr.getMobile());
        // 订单地址id
        deliveryOrderDTO.setOrderAddrId(curOderReturnsDTO.getOrderAddrId());
        // 物流订单项
        List<DeliveryOrderItemDTO> deliveryOrderItemDTOList = new ArrayList<>();
        DeliveryOrderItemDTO deliveryOrderItemDTO = new DeliveryOrderItemDTO();
        deliveryOrderItemDTO.setSpuName("球杆");
        deliveryOrderItemDTOList.add(deliveryOrderItemDTO);
        deliveryOrderDTO.setSelectOrderItems(deliveryOrderItemDTOList);
        deliveryOrderDTO.setOrderId(1L);

        String trackingNumber = deliveryPrintManager.deliveryPrint(deliveryOrderDTO, 1, 2);
        return ServerResponseEntity.success(trackingNumber);
    }

}
