package org.jeecg.modules.subwayNetwork.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.dto.PageSearch;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.subwayNetwork.dto.TrainStationEditDTO;
import org.jeecg.modules.subwayNetwork.dto.TrainStationQueryDTO;
import org.jeecg.modules.subwayNetwork.entity.*;
import org.jeecg.modules.subwayNetwork.service.ILightRailService;
import org.jeecg.modules.subwayNetwork.service.ILineAliasService;
import org.jeecg.modules.subwayNetwork.service.ISectionStationMapService;
import org.jeecg.modules.subwayNetwork.service.ITrainStationService;
import org.jeecg.modules.subwayNetwork.vo.TrainStationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 线路车站-地铁站
 * @Author: jeecg-boot
 * @Date: 2023-06-14
 * @Version: V1.0
 */
@Api(tags = "线路车站-地铁站")
@RestController
@RequestMapping("/subwayNetwork/trainStation")
@Slf4j
public class TrainStationController extends JeecgController<TrainStation, ITrainStationService> {
    @Resource
    private ITrainStationService trainStationService;

    @Resource
    private ISectionStationMapService sectionStationMapService;

    @Resource
    private ILightRailService lightRailService;

    @Resource
    private ILineAliasService lineAliasService;

    @AutoLog(value = "线路车站-地铁站-分页列表查询")
    @ApiOperation(value = "线路车站-地铁站-分页列表查询", notes = "线路车站-地铁站-分页列表查询")
    @PostMapping(value = "/list")
    public Result<IPage<TrainStationVO>> queryPageList(@RequestBody PageSearch<TrainStationQueryDTO> dto) {
        IPage<TrainStationVO> pageList = trainStationService.queryPageList(dto);
        return Result.OK(pageList);
    }


    @AutoLog(value = "线路车站-地铁站-编辑")
    @ApiOperation(value = "线路车站-地铁站-编辑", notes = "线路车站-地铁站-编辑")
    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody TrainStationEditDTO dto) {
        LightRail lightRail = lightRailService.getById(dto.getLightRailId());
        LineAlias lineAlias = lineAliasService.getById(dto.getLineAliasId());
        BigDecimal lightRailEndMileage = lightRail.getUpLineMileage();
        if (lineAlias.getLineAliasName().contains("下行")) {
            lightRailEndMileage = lightRail.getDownLineMileage();
        }
        if (dto.getEndMileage().compareTo(lightRailEndMileage) > 0) {
            throw JeecgBootException.error("新增车站结束里程超过:" + lightRail.getRailLineName() + "的" + lineAlias.getLineAliasName() + "的结束里程【" + lightRailEndMileage + "】");
        }


        List<TrainStation> listRecord = this.service.lambdaQuery()
                .eq(TrainStation::getLightRailId, dto.getLightRailId())
                .eq(TrainStation::getLineAliasId, dto.getLineAliasId())
                .list();
        for (TrainStation record : listRecord) {
            // 如果是更新，排除自己
            if (record.getId().equals(dto.getId())) {
                continue;
            }
            if(record.getStationName().equals(dto.getStationName())){
                throw JeecgBootException.error("同一线路,线别下已存在该站名");
            }


            BigDecimal currentStartMileage = record.getStartingMileage();
            BigDecimal currentEndMileage = record.getEndMileage();

            BigDecimal startMileage = dto.getStartingMileage();
            BigDecimal endMileage = dto.getEndMileage();


            // 判断区间是否重叠
            if (currentStartMileage.compareTo(startMileage) >= 0 && currentEndMileage.compareTo(endMileage) <= 0) {
                throw JeecgBootException.error("你输入的站点里程范围【" + dto.getStartingMileage() + "~" + dto.getEndMileage() + "】;" +
                        "冲突车站名称:" + record.getStationName() + ",里程范围【" + record.getStartingMileage() + "~" + record.getEndMileage() + "】");
            }

            // 判断开始里程是否是否冲突
            if (currentStartMileage.compareTo(startMileage) < 0 && currentEndMileage.compareTo(startMileage) > 0) {
                throw JeecgBootException.error("你输入的站点里程范围【" + dto.getStartingMileage() + "~" + dto.getEndMileage() + "】;" +
                        "冲突车站名称:" + record.getStationName() + ",里程范围【" + record.getStartingMileage() + "~" + record.getEndMileage() + "】");
            }

            // 判断结束里程是否是否冲突
            if (currentStartMileage.compareTo(endMileage) < 0 && currentEndMileage.compareTo(endMileage) > 0) {
                throw JeecgBootException.error("你输入的站点里程范围【" + dto.getStartingMileage() + "~" + dto.getEndMileage() + "】;" +
                        "冲突车站名称:" + record.getStationName() + ",里程范围【" + record.getStartingMileage() + "~" + record.getEndMileage() + "】");
            }
        }


        trainStationService.edit(dto);

        return Result.OK("编辑成功!");
    }


    @AutoLog(value = "线路车站-地铁站-通过id删除")
    @ApiOperation(value = "线路车站-地铁站-通过id删除", notes = "线路车站-地铁站-通过id删除")
    @GetMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        // 区间线路关联是否都删除了
        Long sectionStationMapCount = sectionStationMapService.lambdaQuery()
                .eq(SectionStationMap::getStationId, id)
                .count();
        if (sectionStationMapCount > 0) {
            throw new JeecgBootException("该车站下面还有关联区间");
        }

        trainStationService.removeById(id);
        return Result.OK("删除成功!");
    }


    @AutoLog(value = "线路车站-地铁站-批量删除")
    @ApiOperation(value = "线路车站-地铁站-批量删除", notes = "线路车站-地铁站-批量删除")
    @GetMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        String message = "";
        Integer totalNum = 0;
        Integer successNum = 0;
        Integer failNum = 0;
        String failMessage = " ";


        // 1.查询待删除的数据
        List<TrainStation> list = this.service.lambdaQuery()
                .in(TrainStation::getId, Arrays.asList(ids.split(",")))
                .list();
        for (TrainStation trainStation : list) {
            totalNum++;
            Long sectionStationMapCount = sectionStationMapService.lambdaQuery()
                    .eq(SectionStationMap::getStationId, trainStation.getId())
                    .count();
            if (sectionStationMapCount > 0) {
                failNum++;
                failMessage = failMessage + trainStation.getStationName() + " ";
                continue;
            }
            successNum++;

            this.service.removeById(trainStation.getId());
        }

        message = "选中" + totalNum + "条数据已删除数据" + successNum + "条";

        if (totalNum - successNum > 0) {
            message = message + ",未删除" + failNum + "条。未删除" + failMessage + "车站下面有关联区间故不能被删除!";
        }

        return Result.batchDelete(message);
    }


    @AutoLog(value = "线路车站-地铁站-获取全部车站")
    @ApiOperation(value = "线路车站-地铁站-获取全部车站", notes = "线路车站-地铁站-获取全部车站")
    @GetMapping(value = "/listAll")
    public Result<List<Map<String, Object>>> listAll() {
        List<TrainStation> pageList = trainStationService.list();

        List<Map<String, Object>> list = new ArrayList<>();
        for (TrainStation trainStation : pageList) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", trainStation.getStationName());
            map.put("value", trainStation.getId());
            map.put("lineAliasCode", trainStation.getLineAliasId());
            map.put("lightRailId", trainStation.getLightRailId());
            list.add(map);
        }
        return Result.OK(list);
    }

}
