package org.dromara.inspection.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.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.inspection.domain.ArStep;
import org.dromara.inspection.domain.bo.ArStepBo;
import org.dromara.inspection.domain.vo.ArStepTreeVo;
import org.dromara.inspection.domain.vo.ArStepVo;
import org.dromara.inspection.mapper.ArStepMapper;
import org.dromara.inspection.service.IArStepService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 巡检步骤Service业务层处理
 *
 * @author Lion Li
 * @date 2025-01-13
 */
@RequiredArgsConstructor
@Service
public class ArStepServiceImpl implements IArStepService {

    private final ArStepMapper baseMapper;

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

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

    @Override
    public List<ArStepVo> queryList(ArStepBo bo) {
        return baseMapper.selectVoList(buildQueryWrapper(bo));
    }

    /**
     * 查询任务的步骤树
     *
     * @param taskId 任务ID
     * @return 步骤树列表
     */
    @Override
    public List<ArStepTreeVo> queryStepTree(Long taskId) {
        // 查询所有步骤
        LambdaQueryWrapper<ArStep> lqw = Wrappers.lambdaQuery();
        lqw.eq(ArStep::getTaskId, taskId);
        lqw.orderByAsc(ArStep::getOrderNum);
        List<ArStepVo> allSteps = baseMapper.selectVoList(lqw);

        // 构建树形结构
        return buildStepTree(allSteps, 0L);
    }

    /**
     * 递归构建步骤树
     *
     * @param allSteps 所有步骤列表
     * @param parentId 父步骤ID
     * @return 树形步骤列表
     */
    private List<ArStepTreeVo> buildStepTree(List<ArStepVo> allSteps, Long parentId) {
        List<ArStepTreeVo> tree = new ArrayList<>();
        for (ArStepVo step : allSteps) {
            if (step.getParentId().equals(parentId)) {
                ArStepTreeVo treeNode = new ArStepTreeVo();
                BeanUtils.copyProperties(step, treeNode);
                // 递归查找子节点
                List<ArStepTreeVo> children = buildStepTree(allSteps, step.getId());
                treeNode.setChildren(children);
                tree.add(treeNode);
            }
        }
        return tree;
    }

    private LambdaQueryWrapper<ArStep> buildQueryWrapper(ArStepBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ArStep> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTaskId() != null, ArStep::getTaskId, bo.getTaskId());
        lqw.eq(bo.getParentId() != null, ArStep::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getStepName()), ArStep::getStepName, bo.getStepName());
        lqw.eq(bo.getPointId() != null, ArStep::getPointId, bo.getPointId());
        lqw.eq(StringUtils.isNotBlank(bo.getIsOperation()), ArStep::getIsOperation, bo.getIsOperation());
        lqw.eq(StringUtils.isNotBlank(bo.getIsLeaf()), ArStep::getIsLeaf, bo.getIsLeaf());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            ArStep::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.orderByAsc(ArStep::getOrderNum);
        return lqw;
    }

    @Override
    public Boolean insertByBo(ArStepBo bo) {
        ArStep add = MapstructUtils.convert(bo, ArStep.class);
        validEntityBeforeSave(add);
        // 自动设置 ancestors
        if (add.getParentId() != null && add.getParentId() != 0) {
            ArStep parent = baseMapper.selectById(add.getParentId());
            if (parent != null) {
                add.setAncestors(parent.getAncestors() + "," + add.getParentId());
            } else {
                add.setAncestors(String.valueOf(add.getParentId()));
            }
        } else {
            add.setAncestors("0");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(ArStepBo bo) {
        ArStep update = MapstructUtils.convert(bo, ArStep.class);
        validEntityBeforeSave(update);
        // 更新 ancestors（如果父节点变更）
        ArStep old = baseMapper.selectById(update.getId());
        if (old != null && !old.getParentId().equals(update.getParentId())) {
            if (update.getParentId() != null && update.getParentId() != 0) {
                ArStep parent = baseMapper.selectById(update.getParentId());
                if (parent != null) {
                    update.setAncestors(parent.getAncestors() + "," + update.getParentId());
                } else {
                    update.setAncestors(String.valueOf(update.getParentId()));
                }
            } else {
                update.setAncestors("0");
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ArStep entity) {
        // 校验父节点是否存在
        if (entity.getParentId() != null && entity.getParentId() != 0) {
            ArStep parent = baseMapper.selectById(entity.getParentId());
            if (parent == null) {
                throw new ServiceException("父步骤不存在!");
            }
            // 校验父节点是否属于同一任务
            if (!parent.getTaskId().equals(entity.getTaskId())) {
                throw new ServiceException("父步骤必须属于同一任务!");
            }
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验是否有权限删除
            List<ArStep> list = baseMapper.selectByIds(ids);
            if (list.size() != ids.size()) {
                throw new ServiceException("您没有删除权限!");
            }
            // 校验是否有子步骤，有则级联删除
            for (Long id : ids) {
                LambdaQueryWrapper<ArStep> lqw = Wrappers.lambdaQuery();
                lqw.eq(ArStep::getParentId, id);
                long count = baseMapper.selectCount(lqw);
                if (count > 0) {
                    // 级联删除子步骤
                    List<ArStep> children = baseMapper.selectList(lqw);
                    List<Long> childrenIds = children.stream().map(ArStep::getId).toList();
                    deleteWithValidByIds(childrenIds, false);
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
