package com.tuoheng.miniprogram.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.common.core.common.BaseServiceImpl;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.miniprogram.dao.*;
import com.tuoheng.miniprogram.entity.*;
import com.tuoheng.miniprogram.entity.dto.WorkOrderDto;
import com.tuoheng.miniprogram.entity.query.HandleQuery;
import com.tuoheng.miniprogram.entity.query.WorkOrderQuery;
import com.tuoheng.miniprogram.enums.*;
import com.tuoheng.miniprogram.service.IWorkOrderService;
import com.tuoheng.miniprogram.utils.CurrentUserUtil;
import com.tuoheng.miniprogram.vo.WorkOrderCountVo;
import com.tuoheng.miniprogram.vo.WorkOrderHandleVo;
import com.tuoheng.miniprogram.vo.WorkOrderInfoVo;
import com.tuoheng.miniprogram.vo.WorkOrderNumVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/12/6
 */
@Service
@Slf4j
public class WorkOrderServiceImpl extends BaseServiceImpl<WorkOrderMapper, WorkOrder> implements IWorkOrderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkOrderFileMapper workOrderFileMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Override
    public JsonResult addInfo(WorkOrderDto dto) {
        //登录用户信息
        String tenantId = CurrentUserUtil.getTenantId();
        dto.setTenantId(tenantId);
        if (StringUtils.isEmpty(dto.getTenantId())) {
            return JsonResult.error(WorkOrderEnum.TENANT_ID_IS_NULL.getCode(), WorkOrderEnum.TENANT_ID_IS_NULL.getMsg());
        }
        if (StringUtils.isEmpty(dto.getInspectionFileId())) {
            return JsonResult.error(WorkOrderEnum.INSPECTION_FILE_ID_IS_NULL.getCode(), WorkOrderEnum.INSPECTION_FILE_ID_IS_NULL.getMsg());
        }
        //登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String username = userInfo.getUsername();
        if (StringUtils.isEmpty(username)) {
            return JsonResult.error(WorkOrderEnum.USER_NAME_IS_NULL.getCode(), WorkOrderEnum.USER_NAME_IS_NULL.getMsg());
        }
        //根据用户id查询部门id
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getUsername, username));
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(WorkOrderEnum.USER_IS_NOT_EXIST.getCode(), WorkOrderEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String deptId = user.getDeptId();
        if (StringUtils.isEmpty(deptId)) {
            return JsonResult.error(WorkOrderEnum.DEPT_ID_IS_NULL.getCode(), WorkOrderEnum.DEPT_ID_IS_NULL.getMsg());
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setTenantId(dto.getTenantId());
        workOrder.setDeptId(deptId);
        //分配人员是当前登录用户
        workOrder.setDistributionId(user.getId());
        //工单编号 XJGD+日期+随机
        String code = DateUtils.generateCode("XJGD");
        workOrder.setCode(code);
        workOrder.setStatus(WorkOrderStatusEnum.STATUS_ALLOCATED.getCode());
//        workOrder.setAssignDeptId(deptId);
//        workOrder.setAssignUser(user.getId());
//        workOrder.setAssignContact(user.getMobile());
//        workOrder.setAssignTime(DateUtils.now());
        workOrder.setCreateUser(user.getId());
        workOrder.setCreateTime(DateUtils.now());
        workOrder.setMark(1);
        super.add(workOrder);
        //工单子表数据入库
        WorkOrderFile workOrderFile = new WorkOrderFile();
        workOrderFile.setTenantId(dto.getTenantId());
        workOrderFile.setInspectionFileId(dto.getInspectionFileId());
        workOrderFile.setWorkOrderId(workOrder.getId());
        int num = workOrderFileMapper.insert(workOrderFile);
        if (num <= 0) {
            return JsonResult.error();
        }
        //更新问题状态为工单已生成
        InspectionFile inspectionFile = inspectionFileMapper.selectById(dto.getInspectionFileId());
        inspectionFile.setStatus(InspectionFileStatusEnum.GENERATE_ORDER.getCode());
        int count = inspectionFileMapper.updateById(inspectionFile);
        if (count <= 0) {
            return JsonResult.error();
        }

        return JsonResult.success();
    }

    /**
     * 代办工单
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult getTodoList(WorkOrderQuery query) {
        if (query.getLimit() == null && query.getPage() == null) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户信息
        User user = CurrentUserUtil.getUserInfo();
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(WorkOrderEnum.USER_IS_NOT_EXIST.getCode(), WorkOrderEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String tenantId = user.getTenantId();
        if (null == tenantId) {
            return JsonResult.error(WorkOrderEnum.DEPT_ID_IS_NULL.getCode(), WorkOrderEnum.DEPT_ID_IS_NULL.getMsg());
        }
        query.setTenantId(tenantId);
        //获取分页数据
        IPage<WorkOrder> page = new Page<>(query.getPage(), query.getLimit());
        IPage<WorkOrderInfoVo> pageData = new Page<>(query.getPage(), query.getLimit());
        //时间处理
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(query.getTime())) {
            startTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 00:00:00");
            endTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 23:59:59");
        }
        query.setOrderStartTime(startTime);
        query.setOrderEndTime(endTime);
        Integer type = user.getDataPermission();

        //查询分配我的待处理工单
        List<WorkOrderInfoVo> workOrderVo = this.myWorkOrderList(user,query);
        List<WorkOrderInfoVo> list = new ArrayList<>();
        //数据权限为1当前租户下的数据
        if (RoleEnum.SUPER_ADMIN.getCode() == type) {
            //查询当前租户下所有工单数据
            IPage<WorkOrder> workPageData = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getStatus, 5)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            if (null == workPageData.getRecords()) {
                return JsonResult.success("数据为空");
            }

            List<WorkOrderInfoVo>  getWorkOrderVo = this.getWorkOrderList(workPageData,user);
            if(CollectionUtil.isNotEmpty(workOrderVo) || workOrderVo.size() != 0){
                list.addAll(workOrderVo);
            }
            if(CollectionUtil.isNotEmpty(getWorkOrderVo) || getWorkOrderVo.size() != 0){
                list.addAll(getWorkOrderVo);
            }
            pageData.setRecords(list);

            return JsonResult.success(pageData);
        }

        //数据权限为2部门管理员查询本部门及子部门工单数据
        if (RoleEnum.ADMIN.getCode() == type) {
            //根据部门id获取本部门及子部门列表
            String deptId = user.getDeptId();
            if(StringUtils.isEmpty(deptId)){
                return JsonResult.error(QueryDeptChildListCodeEnum.DEPT_ID_IS_NULL.getCode(),QueryDeptChildListCodeEnum.DEPT_ID_IS_NULL.getMsg());
            }
            List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
            if (CollectionUtil.isEmpty(deptIdList)) {
                log.info("获取部门列表为空");
                return JsonResult.error(QueryDeptChildListCodeEnum.DEPT_LIST_IS_FAILED.getCode(), QueryDeptChildListCodeEnum.DEPT_LIST_IS_FAILED.getMsg());
            }

            //查询当前部门及子部门下所有工单数据
            IPage<WorkOrder> workPageData = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getStatus, 5)
                    .in(WorkOrder::getDeptId,deptIdList)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            if (null == workPageData.getRecords()) {
                return JsonResult.success("数据为空");
            }

            List<WorkOrderInfoVo>  getWorkOrderVo = this.getWorkOrderList(workPageData,user);
            if(CollectionUtil.isNotEmpty(workOrderVo) || workOrderVo.size() != 0){
                list.addAll(workOrderVo);
            }
            if(CollectionUtil.isNotEmpty(getWorkOrderVo) || getWorkOrderVo.size() != 0){
                list.addAll(getWorkOrderVo);
            }
            pageData.setRecords(list);

            return JsonResult.success(pageData);
        }

        //数据权限为3普通用户查询本部门数据
        if (RoleEnum.ORDINARY_USER.getCode() == type) {
            String deptId = user.getDeptId();
            if(StringUtils.isEmpty(deptId)){
                return JsonResult.error(QueryDeptChildListCodeEnum.DEPT_ID_IS_NULL.getCode(),QueryDeptChildListCodeEnum.DEPT_ID_IS_NULL.getMsg());
            }
            IPage<WorkOrder> workPageData = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getStatus, 5)
                    .eq(WorkOrder::getDeptId,deptId)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            if (null == workPageData.getRecords()) {
                return JsonResult.success("数据为空");
            }

            List<WorkOrderInfoVo>  getWorkOrderVo = this.getWorkOrderList(workPageData,user);
            if(CollectionUtil.isNotEmpty(workOrderVo) || workOrderVo.size() != 0){
                list.addAll(workOrderVo);
            }
            if(CollectionUtil.isNotEmpty(getWorkOrderVo) || getWorkOrderVo.size() != 0){
                list.addAll(getWorkOrderVo);
            }
            pageData.setRecords(list);

            return JsonResult.success(pageData);
        }

        return JsonResult.success("数据为空");
    }

    /**
     * 获取我的待处理工单数据
     * @param user
     * @param query
     * @return
     */
    private List<WorkOrderInfoVo> myWorkOrderList(User user,WorkOrderQuery query) {
        Integer type = user.getDataPermission();
        IPage<WorkOrder> page = new Page<>(query.getPage(), query.getLimit());
        List<WorkOrderInfoVo> workOrderInfoList = new ArrayList<>();
        if (RoleEnum.SUPER_ADMIN.getCode() == type || RoleEnum.ADMIN.getCode() == type || RoleEnum.ORDINARY_USER.getCode() == type) {
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            //获取当前分配人对应的工单分页数据
            IPage<WorkOrder> workPageData = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getAssignDeptId, deptId)
                    .in(WorkOrder::getStatus,10)
                    .like(StringUtils.isNotEmpty(user.getId()), WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getTenantId, user.getTenantId())
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            if (null == workPageData.getRecords()) {
                return null;
            }
            workOrderInfoList = this.getWorkOrderList(workPageData, user);
            System.out.println("------->" + workOrderInfoList);
        }
        return workOrderInfoList;
    }

    /**
     * vo数据封装
     * @param workPageData
     * @return
     */
    private List<WorkOrderInfoVo> getWorkOrderList(IPage<WorkOrder> workPageData,User user) {

        List<WorkOrderInfoVo> WorkOrderInfoList = new ArrayList<>();
        //设置每条工单对应的各状态问题数量
        List<WorkOrderInfoVo> workOrderList = workPageData.getRecords().stream().map(x -> {
            WorkOrderInfoVo vo = new WorkOrderInfoVo();
            BeanUtils.copyProperties(x, vo);
            vo.setCreateTime(x.getCreateTime());
            //被分配人员对应id
            String assignUser = x.getAssignUser();
            String[] assignUserId = assignUser.split(",");
            if (StringUtils.isEmpty(assignUserId)) {
                return null;
            }
            List<String> list = new ArrayList<>();
            for (String userId : assignUserId) {
                User userInfo = userMapper.selectById(userId);
                if (ObjectUtil.isNotNull(userInfo)) {
                    list.add(userInfo.getRealname());
                }
            }
            String usernames = list.stream().map(String::valueOf).collect(Collectors.joining("、"));
            vo.setAssignUserName(usernames);
            //问题总数
            List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                    .eq(WorkOrderFile::getWorkOrderId, x.getId()));
            if (CollectionUtil.isEmpty(workOrderFiles)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            vo.setPromTotal(workOrderFiles.size());
            //对应的问题id集合
            List<String> inspectionFiledIds = workOrderFiles.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(inspectionFiledIds)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            //获取问题集合
            List<InspectionFile> inspectionFileList = new ArrayList<>();
            for (String inspectionFiledId : inspectionFiledIds) {
                InspectionFile inspectionFile = inspectionFileMapper.selectById(inspectionFiledId);
                inspectionFileList.add(inspectionFile);
            }
            if(CollectionUtil.isEmpty(inspectionFileList) || inspectionFileList.size() == 0){
                throw new ServiceException("问题数据查询为空");
            }
            log.info("问题列表为：inspectionFileList={}",inspectionFileList.toString());
            //待处理问题总数
            long count = inspectionFileList.stream().filter(t -> t.getStatus() == 20).count();
            log.info("待处理问题总数为：count={}",count);
            if(ArrayUtil.isNotEmpty(count)){
                vo.setPromTodo((int) count);
            }
            //已处理问题总数
            long count1 = inspectionFileList.stream().filter(t -> t.getStatus() == 25).count();
            log.info("已处理问题总数为：count1={}",count1);
            if(ArrayUtil.isNotEmpty(count1)){
                vo.setPromProcessed((int) count1);
            }

            return vo;
        }).collect(Collectors.toList());
        //当待处理问题总数为0时,此工单不出现在代办工单列表并且工单状态修改为15已完成
        List<WorkOrderInfoVo> collect = workOrderList.stream().filter(f -> f.getPromTodo() == 0).collect(Collectors.toList());
        if (null != collect) {
            for (WorkOrderInfoVo workOrderInfoVo : collect) {
                //每一个工单对应的状态发生改变,一个工单id对应一个工单
                WorkOrder workOrder = workOrderMapper.selectById(workOrderInfoVo.getId());
                if (ObjectUtil.isNotNull(workOrder)) {
                    workOrder.setStatus(15);
                    workOrder.setUpdateTime(DateUtils.now());
                    workOrder.setUpdateUser(user.getId());
                    super.update(workOrder);
                }
            }
        }
        //工单的待处理问题个数不为0时 重新返回
        WorkOrderInfoList = workOrderList.stream().filter(h -> h.getPromTodo() != 0).collect(Collectors.toList());

        System.out.println("----->"+ WorkOrderInfoList);

        return WorkOrderInfoList;
    }


    /**
     * 处理工单
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult handle(HandleQuery query) {
        if (StringUtils.isEmpty(query.getId())) {
            JsonResult.error(WorkOrderEnum.WORK_ORDER_ID_IS_NULL.getCode(), WorkOrderEnum.WORK_ORDER_ID_IS_NULL.getMsg());
        }
        if (null == query.getPage() && null == query.getLimit()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //根据工单id获取对应的问题集合
        List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                .eq(WorkOrderFile::getWorkOrderId, query.getId()));
        if (null == workOrderFiles) {
            return JsonResult.error(WorkOrderEnum.DATA_IS_NULL.getCode(), WorkOrderEnum.DATA_IS_NULL.getMsg());
        }
        //工单子表获取对应的问题集合id
        List<String> inspectionFiledIds = workOrderFiles.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());

        //获取分页数据
        IPage<InspectionFile> page = new Page<>(query.getPage(), query.getLimit());
        IPage<WorkOrderHandleVo> pageData = new Page<>(query.getPage(), query.getLimit());
        //获取当前分配人对应的工单分页数据
        IPage<InspectionFile> inspectionFilePageData = inspectionFileMapper.selectPage(page, Wrappers.<InspectionFile>lambdaQuery()
                            .in(InspectionFile::getId, inspectionFiledIds));
        List<WorkOrderHandleVo> list = inspectionFilePageData.getRecords().stream().map(t -> {
            WorkOrderHandleVo vo = new WorkOrderHandleVo();
            BeanUtils.copyProperties(t, vo);
            //工单id
            vo.setWorkOrderId(query.getId());
            //缩略图处理
            if (StringUtils.isNotEmpty(t.getFileThumbnail())) {
                vo.setFileThumbnail(CommonConfig.imageURL + t.getFileThumbnail());
            }
            //原图
            if (StringUtils.isNotEmpty(t.getFileOriginal())) {
                vo.setFileOriginal(CommonConfig.imageURL + t.getFileOriginal());
            }
            //标记图
            if(StringUtils.isNotEmpty(t.getFileImage())){
                vo.setFileImage(CommonConfig.imageURL + t.getFileImage());
            }
            if (StringUtils.isEmpty(t.getInspectionId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            Inspection inspection = inspectionMapper.selectById(t.getInspectionId());
            if (ObjectUtil.isNotNull(inspection)) {
                vo.setName(inspection.getName());
                vo.setExecutionStartTime(inspection.getExecutionStartTime());
                Channel channel = channelMapper.selectById(inspection.getChannelId());
                if (null != channel) {
                    if (StringUtils.isEmpty(channel.getCode())) {
                        throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                    }
                    vo.setCode(channel.getCode());
                }

            }
            //问题类型
            if (StringUtils.isEmpty(t.getQuestionId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            QuestionType questionType = questionTypeMapper.selectById(t.getQuestionId());
            if (ObjectUtil.isNotNull(questionType)) {
                vo.setType(questionType.getName());
                vo.setContent(t.getQuestionName());
            }
            return vo;

        }).collect(Collectors.toList());
        pageData.setRecords(list);

        return JsonResult.success(pageData);
    }

    /**
     * 已完成工单
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult getCompleted(WorkOrderQuery query) {
        if (query.getLimit() == null && query.getPage() == null) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取登录用户信息
        User userInfo1 = CurrentUserUtil.getUserInfo();
        String username = userInfo1.getUsername();
        if (null == username) {
            return JsonResult.error(WorkOrderEnum.USER_NAME_IS_NULL.getCode(), WorkOrderEnum.USER_NAME_IS_NULL.getMsg());
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getUsername, username));
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(WorkOrderEnum.USER_IS_NOT_EXIST.getCode(), WorkOrderEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String tenantId = user.getTenantId();
        if (null == tenantId) {
            return JsonResult.error(WorkOrderEnum.DEPT_ID_IS_NULL.getCode(), WorkOrderEnum.DEPT_ID_IS_NULL.getMsg());
        }
        query.setTenantId(tenantId);
        //根据登录用户判断角色 1超级管理员 2部门管理员 3普通用户
        Integer type = user.getDataPermission();
        //获取分页数据
        IPage<WorkOrder> page = new Page<>(query.getPage(), query.getLimit());
        IPage<WorkOrderInfoVo> pageData = new Page<>(query.getPage(), query.getLimit());
        //时间处理
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(query.getTime())) {
            startTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 00:00:00");
            endTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 23:59:59");
        }
        query.setOrderStartTime(startTime);
        query.setOrderEndTime(endTime);
        //用户角色为2部门管理员 3普通用户
        if (RoleEnum.SUPER_ADMIN.getCode() == type) {
            //超级管理员可查看系统内所有已处理工单
            IPage<WorkOrder> workPageData = workOrderMapper.selectPage(page, new LambdaQueryWrapper<WorkOrder>()
                    .eq(WorkOrder::getStatus, 15)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            //设置每条工单对应的已完成问题数量 问题状态为25问题已处理
            List<WorkOrderInfoVo> collect = workPageData.getRecords().stream().map(s -> {
                WorkOrderInfoVo vo = new WorkOrderInfoVo();
                BeanUtils.copyProperties(s, vo);
                //被分配人员对应的id
                String assignUser = s.getAssignUser();
                if (StringUtils.isEmpty(assignUser)) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                String[] assignUserId = assignUser.split(",");
                List<String> list = new ArrayList<>();
                for (String userId : assignUserId) {
                    User userInfo = userMapper.selectById(userId);
                    if (ObjectUtil.isNotNull(userInfo)) {
                        list.add(userInfo.getRealname());
                    }
                }
                String usernames = list.stream().map(String::valueOf).collect(Collectors.joining("、"));
                vo.setAssignUserName(usernames);
                //问题总数
                List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                        .eq(WorkOrderFile::getWorkOrderId, s.getId()));
                if (null == workOrderFiles) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                vo.setPromTotal(workOrderFiles.size());
                //已解决问题=问题总数
                vo.setPromProcessed(workOrderFiles.size());
                return vo;
            }).collect(Collectors.toList());
            pageData.setRecords(collect);
            return JsonResult.success(pageData);
        }
        //数据权限为2本部门及子部门数据列表
        if (RoleEnum.ADMIN.getCode() == user.getDataPermission()) {
            //获取部门
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            //获取当前本部门及子部门数据
            List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
            //获取当前分配人对应的工单分页数据
            IPage<WorkOrder> workPageData1 = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .in(WorkOrder::getDeptId, deptIdList)
                    .eq(WorkOrder::getStatus, 15)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            //设置每条工单对应的状态问题数量
            List<WorkOrderInfoVo> collect1 = workPageData1.getRecords().stream().map(g -> {
                WorkOrderInfoVo vo = new WorkOrderInfoVo();
                BeanUtils.copyProperties(g, vo);
                //被分配人员对应的id
                String assignUser = g.getAssignUser();
                if (StringUtils.isEmpty(assignUser)) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                String[] assignUserId = assignUser.split(",");
                List<String> list = new ArrayList<>();
                for (String userId : assignUserId) {
                    User userInfo = userMapper.selectById(userId);
                    if (ObjectUtil.isNotNull(userInfo)) {
                        list.add(userInfo.getRealname());
                    }
                }
                String usernames = list.stream().map(String::valueOf).collect(Collectors.joining("、"));
                vo.setAssignUserName(usernames);
                //问题总数
                List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                        .eq(WorkOrderFile::getWorkOrderId, g.getId()));
                if (null == workOrderFiles) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                vo.setPromTotal(workOrderFiles.size());
                //已解决问题=问题总数
                vo.setPromProcessed(workOrderFiles.size());
                return vo;
            }).collect(Collectors.toList());
            pageData.setRecords(collect1);
            return JsonResult.success(pageData);
        }

        //3普通用户
        if(RoleEnum.ORDINARY_USER.getCode() == user.getDataPermission()){
            //获取部门
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            //获取当前分配人对应的工单分页数据
            IPage<WorkOrder> workPageData1 = workOrderMapper.selectPage(page, Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getDeptId, deptId)
                    .eq(WorkOrder::getStatus, 15)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(WorkOrder::getCreateTime));
            //设置每条工单对应的状态问题数量
            List<WorkOrderInfoVo> collect2 = workPageData1.getRecords().stream().map(g -> {
                WorkOrderInfoVo vo = new WorkOrderInfoVo();
                BeanUtils.copyProperties(g, vo);
                //被分配人员对应的id
                String assignUser = g.getAssignUser();
                if (StringUtils.isEmpty(assignUser)) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                String[] assignUserId = assignUser.split(",");
                List<String> list = new ArrayList<>();
                for (String userId : assignUserId) {
                    User userInfo = userMapper.selectById(userId);
                    if (ObjectUtil.isNotNull(userInfo)) {
                        list.add(userInfo.getRealname());
                    }
                }
                String usernames = list.stream().map(String::valueOf).collect(Collectors.joining("、"));
                vo.setAssignUserName(usernames);
                //问题总数
                List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                        .eq(WorkOrderFile::getWorkOrderId, g.getId()));
                if (null == workOrderFiles) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                vo.setPromTotal(workOrderFiles.size());
                //已解决问题=问题总数
                vo.setPromProcessed(workOrderFiles.size());
                return vo;
            }).collect(Collectors.toList());
            pageData.setRecords(collect2);
            return JsonResult.success(pageData);
        }

        return JsonResult.error(WorkOrderEnum.DATA_IS_NULL.getCode(), WorkOrderEnum.DATA_IS_NULL.getMsg());
    }

    /**
     * 工单详情
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult details(HandleQuery query) {
        if (StringUtils.isEmpty(query.getId())) {
            JsonResult.error(WorkOrderEnum.WORK_ORDER_ID_IS_NULL.getCode(), WorkOrderEnum.WORK_ORDER_ID_IS_NULL.getMsg());
        }
        if (null == query.getPage() && null == query.getLimit()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取分页数据
        IPage<InspectionFile> page = new Page<>(query.getPage(), query.getLimit());
        IPage<WorkOrderHandleVo> pageData = new Page<>(query.getPage(), query.getLimit());
        //根据工单id获取对应的问题集合
        List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                .eq(WorkOrderFile::getWorkOrderId, query.getId()));
        if (null == workOrderFiles) {
            return JsonResult.error(WorkOrderEnum.DATA_IS_NULL.getCode(), WorkOrderEnum.DATA_IS_NULL.getMsg());
        }
        //工单子表获取对应的问题集合id
        List<String> inspectionFiledIds = workOrderFiles.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());
//        List<InspectionFile> inspectionFilesList = inspectionFileMapper.selectBatchIds(inspectionFiledIds);
        IPage<InspectionFile> IPageData = inspectionFileMapper.selectPage(page, new LambdaQueryWrapper<InspectionFile>()
                .in(InspectionFile::getId, inspectionFiledIds));
        //设置分页
        //IPage<InspectionFile> inspectionFileIPage = page.setRecords(inspectionFilesList);
        List<WorkOrderHandleVo> collect = IPageData.getRecords().stream().map(s -> {
            WorkOrderHandleVo vo = new WorkOrderHandleVo();
            //对象拷贝
            BeanUtils.copyProperties(s,vo);
            //缩略图处理
            if (StringUtils.isNotEmpty(s.getFileThumbnail())) {
                vo.setFileThumbnail(CommonConfig.imageURL + s.getFileThumbnail());
            }
            //原图
            if (StringUtils.isNotEmpty(s.getFileOriginal())) {
                vo.setFileOriginal(CommonConfig.imageURL + s.getFileOriginal());
            }
            //标识图
            if(StringUtils.isNotEmpty(s.getFileImage())){
                vo.setFileImage(CommonConfig.imageURL + s.getFileImage());
            }
            if (StringUtils.isEmpty(s.getInspectionId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            Inspection inspection = inspectionMapper.selectById(s.getInspectionId());
            if (ObjectUtil.isNotNull(inspection)) {
                vo.setName(inspection.getName());
                //任务执行开始时间取任务执行时间
                vo.setExecutionStartTime(inspection.getInspectionTime());
                Channel channel = channelMapper.selectById(inspection.getChannelId());
                if (null != channel) {
                    if (StringUtils.isEmpty(channel.getCode())) {
                        throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                    }
                    vo.setCode(channel.getCode());
                }
            }
            //问题类型
            if (StringUtils.isEmpty(s.getQuestionId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            QuestionType questionType = questionTypeMapper.selectById(s.getQuestionId());
            if (ObjectUtil.isNotNull(questionType)) {
                vo.setType(questionType.getName());
                vo.setContent(s.getQuestionName());
            }
            return vo;

        }).collect(Collectors.toList());
        pageData.setRecords(collect);

        return JsonResult.success(pageData);
    }

    /**
     * 统计近七天工单数量
     *
     * @return
     */
    @Override
    public JsonResult weekCount() {
        //获取登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String username = userInfo.getUsername();
        if (StringUtils.isEmpty(username)) {
            return JsonResult.error(WorkOrderEnum.USER_NAME_IS_NULL.getCode(), WorkOrderEnum.USER_NAME_IS_NULL.getMsg());
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getUsername, username));
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(WorkOrderEnum.USER_IS_NOT_EXIST.getCode(), WorkOrderEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String tenantId = user.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            return JsonResult.error(WorkOrderEnum.TENANT_ID_IS_NULL.getCode(), WorkOrderEnum.TENANT_ID_IS_NULL.getMsg());
        }
        //用户角色
        Integer type = user.getDataPermission();
        if (null == type) {
            return JsonResult.error(WorkOrderEnum.DATA_IS_NULL.getCode(), WorkOrderEnum.DATA_IS_NULL.getMsg());
        }
        WorkOrderNumVo vo = new WorkOrderNumVo();
        //今日
        DateTime endTime = DateUtil.endOfDay(DateUtil.date());
        //一周前的时间
        DateTime startTime = DateUtil.offset(DateUtil.beginOfDay(DateUtil.date()), DateField.DAY_OF_WEEK, -6);
        if (null == endTime || null == startTime) {
            return null;
        }
        //根据用户角色判断 1超级管理员 2部门管理员 3普通用户
        if (RoleEnum.SUPER_ADMIN.getCode() == type) {
            //获取当前登录用户(超级管理员)已完成工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getStatus, 15)
                    .between(WorkOrder::getUpdateTime, startTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setWeekWorkOrderFinishedSum(workOrders.size());
            }
        }
        //部门管理员 普通用户
        if (RoleEnum.ADMIN.getCode() == type || RoleEnum.ORDINARY_USER.getCode() == type) {
            //获取部门id
            if (StringUtils.isEmpty(user.getDeptId())) {
                return JsonResult.error(WorkOrderEnum.DEPT_ID_IS_NULL.getCode(), WorkOrderEnum.DEPT_ID_IS_NULL.getMsg());
            }
            //获取当前登录用户(被分配人员)的待处理工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .like(WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getStatus, 10)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getDeptId, user.getDeptId())
                    .between(WorkOrder::getAssignTime, startTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setWeekWorkOrderTodoSum(workOrders.size());
            }
            //获取当前登录用户(被分配人员)的已完成工单列表
            List<WorkOrder> result = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .like(WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getStatus, 15)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getDeptId, user.getDeptId())
                    .between(WorkOrder::getUpdateTime, startTime, endTime));
            if (StringUtils.isNotEmpty(result)) {
                vo.setWeekWorkOrderFinishedSum(result.size());
            }
        }

        return JsonResult.success(vo);
    }

    /**
     * 统计上个月的工单数量
     *
     * @return
     */
    @Override
    public JsonResult mothCount() {
        //获取登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String username = userInfo.getUsername();
        if (StringUtils.isEmpty(username)) {
            return JsonResult.error(WorkOrderEnum.USER_NAME_IS_NULL.getCode(), WorkOrderEnum.USER_NAME_IS_NULL.getMsg());
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getUsername, username));
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(WorkOrderEnum.USER_IS_NOT_EXIST.getCode(), WorkOrderEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String tenantId = user.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            return JsonResult.error(WorkOrderEnum.TENANT_ID_IS_NULL.getCode(), WorkOrderEnum.TENANT_ID_IS_NULL.getMsg());
        }
        //用户角色
        Integer type = user.getDataPermission();
        if (null == type) {
            return JsonResult.error(WorkOrderEnum.DATA_IS_NULL.getCode(), WorkOrderEnum.DATA_IS_NULL.getMsg());
        }
        WorkOrderCountVo vo = new WorkOrderCountVo();
        // 上月起始
        Calendar lastMonthFirstDateCal = Calendar.getInstance();
        lastMonthFirstDateCal.add(Calendar.MONTH, -1);
        lastMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
        // 上月末尾
        Calendar lastMonthEndDateCal = Calendar.getInstance();
        lastMonthEndDateCal.add(Calendar.MONTH, -1);
        lastMonthEndDateCal.set(
                Calendar.DAY_OF_MONTH, lastMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH));
        DateTime beginTime = DateUtil.beginOfDay(lastMonthFirstDateCal.getTime());
        DateTime endTime = DateUtil.endOfDay(lastMonthEndDateCal.getTime());
        if (null == endTime || null == beginTime) {
            return null;
        }
        //根据用户角色判断 1超级管理员 2部门管理员 3普通用户
        if (RoleEnum.SUPER_ADMIN.getCode() == type) {
            //获取当前登录用户(超级管理员)已完成工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getStatus, 15)
                    .between(WorkOrder::getUpdateTime, beginTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setMonthWorkOrderFinishedSum(workOrders.size());
            }
        }
        //部门管理员 普通用户
        if (RoleEnum.ADMIN.getCode() == type || RoleEnum.ORDINARY_USER.getCode() == type) {
            //获取部门id
            if (StringUtils.isEmpty(user.getDeptId())) {
                return JsonResult.error(WorkOrderEnum.DEPT_ID_IS_NULL.getCode(), WorkOrderEnum.DEPT_ID_IS_NULL.getMsg());
            }
            //获取当前登录用户(被分配人员)的待处理工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .like(WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getStatus, 10)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getDeptId, user.getDeptId())
                    .between(WorkOrder::getAssignTime, beginTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setMonthWorkOrderTodoSum(workOrders.size());
            }
            //获取当前登录用户(被分配人员)的已完成工单列表
            List<WorkOrder> result = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, MarkEnum.VALID.getCode())
                    .like(WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getStatus, 15)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getDeptId, user.getDeptId())
                    .between(WorkOrder::getUpdateTime, beginTime, endTime));
            if (StringUtils.isNotEmpty(result)) {
                vo.setMonthWorkOrderFinishedSum(result.size());
            }
        }

        return JsonResult.success(vo);
    }

    /**
     *批量生成工单
     * @param idList
     * @return
     */
    @Override
    public JsonResult generate(List<String> idList) {
        log.info("进入生成工单业务， idList:{}", idList);
        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(idList);
        if (0 != result.getCode()) {
            log.info("进入生成工单业务：校验失败：{}", result.getMsg());
            return result;
        }
        List<InspectionFile> inspectionFileList = (List<InspectionFile>) result.getData();
        List<String> inspectionIdList = inspectionFileList.stream().map(o -> o.getInspectionId()).collect(Collectors.toList());
        List<Inspection> inspectionList = inspectionMapper.selectBatchIds(inspectionIdList);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getId, userId)
                .eq(User::getMark, 1));
        result = checkPermission(user, inspectionList);

        if (0 != result.getCode()) {
            log.info("进入生成工单务：校验权限失败：{}", result.getMsg());
            return result;
        }

        WorkOrder workOrder = this.insertWorkOrder(user);

        this.insertWorkOrderFile(workOrder, idList);

        this.updateInspectionFileStatus(userId, idList);

        return JsonResult.success();
    }

    /**
     * 分配工单
     * @param request
     * @return
     */
    @Override
    public JsonResult distribution(DistributionWorkorderRequest request) {
        log.info("进入分配工单业务， request:{}", request);
        JsonResult jsonResult = this.disCheck(request);
        if (0 != jsonResult.getCode()) {
            log.info("进入分配工单业务：校验失败：{}", jsonResult.getMsg());
            return jsonResult;
        }
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        jsonResult = this.distributionWorkOrder(userId, request);
        if (0 != jsonResult.getCode()) {
            log.info("进入分配工单：分配工单失败：{}", jsonResult.getMsg());
            return jsonResult;
        }
        return JsonResult.success();
    }

    private JsonResult disCheck(DistributionWorkorderRequest request) {
        if(StringUtils.isEmpty(request.getWorkorderId())){
            return JsonResult.error(DistributionWorkorderCodeEnum.ID_LIST_IS_NULL.getCode(),DistributionWorkorderCodeEnum.ID_LIST_IS_NULL.getMsg());
        }
        if(StringUtils.isEmpty(request.getAssignDeptId())){
            return JsonResult.error(DistributionWorkorderCodeEnum.ASSIGN_DEPT_ID_IS_NULL.getCode(),DistributionWorkorderCodeEnum.ASSIGN_DEPT_ID_IS_NULL.getMsg());
        }
        if(StringUtils.isEmpty(request.getAssignUserIds())){
            return JsonResult.error(DistributionWorkorderCodeEnum.ASSIGN_USER_ID_IS_NULL.getCode(), DistributionWorkorderCodeEnum.ASSIGN_USER_ID_IS_NULL.getMsg());
        }
        WorkOrder workOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getId, request.getWorkorderId())
                .eq(WorkOrder::getMark, 1));
        if (null == workOrder) {
            return JsonResult.error(DistributionWorkorderCodeEnum.WORK_ORDER_IS_NOT_EXIST.getCode(), DistributionWorkorderCodeEnum.WORK_ORDER_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(workOrder);
    }

    /**
     *
     *  分配工单
     *      1）、修改分配字段信息
     *      2）、修改工单状态
     *      3）、修改更新字段
     *
     * @param userId
     * @param request
     */
    private JsonResult distributionWorkOrder(String userId, DistributionWorkorderRequest request) {
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(request.getWorkorderId());
        workOrder.setUpdateUser(userId);
        workOrder.setUpdateTime(DateUtils.now());
        workOrder.setStatus(WorkOrderStatusEnum.STATUS_ASSIGNED.getCode());
        workOrder.setAssignDeptId(request.getAssignDeptId());
        workOrder.setAssignUser(request.getAssignUserIds());
        workOrder.setAssignTime(DateUtils.now());
        Integer rowCount = workOrderMapper.updateWorkOrder(workOrder);
        if (rowCount <= 0) {
            log.info("修改工单状态， 确认失败");
            return JsonResult.error(GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getCode(), GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 判断是否有生成工单权限
     * 1）、超级管理员可选择所有部门问题生成工单
     * 2）、部门管理员仅可生成本部门工单，无法生成子部门工单
     * 3）、普通用户无生成工单权限
     * 目前小程序不做权限控制
     *
     * @param user
     * @param inspectionList
     * @return
     */
    private JsonResult checkPermission(User user, List<Inspection> inspectionList) {
//        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
//            return JsonResult.success(user);
//        } else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
//            for (Inspection inspection : inspectionList) {
//                if (!user.getDeptId().equals(inspection.getDeptId())) {
//                    return JsonResult.error(GenerateWorkorderCodeEnum.ADMIN_NOT_GENERATE_CHILD_WORKORDER.getCode(), GenerateWorkorderCodeEnum.ADMIN_NOT_GENERATE_CHILD_WORKORDER.getMsg());
//                }
//            }
//            return JsonResult.success(user);
//        } else if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
//            return JsonResult.error(GenerateWorkorderCodeEnum.ORDINARY_USER_NO_PERMISSION_TO_GENERATE.getCode(), GenerateWorkorderCodeEnum.ORDINARY_USER_NO_PERMISSION_TO_GENERATE.getMsg());
//        }
        return JsonResult.success(user);
    }

    /**
     * 检查参数
     *
     * @param idList
     * @return
     */
    private JsonResult check(List<String> idList) {
        // 判断任务问题id是否为空
        if (CollectionUtil.isEmpty(idList)) {
            return JsonResult.error(GenerateWorkorderCodeEnum.ID_LIST_IS_NULL.getCode(), GenerateWorkorderCodeEnum.ID_LIST_IS_NULL.getMsg());
        }
        List<InspectionFile> inspectionFileList = inspectionFileMapper.selectBatchIds(idList);
        if (CollectionUtil.isEmpty(inspectionFileList)) {
            return JsonResult.error(GenerateWorkorderCodeEnum.INSPECTION_FILE_ID_LIST_IS_NOT_EXIST.getCode(), GenerateWorkorderCodeEnum.INSPECTION_FILE_ID_LIST_IS_NOT_EXIST.getMsg());
        }
        for (InspectionFile inspectionFile : inspectionFileList) {
            if (inspectionFile.getStatus() != InspectionFileStatusEnum.CONFIRMED.getCode()) {
                return JsonResult.error(GenerateWorkorderCodeEnum.INCLUDE_NO_CONFIRMED_INSPECTION.getCode(), GenerateWorkorderCodeEnum.INCLUDE_NO_CONFIRMED_INSPECTION.getMsg());
            }
        }
        return JsonResult.success(inspectionFileList);
    }

    /**
     *
     * 添加工单
     *
     */
    private WorkOrder insertWorkOrder(User user) {
        WorkOrder workOrder = new WorkOrder();
        String code = DateUtils.generateCode("XJGD");
        workOrder.setCode(code);
        workOrder.setTenantId(user.getTenantId());
        workOrder.setDeptId(user.getDeptId());
        workOrder.setStatus(WorkOrderStatusEnum.STATUS_ALLOCATED.getCode());
        //分配人员为当前登录用户
        workOrder.setDistributionId(user.getId());
        //指派人员目前临时是当前登录用户
//        workOrder.setAssignUser(user.getId());
//        workOrder.setAssignContact(user.getMobile());
//        workOrder.setAssignTime(DateUtils.now());
        workOrder.setCreateUser(user.getId());
        workOrder.setCreateTime(DateUtils.now());
        Integer rowCount = workOrderMapper.insert(workOrder);
        if (rowCount <= 0) {
            log.info("添加工单表失败");
        }
        return workOrder;
    }

    /**
     *
     * 添加工单子表
     *
     */
    private void insertWorkOrderFile(WorkOrder workOrder, List<String> idList) {
        List<WorkOrderFile> workOrderFileList = new ArrayList<>();
        WorkOrderFile workOrderFile;
        for (String id : idList) {
            workOrderFile = new WorkOrderFile();
            workOrderFile.setTenantId(workOrder.getTenantId());
            workOrderFile.setWorkOrderId(workOrder.getId());
            workOrderFile.setInspectionFileId(id);
            workOrderFileList.add(workOrderFile);
        }

        if (CollectionUtil.isEmpty(workOrderFileList)) {
            return;
        }
        Integer rowCount = workOrderFileMapper.insertBatch(workOrderFileList);
        if (rowCount <= 0) {
            log.info("添加工单子表失败");
        }
    }

    /**
     *
     * 问题状态，改为已生成工单
     *
     * @param userId
     * @param idList
     */
    private JsonResult updateInspectionFileStatus(String userId, List<String> idList) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", InspectionFileStatusEnum.GENERATE_ORDER.getCode());
        map.put("updateUser", userId);
        map.put("updateTime", DateUtils.now());
        map.put("idList", idList);

        Integer rowCount = inspectionFileMapper.updateByIdList(map);
        if (rowCount <= 0) {
            log.info("修改任务问题状态， 确认失败");
            return JsonResult.error(GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getCode(), GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }


    /**
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(Date beginTime, Date endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        allDate.add(DateUtil.formatDate(beginTime));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(beginTime);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(endTime);
        // 测试此日期是否在指定日期之后
        while (endTime.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(DateUtil.formatDate(calBegin.getTime()));
        }
        allDate.remove(allDate.size() - 1);
        return allDate;
    }


}
