package com.zksy.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.CaseInfo;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.WorkOrder;
import com.zksy.base.domain.WorkOrderLog;
import com.zksy.base.mapper.CaseInfoMapper;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.WorkOrderLogMapper;
import com.zksy.base.mapper.WorkOrderMapper;
import com.zksy.base.service.WorkOrderService;
import com.zksy.common.core.domain.entity.SysUser;
import com.zksy.common.core.domain.model.LoginUser;
import com.zksy.common.exception.ServiceException;
import com.zksy.common.utils.SecurityUtils;
import com.zksy.manhole.dto.in.*;
import com.zksy.manhole.dto.out.WorkOrderOutDTO;
import com.zksy.system.service.ISysUserService;
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
* @author Administrator
* @description 针对表【work_order(运维工单表)】的数据库操作Service实现
* @createDate 2026-06-11 11:50:08
*/
@Slf4j
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder>
    implements WorkOrderService{

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private WorkOrderLogMapper workOrderLogMapper;

    @Autowired
    private CaseInfoMapper caseInfoMapper;

    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;

    /**
     * 分页查询工单信息列表
     * @param pageInDTO
     * @return
     */
    @Override
    public Page<WorkOrderOutDTO> findByPage(WorkOrderPageInDTO pageInDTO) {
        log.info("分页查询工单信息列表-入参:{}", pageInDTO);
        Page<WorkOrder> page = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize());
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(pageInDTO.getOrderNo()), WorkOrder::getOrderNo, pageInDTO.getOrderNo())
                .like(StringUtils.isNotEmpty(pageInDTO.getCaseNo()), WorkOrder::getCaseNo, pageInDTO.getCaseNo())
                .orderByDesc(WorkOrder::getUpdateTime);
        Page<WorkOrder> rs = this.page(page, queryWrapper);
        List<WorkOrderOutDTO> outDTOList = BeanUtil.copyToList(rs.getRecords(), WorkOrderOutDTO.class);
        Page<WorkOrderOutDTO> outPage = new Page<>(pageInDTO.getPageNum(), pageInDTO.getPageSize(), rs.getTotal());
        outPage.setRecords(outDTOList);
        return outPage;
    }

    /**
     * 新增工单
     * @param inDTO
     * @return
     */
    @Override
    public boolean addWorkOrder(WorkOrderAddInDTO inDTO) {
        log.info("新增工单-入参:{}", inDTO);
        WorkOrder workOrder = BeanUtil.copyProperties(inDTO, WorkOrder.class);
        workOrder.setOrderNo(generateOrderNo());
        // 初始状态：1-待派单
        workOrder.setOrderStatus(1);
        if(inDTO.getCaseId() != null){
            CaseInfo caseInfo = caseInfoMapper.selectById(inDTO.getCaseId());
            if(caseInfo != null){
                workOrder.setCaseNo(caseInfo.getCaseNo());
            }
        }
        if(inDTO.getDeviceId() != null){
            EquipmentBase equipmentBase = equipmentBaseMapper.selectById(inDTO.getDeviceId());
            if(equipmentBase != null){
                workOrder.setDeviceCode(equipmentBase.getEquipmentCode());
            }
        }
        this.save(workOrder);
        WorkOrderLog workOrderLog = new WorkOrderLog();
        workOrderLog.setOrderId(workOrder.getOrderId());
        //1-创建工单
        workOrderLog.setOperType(1);
        workOrderLog.setOperDesc(inDTO.getOrderDesc() + ",创建工单");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            workOrderLog.setOperUserId(loginUser.getUserId());
            workOrderLog.setOperUserName(loginUser.getUser().getNickName());
        }
        return workOrderLogMapper.insert(workOrderLog) > 0;
    }

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

    /**
     * 经办工单分页查询（处理中：待接单、已接单、处理中、待验收）
     * @param inDTO
     * @return
     */
    @Override
    public Page<WorkOrderOutDTO> findProcessingPage(WorkOrderProcessingInDTO inDTO) {
        log.info("经办工单分页查询-入参:{}", inDTO);
        Page<WorkOrder> page = new Page<>(inDTO.getPageNum(), inDTO.getPageSize());
        // 经办工单状态：2-待接单 3-已接单 4-处理中 5-待验收 8-延期审核
        List<Integer> processingStatusList = Arrays.asList(2, 3, 4, 5, 8);
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WorkOrder::getOrderStatus, processingStatusList)
                .like(StringUtils.isNotEmpty(inDTO.getOrderNo()), WorkOrder::getOrderNo, inDTO.getOrderNo())
                .like(StringUtils.isNotEmpty(inDTO.getCaseNo()), WorkOrder::getCaseNo, inDTO.getCaseNo())
                .eq(inDTO.getOrderType() != null, WorkOrder::getOrderType, inDTO.getOrderType())
                .eq(inDTO.getOrderLevel() != null, WorkOrder::getOrderLevel, inDTO.getOrderLevel())
                .eq(inDTO.getReceiveUser() != null, WorkOrder::getReceiveUser, inDTO.getReceiveUser())
                .orderByDesc(WorkOrder::getUpdateTime);
        Page<WorkOrder> rs = this.page(page, queryWrapper);
        List<WorkOrderOutDTO> outDTOList = BeanUtil.copyToList(rs.getRecords(), WorkOrderOutDTO.class);
        Page<WorkOrderOutDTO> outPage = new Page<>(inDTO.getPageNum(), inDTO.getPageSize(), rs.getTotal());
        outPage.setRecords(outDTOList);
        return outPage;
    }

    /**
     * 办结工单分页查询（已办结：已结案、已驳回）
     * @param inDTO
     * @return
     */
    @Override
    public Page<WorkOrderOutDTO> findFinishedPage(WorkOrderFinishedInDTO inDTO) {
        log.info("办结工单分页查询-入参:{}", inDTO);
        Page<WorkOrder> page = new Page<>(inDTO.getPageNum(), inDTO.getPageSize());
        // 办结工单状态：6-已结案 7-已驳回 9-已延期
        List<Integer> finishedStatusList = Arrays.asList(6, 7, 9);
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WorkOrder::getOrderStatus, finishedStatusList)
                .like(StringUtils.isNotEmpty(inDTO.getOrderNo()), WorkOrder::getOrderNo, inDTO.getOrderNo())
                .like(StringUtils.isNotEmpty(inDTO.getCaseNo()), WorkOrder::getCaseNo, inDTO.getCaseNo())
                .eq(inDTO.getOrderType() != null, WorkOrder::getOrderType, inDTO.getOrderType())
                .eq(inDTO.getOrderLevel() != null, WorkOrder::getOrderLevel, inDTO.getOrderLevel())
                .eq(inDTO.getVerifyUser() != null, WorkOrder::getVerifyUser, inDTO.getVerifyUser())
                .ge(inDTO.getStartTime() != null, WorkOrder::getRealFinishTime, inDTO.getStartTime())
                .le(inDTO.getEndTime() != null, WorkOrder::getRealFinishTime, inDTO.getEndTime())
                .orderByDesc(WorkOrder::getUpdateTime);
        Page<WorkOrder> rs = this.page(page, queryWrapper);
        List<WorkOrderOutDTO> outDTOList = BeanUtil.copyToList(rs.getRecords(), WorkOrderOutDTO.class);
        Page<WorkOrderOutDTO> outPage = new Page<>(inDTO.getPageNum(), inDTO.getPageSize(), rs.getTotal());
        outPage.setRecords(outDTOList);
        return outPage;
    }

    /**
     * 操作工单
     * @param inDTO
     * @return
     */
    @Override
    public boolean operWorkOrder(WorkOrderOperInDTO inDTO) {
        log.info("操作工单-入参:{}", inDTO);
        WorkOrder workOrder = this.getById(inDTO.getOrderId());
        if(workOrder == null){
            throw new ServiceException("工单ID不存在");
        }
        SysUser user = sysUserService.selectUserById(inDTO.getOperUserId());
        if(user == null){
            throw new ServiceException("操作人ID不存在");
        }
        if(inDTO.getOperType() == null){
            throw new ServiceException("操作类型不能为空");
        }
        WorkOrder entity = new WorkOrder();
        entity.setOrderId(inDTO.getOrderId());
        if(inDTO.getOperType() == 2){
            //2-派单
            entity.setOrderStatus(2);
            entity.setDispatchUser(inDTO.getOperUserId());
            entity.setDispatchTime(new Date());
            entity.setReceiveUser(inDTO.getReceiveUser().toString());
        } else if(inDTO.getOperType() == 3){
            //3-接单
            entity.setOrderStatus(3);
            entity.setReceiveUser(inDTO.getOperUserId().toString());
        } else if(inDTO.getOperType() == 4){
            //4-开始维修
            entity.setOrderStatus(4);
        } else if(inDTO.getOperType() == 5){
            //5-提交验收
            entity.setOrderStatus(5);
            entity.setVerifyUser(workOrder.getDispatchUser());
        } else if(inDTO.getOperType() == 6){
            //6-验收通过
            entity.setOrderStatus(6);
            entity.setVerifyUser(inDTO.getOperUserId());
            entity.setVerifyTime(new Date());
            // 同步将案件状态改为已办结
            if(workOrder.getCaseId() != null){
                CaseInfo caseInfo = caseInfoMapper.selectById(workOrder.getCaseId());
                if(caseInfo != null){
                    CaseInfo caseEntity = new CaseInfo();
                    caseEntity.setCaseId(caseInfo.getCaseId());
                    caseEntity.setCaseStatus(3);
                    caseEntity.setFinishTime(new Date());
                    caseInfoMapper.updateById(caseEntity);
                }
            }
        } else if(inDTO.getOperType() == 7){
            //7-驳回工单
            entity.setOrderStatus(7);
        } else if(inDTO.getOperType() == 8){
            //8-申请延期
            entity.setOrderStatus(8);
            entity.setDelayedReason(inDTO.getDelayedReason());
            entity.setDelayedDeadline(inDTO.getDelayedDeadline());
        } else if(inDTO.getOperType() == 9){
            //9-延期审核通过
            entity.setOrderStatus(9);
        }
        WorkOrderLog workOrderLog = BeanUtil.copyProperties(inDTO, WorkOrderLog.class);
        workOrderLog.setOperUserName(user.getNickName());
        workOrderLogMapper.insert(workOrderLog);
        return this.updateById(entity);
    }
}




