package org.jeecg.modules.subwayNetwork.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.dto.PageSearch;
import org.jeecg.modules.subwayNetwork.dto.TrainStationEditDTO;
import org.jeecg.modules.subwayNetwork.dto.TrainStationQueryDTO;
import org.jeecg.modules.subwayNetwork.mapper.TrainStationMapper;
import org.jeecg.modules.subwayNetwork.service.ITrainStationService;
import org.jeecg.modules.subwayNetwork.entity.TrainStation;
import org.jeecg.modules.subwayNetwork.vo.LightRailQueryVO;
import org.jeecg.modules.subwayNetwork.vo.TrainStationVO;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Description: 线路车站-地铁站
 * @Author: jeecg-boot
 * @Date: 2023-06-14
 * @Version: V1.0
 */
@Service
public class TrainStationServiceImpl extends ServiceImpl<TrainStationMapper, TrainStation> implements ITrainStationService {

    @Override
    public IPage<TrainStationVO> queryPageList(PageSearch<TrainStationQueryDTO> dto) {
        IPage<LightRailQueryVO> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        return this.baseMapper.queryPageList(page, dto.getQuery());
    }

    @Override
    public void edit(TrainStationEditDTO dto) {
        // 1.计算站长度:终点里程-起始里程
        BigDecimal length = dto.getEndMileage().subtract(dto.getStartingMileage());


        // 2.通过id判断是保存还是修改
        if (ObjectUtil.isEmpty(dto.getId())) {
            Integer seq = 1;
            TrainStation exist = this.lambdaQuery().eq(TrainStation::getLightRailId, dto.getLightRailId())
                    .eq(TrainStation::getStationName, dto.getStationName())
                    .last("limit 1")
                    .one();
            if (ObjectUtil.isEmpty(exist)) {
                List<TrainStation> list = this.lambdaQuery()
                        .eq(TrainStation::getLightRailId, dto.getLightRailId())
                        .groupBy(TrainStation::getStationName)
                        .list();
                seq = list.size() + 1;
            } else {
                seq = exist.getSeq();
            }


            TrainStation trainStation = BeanUtil.copyProperties(dto, TrainStation.class);
            trainStation.setLength(length);
            trainStation.setSeq(seq);
            this.save(trainStation);
        } else {
            TrainStation trainStation = BeanUtil.copyProperties(dto, TrainStation.class);
            trainStation.setLength(length);
            this.updateById(trainStation);
        }


    }

}
