package com.tuoheng.admin.service.cycle.delete;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionCycle;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionCycleMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DeleteInspectionCycleService {

    @Autowired
    private InspectionCycleMapper inspectionCycleMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    public JsonResult deleteByIdList(List<String> idList) {
        List<Inspection> inspectionList;
        for (String id : idList) {
            InspectionCycle inspectionCycle = inspectionCycleMapper.selectById(id);
            if (ObjectUtil.isNull(inspectionCycle)) {
                return JsonResult.error("周期任务不存在！");
            }
            inspectionCycle.setMark(MarkEnum.NOTVALID.getCode());
            int deleteById = inspectionCycleMapper.updateById(inspectionCycle);
            if (deleteById <= 0) {
                return JsonResult.error("删除周期任务失败！");
            }
            inspectionList = inspectionMapper.selectList(Wrappers.<Inspection>lambdaQuery()
                    .eq(Inspection::getTenantId, inspectionCycle.getTenantId())
                    .eq(Inspection::getInspectionCycleId, inspectionCycle.getId())
                    .eq(Inspection::getStatus, InspectionStatusEnum.WAIT_FLIGHT.getCode())
                    .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(Inspection::getCreateTime));
            if (CollectionUtil.isNotEmpty(inspectionList)) {
                for (Inspection inspection : inspectionList) {
                    inspection.setMark(MarkEnum.NOTVALID.getCode());
                    inspection.setUpdateUser(CurrentUserUtil.getUserId());
                    inspection.setUpdateTime(DateUtils.now());
                    inspectionMapper.update(inspection);
                }
            }
        }
        return JsonResult.success();
    }

}
