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.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.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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 RoadInformationMapper roadInformationMapper;

    @Override
    public JsonResult addInfo(WorkOrderDto dto) {
        //登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String tenantId = userInfo.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());
        }
        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, 1).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_ASSIGNED.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 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, 1)
                .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 = userInfo1.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);
        //根据登录用户判断角色 1超级管理员 2部门管理员 3普通用户
        Integer type = user.getDataPermission();
        if (DataPermissionEnum.ALL.getCode() == type) {

            return JsonResult.success(null,"超级管理员代办工单不显示数据");
        }

        //用户角色为2部门管理员 3普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.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)
                    .eq(WorkOrder::getStatus, 10)
                    .like(StringUtils.isNotEmpty(user.getId()), WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, 1)
                    .orderByDesc(WorkOrder::getCreateTime));
            if (null == workPageData.getRecords()) {
                return null;
            }
            List<WorkOrderInfoVo> WorkOrderInfoList = new ArrayList<>();
            //设置每条工单对应的各状态问题数量
            List<WorkOrderInfoVo> workOrderList = workPageData.getRecords().stream().map(x -> {
                WorkOrderInfoVo vo = new WorkOrderInfoVo();
                BeanUtils.copyProperties(x, vo);
//                vo.setCode(x.getCode());
//                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);
                }
                //待处理问题总数
                long count = inspectionFileList.stream().filter(t -> t.getStatus() == 20).count();
                vo.setPromTodo((int) count);
                //已处理问题总数
                long count1 = inspectionFileList.stream().filter(t -> t.getStatus() == 25).count();
                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());
            pageData.setRecords(WorkOrderInfoList);

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

    /**
     * 处理工单
     *
     * @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());
                RoadInformation roadInformation = roadInformationMapper.selectById(inspection.getRoadId());
                if (null != roadInformation) {
                    if (StringUtils.isEmpty(roadInformation.getCode())) {
                        throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                    }
                    vo.setCode(roadInformation.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.getOrderEndTime()==null && query.getOrderStartTime()==null){
//            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
//        }
        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, 1)
                .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 (DataPermissionEnum.ALL.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, 1)
                    .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部门管理员 3普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission() || DataPermissionEnum.DEPT.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::getAssignDeptId, deptId)
                    .eq(WorkOrder::getStatus, 15)
                    .like(StringUtils.isNotEmpty(user.getId()), WorkOrder::getAssignUser, user.getId())
                    .eq(WorkOrder::getTenantId, tenantId)
                    .between(null != query.getOrderStartTime() && null != query.getOrderEndTime(), WorkOrder::getCreateTime, query.getOrderStartTime(), query.getOrderEndTime())
                    .eq(WorkOrder::getMark, 1)
                    .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);
        }

        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.getExecutionStartTime());
                RoadInformation roadInformation = roadInformationMapper.selectById(inspection.getRoadId());
                if (null != roadInformation) {
                    if (StringUtils.isEmpty(roadInformation.getCode())) {
                        throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                    }
                    vo.setCode(roadInformation.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);



//        IPage<InspectionFile> inspectionFilePageData = page.setRecords(inspectionFilesList);
//        IPage<WorkOrderHandleVo> result = inspectionFilePageData.convert(p -> {
//            WorkOrderHandleVo covert = Convert.convert(WorkOrderHandleVo.class, p);
//            //缩略图处理
//            if (StringUtils.isNotEmpty(p.getFileThumbnail())) {
//                covert.setFileThumbnail(CommonConfig.imageURL + p.getFileThumbnail());
//            }
//            if (StringUtils.isNotEmpty(p.getFileOriginal())) {
//                covert.setFileOriginal(CommonConfig.imageURL + p.getFileOriginal());
//            }
//            //任务名称  任务执行时间 道路位置编号
//            if (StringUtils.isEmpty(p.getInspectionId())) {
//                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
//            }
//            Inspection inspection = inspectionMapper.selectById(p.getInspectionId());
//            if (ObjectUtil.isNotNull(inspection)) {
//                covert.setName(inspection.getName());
//                covert.setExecutionStartTime(inspection.getExecutionStartTime());
//                RoadInformation roadInformation = roadInformationMapper.selectById(inspection.getRoadId());
//                if (null != roadInformation) {
//                    if (StringUtils.isEmpty(roadInformation.getCode())) {
//                        throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
//                    }
//                    covert.setCode(roadInformation.getCode());
//                }
//
//            }
//            //问题类型
//            if (StringUtils.isEmpty(p.getQuestionId())) {
//                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
//            }
//            QuestionType questionType = questionTypeMapper.selectById(p.getQuestionId());
//            if (ObjectUtil.isNotNull(questionType)) {
//                covert.setType(questionType.getName());
//            }
//            return covert;
//
//        });

        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, 1)
                .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 (DataPermissionEnum.ALL.getCode() == type) {
            //获取当前登录用户(超级管理员)已完成工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, 1)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getStatus, 15)
                    .between(WorkOrder::getUpdateTime, startTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setWeekWorkOrderFinishedSum(workOrders.size());
            }
        }
        //部门管理员 普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.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, 1)
                    .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, 1)
                    .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, 1)
                .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 (DataPermissionEnum.ALL.getCode() == type) {
            //获取当前登录用户(超级管理员)已完成工单列表
            List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>lambdaQuery()
                    .eq(WorkOrder::getMark, 1)
                    .eq(WorkOrder::getTenantId, tenantId)
                    .eq(WorkOrder::getStatus, 15)
                    .between(WorkOrder::getUpdateTime, beginTime, endTime));
            if (StringUtils.isNotEmpty(workOrders)) {
                vo.setMonthWorkOrderFinishedSum(workOrders.size());
            }
        }
        //部门管理员 普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.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, 1)
                    .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, 1)
                    .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 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;
    }


}
