package org.dromara.system.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.TblDzbcSite;
import org.dromara.system.domain.vo.TblDzbcSiteVo;
import org.dromara.system.mapper.TblDzbcSiteMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.TblDzbcAreaBo;
import org.dromara.system.domain.vo.TblDzbcAreaVo;
import org.dromara.system.domain.TblDzbcArea;
import org.dromara.system.mapper.TblDzbcAreaMapper;
import org.dromara.system.service.ITblDzbcAreaService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 定制班车-区域Service业务层处理
 *
 * @author Lion Li
 * @date 2025-02-12
 */
@RequiredArgsConstructor
@Service
public class TblDzbcAreaServiceImpl implements ITblDzbcAreaService {

    private final TblDzbcAreaMapper baseMapper;

    private final TblDzbcSiteMapper siteMapper;

    /**
     * 查询定制班车-区域
     */
    @Override
    public TblDzbcAreaVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询定制班车-区域列表
     */
    @Override
    public TableDataInfo<TblDzbcAreaVo> queryPageList(TblDzbcAreaBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TblDzbcArea> lqw = buildQueryWrapper(bo);
        Page<TblDzbcAreaVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<TblDzbcSiteVo> selectList = siteMapper.selectVoList();

        // hasSchedul=1 时过滤站点，只保留有未过期排班的站点
        if (bo.getHasSchedul() != null && bo.getHasSchedul() == 1) {
            List<Long> siteIdsWithSchedul = getSiteIdsWithSchedul();
            selectList = selectList.stream()
                .filter(siteVo -> siteIdsWithSchedul.contains(siteVo.getId()))
                .toList();
        }

        List<TblDzbcSiteVo> finalSelectList = selectList;
        result.getRecords().forEach(areaVo -> {
            try{
                areaVo.setSites(finalSelectList.stream().filter(siteVo -> siteVo.getAreaId().equals(areaVo.getId())).toList());
            } catch (Exception e) {
                areaVo.setSites(new ArrayList<>());
            }

        });

        return TableDataInfo.build(result);
    }

    /**
     * 获取有未过期排班的站点ID列表
     * 站点关联：有排班的路线（普通/多站点）关联的站点
     */
    private List<Long> getSiteIdsWithSchedul() {
        // 1. 普通路线的站点：站点的 areaId 等于路线的 startArea 或 endArea
        // 查询有排班的普通路线(startArea/endArea)对应的站点
        String normalSiteSql = "SELECT DISTINCT s.id FROM tbl_dzbc_site s " +
            "INNER JOIN tbl_dzbc_path p ON p.id IN " +
            "(SELECT path_id FROM tbl_dzbc_path_scheduling WHERE mdate >= CURDATE() AND path_id IS NOT NULL AND (ext2 IS NULL OR ext2->'$.type' != 2)) " +
            "WHERE s.area_id = p.start_area OR s.area_id = p.end_area";

        // 2. 多站点路线的站点：通过 path_site 表关联
        String multiSiteSql = "SELECT DISTINCT site_id FROM tbl_dzbc_path_site WHERE path_id IN " +
            "(SELECT path_id FROM tbl_dzbc_path_scheduling WHERE mdate >= CURDATE() AND path_id IS NOT NULL AND ext2->'$.type' = 2)";

        // 合并查询
        String allSiteSql = "(" + normalSiteSql + ") UNION (" + multiSiteSql + ")";

        return siteMapper.selectList(new LambdaQueryWrapper<TblDzbcSite>()
            .inSql(TblDzbcSite::getId, allSiteSql))
            .stream()
            .map(TblDzbcSite::getId)
            .toList();
    }

    /**
     * 查询定制班车-区域列表
     */
    @Override
    public List<TblDzbcAreaVo> queryList(TblDzbcAreaBo bo) {
        LambdaQueryWrapper<TblDzbcArea> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TblDzbcArea> buildQueryWrapper(TblDzbcAreaBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TblDzbcArea> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), TblDzbcArea::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getAddr()), TblDzbcArea::getAddr, bo.getAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), TblDzbcArea::getLocation, bo.getLocation());
        lqw.eq(bo.getKyzId() != null, TblDzbcArea::getKyzId, bo.getKyzId());
        lqw.eq(StringUtils.isNotBlank(bo.getExt1()), TblDzbcArea::getExt1, bo.getExt1());
        lqw.eq(StringUtils.isNotBlank(bo.getExt2()), TblDzbcArea::getExt2, bo.getExt2());
        // hasSchedul: 1-只返回有未过期排班的区域 0或不传-返回全部
        // 区域关联：站点(areaId) → 路线(startArea/endArea) 或 站点 → 多站点路线
        if (bo.getHasSchedul() != null && bo.getHasSchedul() == 1) {
            lqw.apply("id IN (" +
                // 普通路线关联的区域
                "SELECT DISTINCT id FROM tbl_dzbc_area WHERE id IN " +
                "(SELECT DISTINCT area_id FROM tbl_dzbc_site WHERE id IN " +
                "(SELECT DISTINCT start_area FROM tbl_dzbc_path WHERE id IN " +
                "(SELECT DISTINCT path_id FROM tbl_dzbc_path_scheduling WHERE mdate >= CURDATE() AND path_id IS NOT NULL AND (ext2 IS NULL OR ext2->'$.type' != 2))) " +
                "OR id IN (SELECT DISTINCT end_area FROM tbl_dzbc_path WHERE id IN " +
                "(SELECT DISTINCT path_id FROM tbl_dzbc_path_scheduling WHERE mdate >= CURDATE() AND path_id IS NOT NULL AND (ext2 IS NULL OR ext2->'$.type' != 2)))) " +
                "OR id IN (" +
                // 多站点路线关联的区域
                "SELECT DISTINCT area_id FROM tbl_dzbc_site WHERE id IN " +
                "(SELECT DISTINCT site_id FROM tbl_dzbc_path_site WHERE path_id IN " +
                "(SELECT DISTINCT path_id FROM tbl_dzbc_path_scheduling WHERE mdate >= CURDATE() AND path_id IS NOT NULL AND ext2->'$.type' = 2)))" +
                ")");
        }
        return lqw;
    }

    /**
     * 新增定制班车-区域
     */
    @Override
    public Boolean insertByBo(TblDzbcAreaBo bo) {
        TblDzbcArea add = MapstructUtils.convert(bo, TblDzbcArea.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改定制班车-区域
     */
    @Override
    public Boolean updateByBo(TblDzbcAreaBo bo) {
        TblDzbcArea update = MapstructUtils.convert(bo, TblDzbcArea.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TblDzbcArea entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除定制班车-区域
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
