package com.ruoyi.sim.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.sim.domain.Fault;
import com.ruoyi.sim.domain.TaskFault;
import com.ruoyi.sim.domain.vo.FaultTreeVo;
import com.ruoyi.sim.domain.vo.TaskVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.sim.mapper.TaskMapper;
import com.ruoyi.sim.domain.Task;
import org.springframework.transaction.annotation.Transactional;

/**
 * 任务Service业务层处理
 *
 * @author tom
 * @date 2024-12-13
 */
@Service
public class TaskService {

    private static final Logger l = LoggerFactory.getLogger(TaskService.class);

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private FaultService faultService;
    @Autowired
    private TaskFaultService taskFaultService;
    @Autowired
    private SimService simService;

    /**
     * 查询任务
     *
     * @param taskId 任务主键
     * @return 任务
     */
    public AjaxResult selectTaskByTaskId(Long taskId) {
        // check
        if (taskId == null) {
            return AjaxResult.error("taskId is null");
        }
        Task t = taskMapper.selectTaskByTaskId(taskId);
        if (t == null) {
            return AjaxResult.error("task is null");
        }
        //
        TaskVo vo = new TaskVo();
        String simType = t.getSimType();
        BeanUtils.copyProperties(t, vo);
        // 查询获得数据结构。
        List<FaultTreeVo> listToQ = (List<FaultTreeVo>) faultService.listAllTreeStyleBySimType(simType).get(AjaxResult.DATA_TAG);
        // 变成扁平list
        List<FaultTreeVo> listToF = FaultService.flatten(listToQ);
        for (FaultTreeVo o : listToF) {
            if (o == null) {
                continue;
            }
            if (Fault.TYPE_3.equals(o.getFaultType())) {
                TaskFault tf = o.getTaskFault();
                TaskFault tfQ = taskFaultService.selectUniqueTaskFault(taskId, tf.getFaultId());
                // 存在就设置上数据库中TaskFault值。
                if (tfQ != null) {
                    o.setTaskFault(tfQ);
                }
            }
        }
        // 变成树list
        vo.setSelectedData(FaultService.toTree(listToF, Fault.ROOT_FAULT_ID));
        //
        return AjaxResult.success(vo);
    }

    /**
     * 查询任务列表
     *
     * @param task 任务
     * @return 任务
     */
    public List<Task> selectTaskList(Task task) {
        return taskMapper.selectTaskList(task);
    }

    /**
     * 修改任务
     *
     * @param tv 任务
     * @return 结果
     */
    public AjaxResult updateTaskByTeacher(TaskVo tv) {
        l.info("updateTaskByTeacher " + tv);
        // check
        if (tv == null) {
            return AjaxResult.error("TaskVo empty!");
        }
        if (!simService.checkSimTypeOk(tv.getSimType())) {
            return AjaxResult.error("simType error!");
        }
        if (!Task.Type.TEACHER_ADD.equals(tv.getTaskType())) {
            return AjaxResult.error("taskType value error!");
        }
        if (StringUtils.isEmpty(tv.getName())) {
            return AjaxResult.error("name isEmpty!");
        }
        //
        tv.setCreateByUserId(SecurityUtils.getUserId());
        tv.setCreateBy(SecurityUtils.getUsername());
        tv.setCreateTime(DateUtils.getNowDate());
        tv.setUpdateBy(SecurityUtils.getUsername());
        tv.setUpdateTime(DateUtils.getNowDate());
        tv.setRemark("");
        tv.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateTask(tv);
        List<FaultTreeVo> selectedData = tv.getSelectedData();
        if (selectedData != null) {
            List<FaultTreeVo> list = FaultService.flatten(selectedData);
            for (FaultTreeVo ftv : list) {
                if (ftv == null) {
                    continue;
                }
                if (!Fault.TYPE_3.equals(ftv.getFaultType())) {
                    continue;
                }
                TaskFault tf = ftv.getTaskFault();
                // check
                if (tf == null) {
                    return AjaxResult.error("TaskFault empty!");
                }
                String flag = tf.getFlag();
                if (StringUtils.isEmpty(flag)) {
                    return AjaxResult.error("flag empty!");
                }
                if (TaskFault.UNKNOWN.equals(flag)) {
                    return AjaxResult.error("flag UNKNOWN!");
                }
                if (!TaskFault.YES.equals(flag) && !TaskFault.NO.equals(flag)) {
                    return AjaxResult.error("flag must YES or NO!");
                }
                // todo:选中数量限制

                // todo:故障部位冲突
                tf.setTaskId(tv.getTaskId());
                taskFaultService.insertOrUpdateTaskFault(tf);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除任务
     *
     * @param ids 需要删除的任务主键
     * @return 结果
     */
    @Transactional
    public AjaxResult deleteTaskByTaskIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("taskIds null!");
        }
        for (Long tId : ids) {
            taskMapper.deleteTaskByTaskId(tId);
            taskFaultService.deleteTaskFaultByTaskId(tId);
        }
        return AjaxResult.success();
    }

    /**
     * 删除任务信息
     *
     * @param taskId 任务主键
     * @return 结果
     */
    public int deleteTaskByTaskId(Long taskId) {
        return taskMapper.deleteTaskByTaskId(taskId);
    }


    /**
     * 新增任务
     *
     * @param tv 任务
     * @return 结果
     * todo:事务有问题。
     */
    @Transactional
    public AjaxResult insertTaskByTeacher(TaskVo tv) {
        l.info("insertTaskByTeacher " + tv);
        // check
        if (tv == null) {
            return AjaxResult.error("TaskVo empty!");
        }
        if (!simService.checkSimTypeOk(tv.getSimType())) {
            return AjaxResult.error("simType error!");
        }
        if (!Task.Type.TEACHER_ADD.equals(tv.getTaskType())) {
            return AjaxResult.error("taskType value error!");
        }
        if (StringUtils.isEmpty(tv.getName())) {
            return AjaxResult.error("name isEmpty!");
        }
        //
        tv.setCreateByUserId(SecurityUtils.getUserId());
        tv.setCreateBy(SecurityUtils.getUsername());
        tv.setCreateTime(DateUtils.getNowDate());
        tv.setUpdateBy(SecurityUtils.getUsername());
        tv.setUpdateTime(DateUtils.getNowDate());
        tv.setRemark("");
        taskMapper.insertTask(tv);
        List<FaultTreeVo> selectedData = tv.getSelectedData();
        if (selectedData != null) {
            List<FaultTreeVo> list = FaultService.flatten(selectedData);
            for (FaultTreeVo ftv : list) {
                if (ftv == null) {
                    continue;
                }
                if (!Fault.TYPE_3.equals(ftv.getFaultType())) {
                    continue;
                }
                TaskFault tf = ftv.getTaskFault();
                // check
                if (tf == null) {
                    return AjaxResult.error("TaskFault empty!");
                }
                String flag = tf.getFlag();
                if (StringUtils.isEmpty(flag)) {
                    return AjaxResult.error("flag empty!");
                }
                if (TaskFault.UNKNOWN.equals(flag)) {
                    return AjaxResult.error("flag UNKNOWN!");
                }
                if (!TaskFault.YES.equals(flag) && !TaskFault.NO.equals(flag)) {
                    return AjaxResult.error("flag must YES or NO!");
                }
                // todo:选中数量限制

                // todo:故障部位冲突
                tf.setTaskId(tv.getTaskId());
                taskFaultService.insertOrUpdateTaskFault(tf);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 为了新建Task，返回一个带tree结构的任务详细信息。
     *
     * @return 任务
     */
    public AjaxResult getInfoForAdd(final String simType) {
        // check
        if (StringUtils.isEmpty(simType)) {
            return AjaxResult.error("simType empty!");
        }
        if (!simService.checkSimTypeOk(simType)) {
            return AjaxResult.error("simType value error!");
        }
        // query obj.
        List<FaultTreeVo> ftList = (List<FaultTreeVo>) faultService.listAllTreeStyleBySimType(simType).get(AjaxResult.DATA_TAG);
        TaskVo t = new TaskVo();
        t.setTaskId(Task.EMPTY_TASK_ID);
        t.setSelectedData(ftList);
        return AjaxResult.success(t);
    }

    /**
     * 新增任务附带选择故障
     *
     * @param task 任务
     * @return 结果
     */
    @Transactional
    public int insertTaskWithFault(Task task) {
        Long taskId = task.getTaskId();
        if (selectTaskByTaskId(taskId) != null) {
            // 已经存在
        }
        task.setCreateTime(DateUtils.getNowDate());
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.insertTask(task);
    }
}
