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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.dto.PageSearch;
import org.jeecg.modules.subwayNetwork.dto.SubwaySectionEditDTO;
import org.jeecg.modules.subwayNetwork.dto.SubwaySectionQueryDTO;
import org.jeecg.modules.subwayNetwork.entity.SubwaySection;
import org.jeecg.modules.subwayNetwork.entity.TrainStation;
import org.jeecg.modules.subwayNetwork.mapper.SubwaySectionMapper;
import org.jeecg.modules.subwayNetwork.mapper.TrainStationMapper;
import org.jeecg.modules.subwayNetwork.service.ISubwaySectionService;
import org.jeecg.modules.subwayNetwork.vo.SubwaySectionVO;
import org.springframework.stereotype.Service;

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

/**
 * @Description: 线路车站-地铁区间
 * @Author: jeecg-boot
 * @Date: 2023-06-15
 * @Version: V1.0
 */
@Service
public class SubwaySectionServiceImpl extends ServiceImpl<SubwaySectionMapper, SubwaySection> implements ISubwaySectionService {


    @Resource
    private TrainStationMapper trainStationMapper;


    @Override
    public void edit(SubwaySectionEditDTO dto) {
        SubwaySection subwaySection = BeanUtil.copyProperties(dto, SubwaySection.class);
        if (ObjectUtil.isEmpty(dto.getId())) {
            this.save(subwaySection);
        } else {
            this.updateById(subwaySection);
        }

    }

    @Override
    public IPage<SubwaySectionVO> queryPageList(PageSearch<SubwaySectionQueryDTO> dto) {
        // 分页查询
        IPage<SubwaySectionVO> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        page = this.baseMapper.queryPageList(page, dto.getQuery());

        for (SubwaySectionVO record : page.getRecords()) {
            // 计算区间里程
            TrainStation startTrainStation = trainStationMapper.selectById(record.getStartTrainStationId());
            TrainStation endTrainStation = trainStationMapper.selectById(record.getEndTrainStationId());
            BigDecimal sectionMileage = endTrainStation.getEndMileage().subtract(startTrainStation.getEndMileage());
            record.setSectionMileage(sectionMileage);


            // 车站数量
            int trainStationNum = endTrainStation.getSeq() - startTrainStation.getSeq();
            record.setTrainStationNum(trainStationNum);
        }

        return page;

    }
}
