
package com.tmerclub.cloud.delivery.controller.platform;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.delivery.vo.StationVO;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventStatus;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventType;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.platform.feign.OfflineHandleEventFeignClient;
import com.tmerclub.cloud.api.platform.vo.OfflineHandleEventVO;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.PrincipalUtil;
import com.tmerclub.cloud.delivery.dto.StationDTO;
import com.tmerclub.cloud.delivery.model.Station;
import com.tmerclub.cloud.delivery.service.StationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自提点信息
 *
 * @author tmerclub
 * @date 2020-12-07 15:10:01
 */
@RestController("platformStationController")
@RequestMapping("/p/station")
@Tag(name = "[平台端]自提点信息")
public class StationController {
    private static final Logger logger = LoggerFactory.getLogger(StationController.class);

    @DubboReference
    private OfflineHandleEventFeignClient offlineHandleEventFeignClient;
    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private StationService stationService;

    @GetMapping("/page")
    @Operation(summary = "获取自提点信息列表", description = "分页获取自提点信息列表")
    public ServerResponseEntity<PageVO<StationVO>> page(@Valid PageDTO pageDTO, StationDTO stationDTO) {
        if (null != stationDTO.getShopName() && !stationDTO.getShopName().isEmpty()) {
            logger.info("根据店铺名称模糊查询店铺id");
            List<Long> shopIds = shopDetailFeignClient.getShopIdsByLikeShopName(stationDTO.getShopName()).getData();
            if (shopIds.isEmpty()) {
                logger.info("查询店铺结果为空直接返回");
                return ServerResponseEntity.success(new PageVO<>());
            }
            stationDTO.setShopIds(shopIds);
        }
        PageVO<StationVO> stationPage = stationService.pageStation(pageDTO, stationDTO);
        // 平台端需补充关联店铺名称
        List<StationVO> stations = stationPage.getList();
        if (!CollectionUtils.isEmpty(stations)) {
            for (StationVO stationVO : stations) {
                if (StrUtil.isNotBlank(stationVO.getMobile()) && PrincipalUtil.isMobile(stationVO.getMobile())) {
                    stationVO.setMobile(PhoneUtil.hideBetween(stationVO.getMobile()).toString());
                }
            }
            Set<Long> shopIds = stations.stream().map(StationVO::getShopId).collect(Collectors.toSet());
            List<ShopDetailVO> shopDetails = shopDetailFeignClient.listByShopIds(new ArrayList<>(shopIds)).getData();
            if (!CollectionUtils.isEmpty(shopDetails)) {
                Map<Long, String> shopNameMap = shopDetails.stream().collect(Collectors.toMap(ShopDetailVO::getShopId, ShopDetailVO::getShopName));
                for (StationVO station : stations) {
                    station.setShopName(shopNameMap.get(station.getShopId()));
                }
            }
        }
        return ServerResponseEntity.success(stationPage);
    }

    @GetMapping
    @Operation(summary = "获取自提点信息", description = "根据stationId获取自提点信息")
    public ServerResponseEntity<StationVO> getByStationId(@RequestParam Long stationId) {
        StationVO stationVO = stationService.getByStationId(stationId);
        if (Objects.nonNull(stationVO) && StrUtil.isNotBlank(stationVO.getMobile()) && PrincipalUtil.isMobile(stationVO.getMobile())) {
            stationVO.setMobile(PhoneUtil.hideBetween(stationVO.getMobile()).toString());
        }
        if (stationVO != null && stationVO.getStatus() == -1) {
            stationVO = null;
        }
        return ServerResponseEntity.success(stationVO);
    }

    @GetMapping("/getOfflineHandleEvent/{stationId}")
    @Operation(summary = "通过自提点id获取下线信息")
    @Parameter(name = "stationId", description = "自提点id", required = true)
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEventByStationId(@PathVariable("stationId") Long stationId) {
        OfflineHandleEventVO offlineHandleEventVO = offlineHandleEventFeignClient.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.STATION.getValue(), stationId, null).getData();
        return ServerResponseEntity.success(offlineHandleEventVO);
    }

    @PostMapping("/offline")
    @Operation(summary = "下线自提点")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO eventDTO) {
        this.isExist(eventDTO.getHandleId());
        // 新增下线信息
        eventDTO.setSysType(SysTypeEnum.STATION.value());
        eventDTO.setHandleType(OfflineHandleEventType.STATION.getValue());
        offlineHandleEventFeignClient.save(eventDTO);
        // 修改门店状态
        Station station = new Station();
        station.setStationId(eventDTO.getHandleId());
        station.setStatus(2);
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditStation")
    @Operation(summary = "自提点下线审核")
    public ServerResponseEntity<Void> auditStation(@RequestBody OfflineHandleEventDTO eventDTO) {
        this.isExist(eventDTO.getHandleId());
        offlineHandleEventFeignClient.auditOfflineEvent(eventDTO);
        // 修改门店状态
        Station station = new Station();
        station.setStationId(eventDTO.getHandleId());
        if (OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue().equals(eventDTO.getStatus())) {
            station.setStatus(0);
        } else {
            station.setStatus(4);
        }
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    /**
     * 检验门店是否存在
     *
     * @param stationId 门店id
     */
    private void isExist(Long stationId) {
        StationVO stationVO = stationService.getByStationId(stationId);
        if (stationVO == null || stationVO.getStatus() == -1) {
            // 未找到该自提点信息
            throw new LuckException("未找到相应门店");
        }
    }
}
