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.ArExecution;
import org.dromara.inspection.domain.bo.ArExecutionBo;
import org.dromara.inspection.domain.vo.ArExecutionVo;
import org.dromara.inspection.mapper.ArExecutionMapper;
import org.dromara.inspection.service.IArExecutionService;
import org.springframework.stereotype.Service;

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

/**
 * 任务执行记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-01-13
 */
@RequiredArgsConstructor
@Service
public class ArExecutionServiceImpl implements IArExecutionService {

    private final ArExecutionMapper baseMapper;

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

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

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

    private LambdaQueryWrapper<ArExecution> buildQueryWrapper(ArExecutionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ArExecution> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTaskId() != null, ArExecution::getTaskId, bo.getTaskId());
        lqw.eq(StringUtils.isNotBlank(bo.getExecutionCode()), ArExecution::getExecutionCode, bo.getExecutionCode());
        lqw.eq(bo.getRegionId() != null, ArExecution::getRegionId, bo.getRegionId());
        lqw.eq(bo.getDeviceId() != null, ArExecution::getDeviceId, bo.getDeviceId());
        lqw.eq(bo.getOperatorId() != null, ArExecution::getOperatorId, bo.getOperatorId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ArExecution::getStatus, bo.getStatus());
        lqw.between(params.get("beginStartTime") != null && params.get("endStartTime") != null,
            ArExecution::getStartTime, params.get("beginStartTime"), params.get("endStartTime"));
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            ArExecution::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.orderByDesc(ArExecution::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByBo(ArExecutionBo bo) {
        ArExecution add = MapstructUtils.convert(bo, ArExecution.class);
        validEntityBeforeSave(add);
        // 自动设置执行编号
        if (StringUtils.isBlank(add.getExecutionCode())) {
            add.setExecutionCode("EXE-" + System.currentTimeMillis());
        }
        // 设置初始状态
        if (StringUtils.isBlank(add.getStatus())) {
            add.setStatus("pending");
        }
        // 设置初始步骤数
        if (add.getTotalSteps() == null) {
            add.setTotalSteps(0);
        }
        if (add.getCompletedSteps() == null) {
            add.setCompletedSteps(0);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(ArExecutionBo bo) {
        ArExecution update = MapstructUtils.convert(bo, ArExecution.class);
        validEntityBeforeSave(update);
        // 如果状态变为 in_progress 且没有开始时间，自动设置
        if ("in_progress".equals(update.getStatus()) && update.getStartTime() == null) {
            update.setStartTime(new Date());
        }
        // 如果状态变为 completed 或 cancelled 且没有结束时间，自动设置
        if (("completed".equals(update.getStatus()) || "cancelled".equals(update.getStatus()))
            && update.getEndTime() == null) {
            update.setEndTime(new Date());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ArExecution entity) {
        // 校验执行编号唯一性
        if (StringUtils.isNotBlank(entity.getExecutionCode())) {
            LambdaQueryWrapper<ArExecution> lqw = Wrappers.lambdaQuery();
            lqw.eq(ArExecution::getExecutionCode, entity.getExecutionCode());
            if (entity.getId() != null) {
                lqw.ne(ArExecution::getId, entity.getId());
            }
            long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new ServiceException("执行编号已存在!");
            }
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验是否有权限删除
            List<ArExecution> list = baseMapper.selectByIds(ids);
            if (list.size() != ids.size()) {
                throw new ServiceException("您没有删除权限!");
            }
            // TODO: 检查是否有关联的步骤记录，有则提示
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
