package com.zksy.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.domain.MaintenanceTask;
import com.zksy.base.domain.MaintenanceTaskDetail;
import com.zksy.base.mapper.MaintenanceTaskMapper;
import com.zksy.base.service.MaintenanceTaskDetailService;
import com.zksy.base.service.MaintenanceTaskService;
import com.zksy.common.exception.ServiceException;
import com.zksy.manhole.dto.in.MaintenanceTaskDispatchInDTO;
import com.zksy.manhole.dto.in.MaintenanceTaskPageInDTO;
import com.zksy.manhole.dto.in.MaintenanceTaskProcessInDTO;
import com.zksy.manhole.dto.out.MaintenanceTaskDetailOutDTO;
import com.zksy.manhole.dto.out.MaintenanceTaskOutDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
* @author Administrator
* @description 针对表【maintenance_task(运维任务主表)】的数据库操作Service实现
* @createDate 2026-06-26 14:11:51
*/
@Slf4j
@Service
public class MaintenanceTaskServiceImpl extends ServiceImpl<MaintenanceTaskMapper, MaintenanceTask>
    implements MaintenanceTaskService{

    @Autowired
    private MaintenanceTaskDetailService maintenanceTaskDetailService;

    /**
     * 分页查询运维任务列表
     * @param pageInDTO
     * @return
     */
    @Override
    public Page<MaintenanceTaskOutDTO> findByPage(MaintenanceTaskPageInDTO pageInDTO) {
        log.info("分页查询运维任务列表-入参:{}", pageInDTO);
        Page<MaintenanceTask> page = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize());
        LambdaQueryWrapper<MaintenanceTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(pageInDTO.getTaskNo()), MaintenanceTask::getTaskNo, pageInDTO.getTaskNo())
                .eq(pageInDTO.getDeptId() != null, MaintenanceTask::getDeptId, pageInDTO.getDeptId())
                .eq(pageInDTO.getReceiveUserId() != null, MaintenanceTask::getReceiveUserId, pageInDTO.getReceiveUserId())
                .eq(pageInDTO.getTaskLevel() != null, MaintenanceTask::getTaskLevel, pageInDTO.getTaskLevel())
                .eq(pageInDTO.getTaskStatus() != null, MaintenanceTask::getTaskStatus, pageInDTO.getTaskStatus())
                .orderByDesc(MaintenanceTask::getUpdateTime);
        Page<MaintenanceTask> rs = this.page(page, queryWrapper);
        List<MaintenanceTaskOutDTO> outDTOList = BeanUtil.copyToList(rs.getRecords(), MaintenanceTaskOutDTO.class);
        Page<MaintenanceTaskOutDTO> outPage = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize(), rs.getTotal());
        outPage.setRecords(outDTOList);
        return outPage;
    }

    /**
     * 获取运维任务详情
     * @param taskId
     * @return
     */
    @Override
    public MaintenanceTaskOutDTO getDetailById(Long taskId) {
        log.info("获取运维任务详情-入参:{}", taskId);
        MaintenanceTask maintenanceTask = this.getById(taskId);
        if(maintenanceTask == null){
            return null;
        }
        MaintenanceTaskOutDTO outDTO = BeanUtil.copyProperties(maintenanceTask, MaintenanceTaskOutDTO.class);
        // 查询运维任务明细列表
        List<MaintenanceTaskDetail> detailList = maintenanceTaskDetailService.list(new LambdaQueryWrapper<MaintenanceTaskDetail>()
                .eq(MaintenanceTaskDetail::getTaskId, taskId)
                .orderByAsc(MaintenanceTaskDetail::getCreateTime));
        if(CollUtil.isNotEmpty(detailList)){
            List<MaintenanceTaskDetailOutDTO> detailOutDTOList = BeanUtil.copyToList(detailList, MaintenanceTaskDetailOutDTO.class);
            outDTO.setDetailList(detailOutDTOList);
        }
        return outDTO;
    }

    /**
     * 批量下发运维任务（新增运维任务主表 + 明细表）
     * @param inDTO
     * @return
     */
    @Override
    public boolean batchDispatch(MaintenanceTaskDispatchInDTO inDTO) {
        log.info("批量下发运维任务-入参:{}", inDTO);
        if(inDTO.getDispatchUserId() == null){
            throw new ServiceException("派单人ID不能为空");
        }
        if(inDTO.getReceiveUserId() == null){
            throw new ServiceException("接收维护人员ID不能为空");
        }
        List<MaintenanceTaskDispatchInDTO.DispatchDetailInDTO> detailList = inDTO.getDetailList();
        if(CollUtil.isEmpty(detailList)){
            throw new ServiceException("设备报警明细列表不能为空");
        }
        // 新增运维任务主表
        MaintenanceTask task = BeanUtil.copyProperties(inDTO, MaintenanceTask.class);
        task.setTaskNo(generateTaskNo());
        // 初始状态：2-待接收
        task.setTaskStatus(2);
        this.save(task);
        // 批量新增运维任务明细表
        List<MaintenanceTaskDetail> taskDetailList = new ArrayList<>();
        for(MaintenanceTaskDispatchInDTO.DispatchDetailInDTO detailInDTO : detailList){
            MaintenanceTaskDetail detail = BeanUtil.copyProperties(detailInDTO, MaintenanceTaskDetail.class);
            detail.setTaskId(task.getTaskId());
            // 明细初始状态：1-待处理
            detail.setDetailStatus(1);
            taskDetailList.add(detail);
        }
        return maintenanceTaskDetailService.saveBatch(taskDetailList);
    }

    /**
     * 生成运维任务编号
     * @return
     */
    public static String generateTaskNo() {
        // 1. 获取当前时间，格式为14位年月日时分秒
        String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 2. 生成4位随机数，不足补0
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        // 3. 拼接完整编号：TS+年月日时分秒+随机数
        return "TS" + currentDateTime + randomNum;
    }

    /**
     * 处理运维任务
     * @param inDTO
     * @return
     */
    @Override
    public boolean processTask(MaintenanceTaskProcessInDTO inDTO) {
        log.info("处理运维任务-入参:{}", inDTO);
        MaintenanceTask task = this.getById(inDTO.getTaskId());
        if(task == null){
            throw new ServiceException("运维任务ID不存在");
        }
        if(inDTO.getProcessType() == null){
            throw new ServiceException("处理类型不能为空");
        }
        MaintenanceTask entity = new MaintenanceTask();
        entity.setTaskId(inDTO.getTaskId());
        if(inDTO.getProcessType() == 1){
            // 1-接收任务：待接收 -> 处理中
            entity.setTaskStatus(3);
            entity.setRealStartTime(new Date());
        } else if(inDTO.getProcessType() == 2){
            // 2-提交验收：处理中 -> 待验收
            entity.setTaskStatus(4);
        } else if(inDTO.getProcessType() == 3){
            // 3-验收通过：待验收 -> 已完成
            entity.setTaskStatus(5);
            entity.setRealEndTime(new Date());
        } else if(inDTO.getProcessType() == 4){
            // 4-驳回：待验收 -> 已驳回
            entity.setTaskStatus(6);
        } else {
            throw new ServiceException("处理类型不合法");
        }
        return this.updateById(entity);
    }
}




