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.ArStepRecord;
import org.dromara.inspection.domain.bo.ArStepRecordBo;
import org.dromara.inspection.domain.vo.ArStepRecordVo;
import org.dromara.inspection.mapper.ArStepRecordMapper;
import org.dromara.inspection.service.IArStepRecordService;
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 ArStepRecordServiceImpl implements IArStepRecordService {

    private final ArStepRecordMapper baseMapper;

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

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

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

    private LambdaQueryWrapper<ArStepRecord> buildQueryWrapper(ArStepRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ArStepRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getExecutionId() != null, ArStepRecord::getExecutionId, bo.getExecutionId());
        lqw.eq(bo.getStepId() != null, ArStepRecord::getStepId, bo.getStepId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ArStepRecord::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDone()), ArStepRecord::getIsDone, bo.getIsDone());
        lqw.eq(bo.getExecutorId() != null, ArStepRecord::getExecutorId, bo.getExecutorId());
        lqw.between(params.get("beginStartTime") != null && params.get("endStartTime") != null,
            ArStepRecord::getStartTime, params.get("beginStartTime"), params.get("endStartTime"));
        lqw.between(params.get("beginCompletionTime") != null && params.get("endCompletionTime") != null,
            ArStepRecord::getCompletionTime, params.get("beginCompletionTime"), params.get("endCompletionTime"));
        lqw.orderByDesc(ArStepRecord::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByBo(ArStepRecordBo bo) {
        ArStepRecord add = MapstructUtils.convert(bo, ArStepRecord.class);
        validEntityBeforeSave(add);
        // 设置初始状态
        if (StringUtils.isBlank(add.getStatus())) {
            add.setStatus("pending");
        }
        if (StringUtils.isBlank(add.getIsDone())) {
            add.setIsDone("0");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(ArStepRecordBo bo) {
        ArStepRecord update = MapstructUtils.convert(bo, ArStepRecord.class);
        validEntityBeforeSave(update);
        // 如果状态变为 completed 且没有完成时间，自动设置
        if ("completed".equals(update.getStatus()) && update.getCompletionTime() == null) {
            update.setCompletionTime(new Date());
            update.setIsDone("1");
            // 计算耗时
            if (update.getStartTime() != null) {
                long duration = (update.getCompletionTime().getTime() - update.getStartTime().getTime()) / 1000;
                update.setDuration((int) duration);
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ArStepRecord entity) {
        // TODO: 业务校验
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验是否有权限删除
            List<ArStepRecord> list = baseMapper.selectByIds(ids);
            if (list.size() != ids.size()) {
                throw new ServiceException("您没有删除权限!");
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
