package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.TblDzbcMultiSitePath;
import org.dromara.system.domain.TblDzbcPathScheduling;
import org.dromara.system.domain.TblDzbcPathSite;
import org.dromara.system.domain.TblDzbcSitePrice;
import org.dromara.system.domain.bo.TblDzbcMultiSitePathBo;
import org.dromara.system.domain.vo.TblDzbcMultiSitePathVo;
import org.dromara.system.domain.vo.TblDzbcPathSiteVo;
import org.dromara.system.domain.vo.TblDzbcSitePriceVo;
import org.dromara.system.mapper.TblDzbcMultiSitePathMapper;
import org.dromara.system.mapper.TblDzbcPathSchedulingMapper;
import org.dromara.system.mapper.TblDzbcPathSiteMapper;
import org.dromara.system.mapper.TblDzbcSitePriceMapper;
import org.dromara.system.service.ITblDzbcMultiSitePathService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class TblDzbcMultiSitePathServiceImpl implements ITblDzbcMultiSitePathService {

    private final TblDzbcMultiSitePathMapper baseMapper;
    private final TblDzbcPathSiteMapper pathSiteMapper;
    private final TblDzbcSitePriceMapper sitePriceMapper;
    private final TblDzbcPathSchedulingMapper schedulingMapper;

    @Override
    public TblDzbcMultiSitePathVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public List<TblDzbcMultiSitePathVo> queryBySiteId(Long siteId, Integer hasSchedul) {
        // 1. 查找包含该站点的所有路线ID
        LambdaQueryWrapper<TblDzbcPathSite> lqw = Wrappers.lambdaQuery();
        lqw.eq(TblDzbcPathSite::getSiteId, siteId);
        List<TblDzbcPathSite> pathSites = pathSiteMapper.selectList(lqw);

        if (pathSites == null || pathSites.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> pathIds = pathSites.stream()
            .map(TblDzbcPathSite::getPathId)
            .distinct()
            .collect(Collectors.toList());

        // 2. 如果需要过滤有排班的路线
        if (hasSchedul != null && hasSchedul == 1) {
            // 查询有未过期排班的多站点路线ID
            LambdaQueryWrapper<TblDzbcPathScheduling> schedulLqw = Wrappers.lambdaQuery();
            schedulLqw.in(TblDzbcPathScheduling::getPathId, pathIds);
            schedulLqw.ge(TblDzbcPathScheduling::getMdate, new java.util.Date());
            schedulLqw.apply("ext2->'$.type' = 2");
            List<TblDzbcPathScheduling> schedulList = schedulingMapper.selectList(schedulLqw);
            if (schedulList == null || schedulList.isEmpty()) {
                return Collections.emptyList();
            }
            pathIds = schedulList.stream()
                .map(TblDzbcPathScheduling::getPathId)
                .distinct()
                .collect(Collectors.toList());
        }

        // 3. 根据路线ID查询路线信息
        return baseMapper.selectVoBatchIds(pathIds);
    }

    @Override
    public TableDataInfo<TblDzbcMultiSitePathVo> queryPageList(TblDzbcMultiSitePathBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TblDzbcMultiSitePath> lqw = buildQueryWrapper(bo);
        Page<TblDzbcMultiSitePathVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<TblDzbcMultiSitePathVo> queryList(TblDzbcMultiSitePathBo bo) {
        LambdaQueryWrapper<TblDzbcMultiSitePath> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public TblDzbcMultiSitePathVo queryByIdWithDetails(Long id) {
        TblDzbcMultiSitePathVo pathVo = baseMapper.selectVoById(id);
        if (pathVo != null) {
            List<TblDzbcPathSiteVo> sites = pathSiteMapper.selectByPathId(id);
            List<TblDzbcSitePriceVo> prices = sitePriceMapper.selectByPathId(id);
            pathVo.setSites(sites);
            pathVo.setPrices(prices);
        }
        return pathVo;
    }

    @Override
    public Boolean insertByBo(TblDzbcMultiSitePathBo bo) {
        TblDzbcMultiSitePath add = MapstructUtils.convert(bo, TblDzbcMultiSitePath.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(TblDzbcMultiSitePathBo bo) {
        TblDzbcMultiSitePath update = MapstructUtils.convert(bo, TblDzbcMultiSitePath.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    private LambdaQueryWrapper<TblDzbcMultiSitePath> buildQueryWrapper(TblDzbcMultiSitePathBo bo) {
        LambdaQueryWrapper<TblDzbcMultiSitePath> lqw = Wrappers.lambdaQuery();
        lqw.like(org.dromara.common.core.utils.StringUtils.isNotBlank(bo.getName()), TblDzbcMultiSitePath::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, TblDzbcMultiSitePath::getStatus, bo.getStatus());
        // hasSchedul: 1-只返回有未过期排班的路线 0或不传-返回全部
        // type=2 表示多站点路线
        if (bo.getHasSchedul() != null && bo.getHasSchedul() == 1) {
            lqw.apply("id IN (SELECT DISTINCT path_id FROM tbl_dzbc_path_scheduling WHERE path_id IS NOT NULL AND mdate >= CURDATE() AND ext2->'$.type' = 2)");
        }
        lqw.orderByDesc(TblDzbcMultiSitePath::getId);
        return lqw;
    }

    private void validEntityBeforeSave(TblDzbcMultiSitePath entity) {
    }
}
