package com.yuchen.saas.park.service.service.work.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.integration.feign.api.util.PageConverterUtils;
import com.yuchen.saas.manage.dict.api.feign.IDictClient;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.dto.work.*;
import com.yuchen.saas.park.api.entity.repair.SaasMatterRepair;
import com.yuchen.saas.park.api.entity.repair.SaasMatterRepairHandleRecord;
import com.yuchen.saas.park.api.entity.work.SaasWorkOrder;
import com.yuchen.saas.park.api.entity.work.SaasWorkOrderAlarmOperation;
import com.yuchen.saas.park.api.entity.work.SaasWorkOrderDeviceRepair;
import com.yuchen.saas.park.api.entity.work.SaasWorkOrderMatterRepair;
import com.yuchen.saas.park.api.enums.repair.RepairStatusEnum;
import com.yuchen.saas.park.api.enums.work.*;
import com.yuchen.saas.park.api.vo.work.*;
import com.yuchen.saas.park.service.mapper.work.SaasWorkOrderMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.repair.ISaasMatterRepairHandleRecordService;
import com.yuchen.saas.park.service.service.repair.ISaasMatterRepairService;
import com.yuchen.saas.park.service.service.repair.ISaasMatterRepairTypeService;
import com.yuchen.saas.park.service.service.work.*;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单主表 服务实现类
 * </p>
 *
 * @author caiwq
 * @since 2024-04-09
 */
@Service
public class SaasWorkOrderServiceImpl extends BaseServiceImpl<SaasWorkOrderMapper, SaasWorkOrder> implements ISaasWorkOrderService {

    @Resource
    private ISaasWorkOrderMatterRepairService workOrderMatterRepairService;
    @Resource
    private ISaasWorkOrderDeviceRepairService workOrderDeviceRepairService;
    @Resource
    private ISaasWorkOrderAlarmOperationService workOrderAlarmOperationService;
    @Resource
    private ISaasWorkOrderTypeService workOrderTypeService;
    @Resource
    private ISaasWorkOrderTimeLimitService workOrderTimeLimitService;
    @Resource
    private ISaasMatterRepairHandleRecordService matterRepairHandleRecordService;
    @Resource
    private ISaasMatterRepairTypeService repairTypeService;
    @Resource
    private ISaasMatterRepairService matterRepairService;
    @Resource
    private IOrgUserClient iOrgUserClient;
    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;
    @Resource
    private IDictClient iDictClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SaasWorkOrder add(SaasWorkOrderDto workOrderDto) {
        SaasWorkOrder workOrder = null;
        if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderMatterRepairDto(), SaasWorkOrder.class);
            //工单单号
            String workOrderNo = "BSBX" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int) ((Math.random() * 9 + 1) * 1000);
            workOrder.setWorkOrderNo(workOrderNo);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderDeviceRepairDto(), SaasWorkOrder.class);
            //工单单号
            String workOrderNo = "SBBX" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int) ((Math.random() * 9 + 1) * 1000);
            workOrder.setWorkOrderNo(workOrderNo);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.ALARM_OPERATION.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderAlarmOperationDto(), SaasWorkOrder.class);
            //工单单号
            String workOrderNo = "GJYW" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int) ((Math.random() * 9 + 1) * 1000);
            workOrder.setWorkOrderNo(workOrderNo);
        }
        //客户ID
        Long customerId = AuthUtil.getUser().getCustomerManageId();
        workOrder.setCustomerId(customerId);
        //录单人
        Long recordUserId = AuthUtil.getUser().getOrgUserId();
        String recordUserName = iOrgUserClient.detail(recordUserId).getData().getName();
        workOrder.setRecordUserId(recordUserId);
        workOrder.setRecordUserName(recordUserName);
        //录单时间
        workOrder.setRecordTime(new Date());
        //派工单号
        String dispatchNo = "PG" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + (int) ((Math.random() * 9 + 1) * 10);
        workOrder.setDispatchNo(dispatchNo);
        //指派人
        String dispatchUserIds = workOrder.getDispatchUserIds();
        List<Long> dispatchUserIdList = Arrays.stream(dispatchUserIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<NestOrgUser> feignResult = iOrgUserClient.findOrgUserListByIds(dispatchUserIdList).getData();
        List<String> orgUserNameList = feignResult.stream().map(NestOrgUser::getName).collect(Collectors.toList());
        workOrder.setDispatchUserNames(CollUtil.join(orgUserNameList, ","));
        workOrder.setWorkOrderStatus(WorkOrderStatusEnum.TO_BEGIN.getValue());
        workOrder.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        save(workOrder);
        if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            SaasWorkOrderMatterRepair matterRepair = BeanUtil.copyProperties(workOrderDto.getWorkOrderMatterRepairDto(), SaasWorkOrderMatterRepair.class);
            matterRepair.setWorkOrderId(workOrder.getId());
            workOrderMatterRepairService.save(matterRepair);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            SaasWorkOrderDeviceRepair deviceRepair = BeanUtil.copyProperties(workOrderDto.getWorkOrderDeviceRepairDto(), SaasWorkOrderDeviceRepair.class);
            deviceRepair.setWorkOrderId(workOrder.getId());
            List<SaasWorkOrderDeviceRepairDto.DeviceDetail> deviceDetailList = workOrderDto.getWorkOrderDeviceRepairDto().getDeviceDetailList();
            if (Func.isNotEmpty(deviceDetailList)) {
                deviceRepair.setDeviceCount(deviceDetailList.size());
                deviceRepair.setDeviceDetail(JSON.toJSONString(deviceDetailList));
            }
            workOrderDeviceRepairService.save(deviceRepair);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.ALARM_OPERATION.getValue()) {
            SaasWorkOrderAlarmOperation alarmOperation = BeanUtil.copyProperties(workOrderDto.getWorkOrderAlarmOperationDto(), SaasWorkOrderAlarmOperation.class);
            alarmOperation.setWorkOrderId(workOrder.getId());
            workOrderAlarmOperationService.save(alarmOperation);
        }
        return workOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean assign(SaasWorkOrderDto workOrderDto) {
        SaasWorkOrder workOrder = null;
        if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderMatterRepairDto(), SaasWorkOrder.class);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderDeviceRepairDto(), SaasWorkOrder.class);
        } else if (workOrderDto.getWorkOrderCategory() == WorkOrderCategoryEnum.ALARM_OPERATION.getValue()) {
            workOrder = BeanUtil.copyProperties(workOrderDto.getWorkOrderAlarmOperationDto(), SaasWorkOrder.class);
        }
        //指派人
        String dispatchUserIds = workOrder.getDispatchUserIds();
        List<Long> dispatchUserIdList = Arrays.stream(dispatchUserIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<NestOrgUser> feignResult = iOrgUserClient.findOrgUserListByIds(dispatchUserIdList).getData();
        List<String> orgUserNameList = feignResult.stream().map(NestOrgUser::getName).collect(Collectors.toList());
        workOrder.setDispatchUserNames(CollUtil.join(orgUserNameList, ","));
        return updateById(workOrder);
    }

    @Override
    public Boolean assignV2(SaasWorkOrderAssignDto workOrderAssignDto) {
        SaasWorkOrder workOrder = getById(workOrderAssignDto.getId());
        workOrder.setDispatchTime(new Date());
        workOrder.setDispatchRemark(workOrderAssignDto.getDispatchRemark());
        //指派人
        String dispatchUserIds = workOrderAssignDto.getDispatchUserIds();
        List<Long> dispatchUserIdList = Arrays.stream(dispatchUserIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<NestOrgUser> feignResult = iOrgUserClient.findOrgUserListByIds(dispatchUserIdList).getData();
        List<String> orgUserNameList = feignResult.stream().map(NestOrgUser::getName).collect(Collectors.toList());
        workOrder.setDispatchUserIds(dispatchUserIds);
        workOrder.setDispatchUserNames(CollUtil.join(orgUserNameList, ","));
        return updateById(workOrder);
    }

    @Override
    public Boolean startHandle(Long id) {
        SaasWorkOrder workOrder = getById(id);
        if (Func.isEmpty(workOrder)) {
            throw new ServiceException("工单不存在");
        }
        workOrder.setStartTime(new Date());
        workOrder.setWorkOrderStatus(WorkOrderStatusEnum.HANDLING.getValue());
        updateById(workOrder);
        // 添加处理记录
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue() && Func.isNotEmpty(workOrder.getLinkNo())) {
            //报事报修更新状态
            SaasMatterRepair matterRepair = matterRepairService.getById(workOrder.getLinkNo());
            matterRepair.setRepairStatus(RepairStatusEnum.HANDLING.getValue());
            matterRepairService.updateById(matterRepair);
            SaasMatterRepairHandleRecord handleRecord = new SaasMatterRepairHandleRecord();
            handleRecord.setRepairId(workOrder.getLinkNo());
            handleRecord.setOperateTime(new Date());
            handleRecord.setOperateType("开始处理");
            handleRecord.setOperateUserId(AuthUtil.getUser().getOrgUserId());
            matterRepairHandleRecordService.save(handleRecord);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitHandle(SaasWorkOrderSubmitHandleDto submitHandleDto) {
        SaasWorkOrder workOrder = getById(submitHandleDto.getId());
        if (Func.isEmpty(workOrder)) {
            throw new ServiceException("工单不存在");
        }
        workOrder.setDispatchType(submitHandleDto.getDispatchType());
        workOrder.setFinishTime(new Date());
        workOrder.setHandleResult(submitHandleDto.getHandleResult());
        workOrder.setFinishDesc(submitHandleDto.getFinishDesc());
        workOrder.setFinishImage(submitHandleDto.getFinishImage());
        workOrder.setWorkOrderStatus(WorkOrderStatusEnum.TO_CONFIRM.getValue());
        updateById(workOrder);
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            SaasWorkOrderMatterRepair matterRepair = workOrderMatterRepairService.lambdaQuery().eq(SaasWorkOrderMatterRepair::getWorkOrderId, workOrder.getId()).one();
            matterRepair.setRepairTypeId(submitHandleDto.getRepairTypeId());
            matterRepair.setAssistUserIds(submitHandleDto.getAssistUserIds());
            List<Long> assistUserIdList = Arrays.stream(submitHandleDto.getAssistUserIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<NestOrgUser> feignResult = iOrgUserClient.findOrgUserListByIds(assistUserIdList).getData();
            List<String> orgUserNameList = feignResult.stream().map(NestOrgUser::getName).collect(Collectors.toList());
            matterRepair.setAssistUserNames(CollUtil.join(orgUserNameList, ","));
            workOrderMatterRepairService.updateById(matterRepair);
        }
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            SaasWorkOrderDeviceRepair deviceRepair = workOrderDeviceRepairService.lambdaQuery().eq(SaasWorkOrderDeviceRepair::getWorkOrderId, workOrder.getId()).one();
            deviceRepair.setRepairTypeId(submitHandleDto.getRepairTypeId());
            deviceRepair.setAssistUserIds(submitHandleDto.getAssistUserIds());
            List<Long> assistUserIdList = Arrays.stream(submitHandleDto.getAssistUserIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<NestOrgUser> feignResult = iOrgUserClient.findOrgUserListByIds(assistUserIdList).getData();
            List<String> orgUserNameList = feignResult.stream().map(NestOrgUser::getName).collect(Collectors.toList());
            deviceRepair.setAssistUserNames(CollUtil.join(orgUserNameList, ","));
            workOrderDeviceRepairService.updateById(deviceRepair);
        }
        // 添加处理记录
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue() && Func.isNotEmpty(workOrder.getLinkNo())) {
            SaasMatterRepairHandleRecord handleRecord = new SaasMatterRepairHandleRecord();
            handleRecord.setRepairId(workOrder.getLinkNo());
            handleRecord.setOperateTime(new Date());
            handleRecord.setOperateType("提交处理");
            handleRecord.setOperateUserId(AuthUtil.getUser().getOrgUserId());
            matterRepairHandleRecordService.save(handleRecord);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean receipt(SaasWorkOrderReceiptDto workOrderReceiptDto) {
        SaasWorkOrder workOrder = getById(workOrderReceiptDto.getId());
        workOrder.setFinishTime(workOrderReceiptDto.getFinishTime());
        workOrder.setReceiptTime(new Date());
        //回单人
        Long receiptUserId = AuthUtil.getUser().getOrgUserId();
        String receiptUserName = iOrgUserClient.detail(receiptUserId).getData().getName();
        workOrder.setReceiptUserId(receiptUserId);
        workOrder.setReceiptUserName(receiptUserName);
        workOrder.setHandleResult(workOrderReceiptDto.getHandleResult());
        workOrder.setFinishDesc(workOrderReceiptDto.getFinishDesc());
        workOrder.setFinishImage(workOrderReceiptDto.getFinishImage());
        workOrder.setWorkOrderStatus(WorkOrderStatusEnum.TO_CONFIRM.getValue());
        updateById(workOrder);
        // 添加处理记录
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue() && Func.isNotEmpty(workOrder.getLinkNo())) {
            SaasMatterRepairHandleRecord handleRecord = new SaasMatterRepairHandleRecord();
            handleRecord.setRepairId(workOrder.getLinkNo());
            handleRecord.setOperateTime(new Date());
            handleRecord.setOperateType("回单");
            handleRecord.setOperateUserId(AuthUtil.getUser().getOrgUserId());
            handleRecord.setOperateContent(workOrderReceiptDto.getFinishDesc());
            handleRecord.setImgUrl(workOrderReceiptDto.getFinishImage());
            matterRepairHandleRecordService.save(handleRecord);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirm(SaasWorkOrderConfirmDto workOrderConfirmDto) {
        SaasWorkOrder workOrder = getById(workOrderConfirmDto.getId());
        workOrder.setConfirmTime(new Date());
        workOrder.setCloseTime(new Date());
        workOrder.setCloseReason(4);
        workOrder.setConfirmResult(workOrderConfirmDto.getConfirmResult());
        workOrder.setConfirmOpinion(workOrderConfirmDto.getConfirmOpinion());
        workOrder.setWorkOrderStatus(workOrderConfirmDto.getConfirmResult() == 1 ? WorkOrderStatusEnum.HANDLING.getValue() : WorkOrderStatusEnum.CLOSED.getValue());
        updateById(workOrder);
        //todo 设备报修完新增一个维修记录；addAssetsMaintainData
        // 添加处理记录
        if (workOrder.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue() && Func.isNotEmpty(workOrder.getLinkNo())) {
            //报事报修更新状态
            SaasMatterRepair matterRepair = matterRepairService.getById(workOrder.getLinkNo());
            matterRepair.setRepairStatus(RepairStatusEnum.TO_RETURN.getValue());
            matterRepairService.updateById(matterRepair);
            SaasMatterRepairHandleRecord handleRecord = new SaasMatterRepairHandleRecord();
            handleRecord.setRepairId(workOrder.getLinkNo());
            handleRecord.setOperateTime(new Date());
            handleRecord.setOperateType("回单确认");
            handleRecord.setOperateUserId(AuthUtil.getUser().getOrgUserId());
            handleRecord.setOperateContent(workOrderConfirmDto.getConfirmOpinion());
            matterRepairHandleRecordService.save(handleRecord);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean close(SaasWorkOrderCloseDto workOrderCloseDto) {
        SaasWorkOrder workOrder = getById(workOrderCloseDto.getId());
        workOrder.setCloseTime(new Date());
        workOrder.setCloseReason(workOrderCloseDto.getCloseReason());
        workOrder.setCloseDesc(workOrderCloseDto.getCloseDesc());
        workOrder.setWorkOrderStatus(WorkOrderStatusEnum.CLOSED.getValue());
        return updateById(workOrder);
    }

    @Override
    public SaasWorkOrderVo getDetail(Long id) {
        SaasWorkOrderVo workOrderVo = BeanUtil.copyProperties(getById(id), SaasWorkOrderVo.class);
        if (Func.isEmpty(workOrderVo)) {
            throw new ServiceException("工单不存在");
        }
        if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            SaasWorkOrderMatterRepairVo matterRepairVo = BeanUtil.copyProperties(workOrderMatterRepairService.lambdaQuery().eq(SaasWorkOrderMatterRepair::getWorkOrderId, id).one(), SaasWorkOrderMatterRepairVo.class);
            if (Func.isEmpty(matterRepairVo)) {
                throw new ServiceException("详情不存在");
            }
            matterRepairVo.setRepairTypeName(repairTypeService.getById(matterRepairVo.getRepairTypeId()).getName());
            workOrderVo.setMatterRepairVo(matterRepairVo);
        } else if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            SaasWorkOrderDeviceRepairVo deviceRepairVo = BeanUtil.copyProperties(workOrderDeviceRepairService.lambdaQuery().eq(SaasWorkOrderDeviceRepair::getWorkOrderId, id).one(), SaasWorkOrderDeviceRepairVo.class);
            if (Func.isEmpty(deviceRepairVo)) {
                throw new ServiceException("详情不存在");
            }
            deviceRepairVo.setRepairTypeName(repairTypeService.getById(deviceRepairVo.getRepairTypeId()).getName());
            List<SaasWorkOrderDeviceRepairDto.DeviceDetail> deviceDetailList = JSON.parseArray(deviceRepairVo.getDeviceDetail(), SaasWorkOrderDeviceRepairDto.DeviceDetail.class);
            deviceDetailList.forEach(deviceDetail -> {
                deviceDetail.setDeviceTypeName(iDictClient.getValue("net_device_type", String.valueOf(deviceDetail.getDeviceType())).getData());
            });
            deviceRepairVo.setDeviceDetailList(deviceDetailList);
            workOrderVo.setDeviceRepairVo(deviceRepairVo);
        } else if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.ALARM_OPERATION.getValue()) {
            SaasWorkOrderAlarmOperationVo alarmOperationVo = BeanUtil.copyProperties(workOrderAlarmOperationService.lambdaQuery().eq(SaasWorkOrderAlarmOperation::getWorkOrderId, id).one(), SaasWorkOrderAlarmOperationVo.class);
            if (Func.isEmpty(alarmOperationVo)) {
                throw new ServiceException("详情不存在");
            }
            workOrderVo.setAlarmOperationVo(alarmOperationVo);
        }
        workOrderVo.setProjectName(pmgBatParkInfoService.getById(workOrderVo.getProjectId()).getParkName());
        workOrderVo.setWorkOrderTypeName(workOrderTypeService.getById(workOrderVo.getWorkOrderTypeId()).getName());
        workOrderVo.setTimeLimitName(workOrderTimeLimitService.getById(workOrderVo.getTimeLimitId()).getTimeLimitName());
        return workOrderVo;
    }

    @Override
    public SaasWorkOrderVo getDetailByLinkNo(Long linkNo) {
        SaasWorkOrderVo workOrderVo = BeanUtil.copyProperties(lambdaQuery().eq(SaasWorkOrder::getLinkNo,linkNo).one(), SaasWorkOrderVo.class);
        if (Func.isEmpty(workOrderVo)) {
            return null;
        }
        if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.MATTER_REPAIR.getValue()) {
            SaasWorkOrderMatterRepairVo matterRepairVo = BeanUtil.copyProperties(workOrderMatterRepairService.lambdaQuery().eq(SaasWorkOrderMatterRepair::getWorkOrderId, workOrderVo.getId()).one(), SaasWorkOrderMatterRepairVo.class);
            if (Func.isEmpty(matterRepairVo)) {
                return null;
            }
            matterRepairVo.setRepairTypeName(repairTypeService.getById(matterRepairVo.getRepairTypeId()).getName());
            workOrderVo.setMatterRepairVo(matterRepairVo);
        } else if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.DEVICE_REPAIR.getValue()) {
            SaasWorkOrderDeviceRepairVo deviceRepairVo = BeanUtil.copyProperties(workOrderDeviceRepairService.lambdaQuery().eq(SaasWorkOrderDeviceRepair::getWorkOrderId, workOrderVo.getId()).one(), SaasWorkOrderDeviceRepairVo.class);
            if (Func.isEmpty(deviceRepairVo)) {
                return null;
            }
            List<SaasWorkOrderDeviceRepairDto.DeviceDetail> deviceDetailList = JSON.parseArray(deviceRepairVo.getDeviceDetail(), SaasWorkOrderDeviceRepairDto.DeviceDetail.class);
            deviceDetailList.forEach(deviceDetail -> {
                deviceDetail.setDeviceTypeName(iDictClient.getValue("net_device_type", String.valueOf(deviceDetail.getDeviceType())).getData());
            });
            deviceRepairVo.setDeviceDetailList(deviceDetailList);
            workOrderVo.setDeviceRepairVo(deviceRepairVo);
        } else if (workOrderVo.getWorkOrderCategory() == WorkOrderCategoryEnum.ALARM_OPERATION.getValue()) {
            SaasWorkOrderAlarmOperationVo alarmOperationVo = BeanUtil.copyProperties(workOrderAlarmOperationService.lambdaQuery().eq(SaasWorkOrderAlarmOperation::getWorkOrderId, workOrderVo.getId()).one(), SaasWorkOrderAlarmOperationVo.class);
            if (Func.isEmpty(alarmOperationVo)) {
                return null;
            }
            workOrderVo.setAlarmOperationVo(alarmOperationVo);
        }
        workOrderVo.setProjectName(pmgBatParkInfoService.getById(workOrderVo.getProjectId()).getParkName());
        workOrderVo.setWorkOrderTypeName(workOrderTypeService.getById(workOrderVo.getWorkOrderTypeId()).getName());
        workOrderVo.setTimeLimitName(workOrderTimeLimitService.getById(workOrderVo.getTimeLimitId()).getTimeLimitName());
        return workOrderVo;
    }

    @Override
    public SaasWorkOrderStatisticsVo statisticsAuditCount(Integer workOrderCategory, Long dispatchUserId) {
        SaasWorkOrderStatisticsVo statisticsVo = new SaasWorkOrderStatisticsVo();
        Integer todayCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory)
                .ge(SaasWorkOrder::getCreateTime, DateUtil.beginOfDay(new Date())).le(SaasWorkOrder::getCreateTime, DateUtil.endOfDay(new Date())).count();
        statisticsVo.setTodayCount(todayCount);
        Integer allCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory).like(Func.isNotEmpty(dispatchUserId), SaasWorkOrder::getDispatchUserIds, dispatchUserId).count();
        statisticsVo.setAllCount(allCount);
        Integer toBeginCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory).like(Func.isNotEmpty(dispatchUserId), SaasWorkOrder::getDispatchUserIds, dispatchUserId).eq(SaasWorkOrder::getWorkOrderStatus, 1).count();
        statisticsVo.setToBeginCount(toBeginCount);
        Integer ProcessingCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory).like(Func.isNotEmpty(dispatchUserId), SaasWorkOrder::getDispatchUserIds, dispatchUserId).eq(SaasWorkOrder::getWorkOrderStatus, 2).count();
        statisticsVo.setProcessingCount(ProcessingCount);
        Integer toConfirmCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory).like(Func.isNotEmpty(dispatchUserId), SaasWorkOrder::getDispatchUserIds, dispatchUserId).eq(SaasWorkOrder::getWorkOrderStatus, 3).count();
        statisticsVo.setToConfirmCount(toConfirmCount);
        Integer closeCount = this.lambdaQuery().eq(SaasWorkOrder::getWorkOrderCategory, workOrderCategory).like(Func.isNotEmpty(dispatchUserId), SaasWorkOrder::getDispatchUserIds, dispatchUserId).eq(SaasWorkOrder::getWorkOrderStatus, 4).count();
        statisticsVo.setCloseCount(closeCount);
        Integer timeoutCount = 0;
        statisticsVo.setTimeoutCount(timeoutCount);
        return statisticsVo;
    }

    @Override
    public NestPage<SaasWorkOrderMatterRepairListVo> getMatterRepairList(SaasWorkOrderMatterRepairQueryDto queryDto) {
        // 分页获取数据
        Page<SaasWorkOrderMatterRepairListVo> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = baseMapper.getMatterRepairList(page, queryDto);
        List<SaasWorkOrderMatterRepairListVo> list = page.getRecords();
        for (SaasWorkOrderMatterRepairListVo vo : list) {
            // 报修类型名称
            vo.setRepairTypeName(repairTypeService.getById(vo.getRepairTypeId()).getName());
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
        }
        return PageConverterUtils.convert(page);
    }

    @Override
    public void exportMatterRepair(SaasWorkOrderMatterRepairQueryDto queryDto, HttpServletResponse response) {
        // 分页获取数据
        Page<SaasWorkOrderMatterRepairListVo> page = new Page<>(1, 100000);
        page = baseMapper.getMatterRepairList(page, queryDto);
        List<SaasWorkOrderMatterRepairListVo> list = page.getRecords();
        List<SaasWorkOrderMatterRepairExcelVo> excelVoList = BeanUtil.copyProperties(list, SaasWorkOrderMatterRepairExcelVo.class);
        for (SaasWorkOrderMatterRepairExcelVo vo : excelVoList) {
            vo.setWorkOrderStatusStr(WorkOrderStatusEnum.getDescByCode(vo.getWorkOrderStatus()));
            vo.setRepairAreaStr(vo.getRepairArea() == 1 ? "户内" : "公区");
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
            vo.setWorkOrderCategoryStr(WorkOrderCategoryEnum.getDescByCode(vo.getWorkOrderCategory()));
            vo.setHandleResultStr(HandleResultEnum.getDescByCode(vo.getHandleResult()));
            vo.setConfirmResultStr(ConfirmResultEnum.getDescByCode(vo.getConfirmResult()));
            vo.setCloseReasonStr(CloseReasonEnum.getDescByCode(vo.getCloseReason()));
        }
        try {
            String fileName = URLEncoder.encode("报事报修工单表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SaasWorkOrderMatterRepairExcelVo.class)
                    .sheet("报事报修工单表")
                    .doWrite(excelVoList); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public NestPage<SaasWorkOrderDeviceRepairListVo> getDeviceRepairList(SaasWorkOrderDeviceRepairQueryDto queryDto) {
        // 分页获取数据
        Page<SaasWorkOrderDeviceRepairListVo> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = baseMapper.getDeviceRepairList(page, queryDto);
        List<SaasWorkOrderDeviceRepairListVo> list = page.getRecords();
        for (SaasWorkOrderDeviceRepairListVo vo : list) {
            // 报修类型名称
            vo.setRepairTypeName(repairTypeService.getById(vo.getRepairTypeId()).getName());
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
        }
        return PageConverterUtils.convert(page);
    }

    @Override
    public void exportDeviceRepair(SaasWorkOrderDeviceRepairQueryDto queryDto, HttpServletResponse response) {
        // 分页获取数据
        Page<SaasWorkOrderDeviceRepairListVo> page = new Page<>(1, 100000);
        page = baseMapper.getDeviceRepairList(page, queryDto);
        List<SaasWorkOrderDeviceRepairListVo> list = page.getRecords();
        List<SaasWorkOrderDeviceRepairExcelVo> excelVoList = BeanUtil.copyProperties(list, SaasWorkOrderDeviceRepairExcelVo.class);
        for (SaasWorkOrderDeviceRepairExcelVo vo : excelVoList) {
            vo.setWorkOrderStatusStr(WorkOrderStatusEnum.getDescByCode(vo.getWorkOrderStatus()));
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
            vo.setWorkOrderCategoryStr(WorkOrderCategoryEnum.getDescByCode(vo.getWorkOrderCategory()));
            vo.setHandleResultStr(HandleResultEnum.getDescByCode(vo.getHandleResult()));
            vo.setConfirmResultStr(ConfirmResultEnum.getDescByCode(vo.getConfirmResult()));
            vo.setCloseReasonStr(CloseReasonEnum.getDescByCode(vo.getCloseReason()));
        }
        try {
            String fileName = URLEncoder.encode("设备报修工单表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SaasWorkOrderDeviceRepairExcelVo.class)
                    .sheet("设备报修工单表")
                    .doWrite(excelVoList); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public NestPage<SaasWorkOrderAlarmOperationListVo> getAlarmOperationList(SaasWorkOrderAlarmOperationQueryDto queryDto) {
        // 分页获取数据
        Page<SaasWorkOrderAlarmOperationListVo> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = baseMapper.getAlarmOperationList(page, queryDto);
        List<SaasWorkOrderAlarmOperationListVo> list = page.getRecords();
        for (SaasWorkOrderAlarmOperationListVo vo : list) {
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
        }
        return PageConverterUtils.convert(page);
    }

    @Override
    public void exportAlarmOperation(SaasWorkOrderAlarmOperationQueryDto queryDto, HttpServletResponse response) {
        // 分页获取数据
        Page<SaasWorkOrderAlarmOperationListVo> page = new Page<>(1, 100000);
        page = baseMapper.getAlarmOperationList(page, queryDto);
        List<SaasWorkOrderAlarmOperationListVo> list = page.getRecords();
        List<SaasWorkOrderAlarmOperationExcelVo> excelVoList = BeanUtil.copyProperties(list, SaasWorkOrderAlarmOperationExcelVo.class);
        for (SaasWorkOrderAlarmOperationExcelVo vo : excelVoList) {
            vo.setWorkOrderStatusStr(WorkOrderStatusEnum.getDescByCode(vo.getWorkOrderStatus()));
            vo.setProjectName(pmgBatParkInfoService.getById(vo.getProjectId()).getParkName());
            vo.setWorkOrderTypeName(workOrderTypeService.getById(vo.getWorkOrderTypeId()).getName());
            vo.setTimeLimitName(workOrderTimeLimitService.getById(vo.getTimeLimitId()).getTimeLimitName());
            vo.setWorkOrderCategoryStr(WorkOrderCategoryEnum.getDescByCode(vo.getWorkOrderCategory()));
            vo.setHandleResultStr(HandleResultEnum.getDescByCode(vo.getHandleResult()));
            vo.setConfirmResultStr(ConfirmResultEnum.getDescByCode(vo.getConfirmResult()));
            vo.setCloseReasonStr(CloseReasonEnum.getDescByCode(vo.getCloseReason()));
        }
        try {
            String fileName = URLEncoder.encode("告警运维工单表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SaasWorkOrderAlarmOperationExcelVo.class)
                    .sheet("告警运维工单表")
                    .doWrite(excelVoList); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

}
