package com.zcxk.order.controller;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.client.UserCenterClient;
import com.zcxk.common.ConvertXY;
import com.zcxk.common.FileUploadUtil;
import com.zcxk.common.MyPoint;
import com.zcxk.entity.Message;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.LoginUser;
import com.zcxk.model.Pagination;
import com.zcxk.model.ResultStatus;
import com.zcxk.order.dto.WorkOrderEvaluationDto;
import com.zcxk.order.dto.WorkOrderManageByAlarmDto;
import com.zcxk.order.dto.WorkOrderManageDto;
import com.zcxk.order.entity.WorkFlowDetail;
import com.zcxk.order.entity.WorkFlowLog;
import com.zcxk.order.entity.WorkOrderManage;
import com.zcxk.order.service.WorkFlowDetailService;
import com.zcxk.order.service.WorkFlowLogService;
import com.zcxk.order.service.WorkOrderManageService;
import com.zcxk.process.dto.TaskPorcessResult;
import com.zcxk.process.entity.ProcessDefinition;
import com.zcxk.process.service.WorkFlowService;
import com.zcxk.process.utils.Action;
import com.zcxk.task.entity.PlanManage;
import com.zcxk.task.entity.UserEntity;
import com.zcxk.task.service.PlanManageService;
import com.zcxk.util.DatesUtil;
import com.zcxk.util.MessageSendUtil;
import com.zcxk.util.UserUtil;
import com.zcxk.utils.EvaluationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order/workOrderManage")
@Api(tags = "工单管理")
@Slf4j
public class WorkOrderManageController {

    @Autowired
    WorkOrderManageService workOrderManageService;

    @Autowired
    WorkFlowDetailService workFlowDetailService;

    @Autowired
    PlanManageService planManageService;

    @Autowired
    WorkFlowLogService workFlowLogService;

    @Autowired
    WorkFlowService workFlowService;

    @Autowired
    UserCenterClient userCenterClient;

    @Autowired
    private MessageSendUtil messageSendUtil;

    @Value("${UMIS.sys_config_path}")
    private String baseDir;

    @Value("${UMIS.sys_video_path}")
    private String videoDir;

    @Value("${UMIS.sys_app_package_path}")
    private String appPackageDir;

    /**select
     * 新增一条数据
     * @param workOrderManage 实体类
     * @return Response对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    @ApiOperation(value = "插入工单")
    public AjaxMessage<Integer> insertSelective(@ApiParam(value = "工单信息", required = true) @RequestBody WorkOrderManage workOrderManage) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        workOrderManage.setTenantId(currentUser.getTenantId());
        workOrderManage.setCompanyOrgId(currentUser.getCompanyId()!=null?currentUser.getCompanyId().toString():null);
        workOrderManage.setDepartmentOrgId(currentUser.getDepartmentId()!=null?currentUser.getDepartmentId().toString():null);
        workOrderManage.setCreateBy(currentUser.getId().toString());
        workOrderManage.setDateCreate(workOrderManage.getDateCreate()==null?new Date():workOrderManage.getDateCreate());
        workOrderManage.setOrderStatus(0);
        workOrderManage.setTaskNo(DatesUtil.formatDate(new Date(),"yyyyMMddHHmmss")+String.valueOf((int) (Math.random()*(9999-1000)+1000)));
        workOrderManageService.insertSelective(workOrderManage);
        int result =workOrderManage.getId();//返回新增数据的id
        if(workOrderManage.getEventType()==1) {
            //发消息
            try {
                Message message=new Message();
                message.setStatus(1);
                message.setCreateBy(currentUser.getId().toString());
                message.setTenantId(currentUser.getTenantId());
                message.setMessageContent(workOrderManage.getTaskDesc());
                message.setMessageId(UUID.randomUUID().toString());
                message.setMessageType(3);
                message.setMessageTemplateId(3);
                message.setChannel(0);
                message.setUrl(String.valueOf(result));
                //获取需要发消息的用户
                List<Long> users=userCenterClient.findUserIdsForOrg();
                for(Long user : users){
                    message.setUserId(user.intValue());
                    messageSendUtil.send(message);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        return new AjaxMessage<>(ResultStatus.OK, result);
    }
    /**
     * APP运维管理待处理查询
     * @return Response对象
     */
    @RequestMapping(value = "selectAppTodo", method = RequestMethod.GET)
    @ApiOperation(value = "APP运维管理待处理查询")
    public AjaxMessage<List<WorkOrderManageDto>> selectAppTodo() {
        List<WorkOrderManageDto> result=workOrderManageService.selectAppTodo();
        setName(result);
        return new AjaxMessage<>(ResultStatus.OK,  result);
    }
    /**
     * APP运维管理全部查询
     * @return Response对象
     */
    @RequestMapping(value = "selectAppAll", method = RequestMethod.GET)
    @ApiOperation(value = "APP运维管理全部查询")
    public AjaxMessage<List<WorkOrderManageDto>> selectAppAll() {
        List<WorkOrderManageDto> result=workOrderManageService.selectAppAll();
        setName(result);
        return new AjaxMessage<>(ResultStatus.OK, result);
    }
    /**
     * 任务和工单的审批、app提交、接单、拒单
     * @return Response对象
     */
    @RequestMapping(value = "submitTask", method = RequestMethod.GET)
    @ApiOperation(value = "任务和工单的审批、app提交、接单、拒单 ")
    public AjaxMessage<Integer> submitTask(
            @ApiParam(value = "1任务、2工单", required = true) @RequestParam Integer flowType,
            @ApiParam(value = "任务、工单id", required = true) @RequestParam Integer flowId,
            @ApiParam(value = "处理结果", required = true) @RequestParam String flowResult,
            @ApiParam(value = "1通过、2同意(暂时不用)、3驳回、4漏点定位、5停水、6提交、7拒单、8接单", required = true) @RequestParam Integer actionId) {
        LoginUser currentUser = UserUtil.getCurrentUser();

        WorkFlowLog workFlowLog=new WorkFlowLog();
        workFlowLog.setFlowId(flowId);
        workFlowLog.setFlowType(flowType);
        workFlowLog.setFlowResult(flowResult);
        workFlowLog.setCreateBy(currentUser.getId().toString());
        workFlowLog.setDateCreate(new Date());
        workFlowLog.setHandleUserId(currentUser.getId()!=null?currentUser.getId().toString():null);
        workFlowLog.setHandleUserName(currentUser.getUsername());

        //流程流转 更新当前任务状态
        Action action=null;
        if(actionId==1||actionId==6||actionId==8){
            action=Action.ACTION_AUDIT;
        }else if(actionId==2){
            action=Action.ACTION_RECEIVE;
        }else if(actionId==3||actionId==7){
            action=Action.ACTION_REJECT;
        }
        Map<String,Object> args=new HashMap<>();

        //查询当前工单或任务 并更新当前状态
        if(flowType == 1){
            PlanManage plan= planManageService.selectByPrimaryKey(flowId);
            workFlowLog.setProcessInstanceId(plan.getProcessInstanceId());
            workFlowLog.setTaskId(plan.getCurrentTaskId());
            if(action!=null){
                List<TaskPorcessResult> handleResult = workFlowService.handleTask(action,plan.getCurrentTaskId(), args, null);
                plan.setCurrentTaskId(handleResult.size()>0?handleResult.get(0).getCurrentTaskId():null);
                plan.setCurrentUsers(handleResult.size()>0?handleResult.get(0).getCurrentTaskUsers():null);
                plan.setCurrentTaskName(handleResult.size()>0?handleResult.get(0).getCurrentTaskName():null);
                plan.setUpdateBy(currentUser.getId().toString());
                plan.setDateUpdate(new Date());
                if(actionId==6){
                    plan.setInProcessStatus(2);
                }else if(actionId==1){
                    plan.setInProcessStatus(3);
                }else if(actionId==3){
                    plan.setInProcessStatus(null);
                }
                if(handleResult.size()==0||handleResult==null) {
                    plan.setPlanStatus(2);
                    plan.setFinishDate(new Date());
                }
                planManageService.updateByPrimaryKey(plan);
            }
        }else if(flowType == 2){
            WorkOrderManage order= workOrderManageService.selectByPrimaryKey(flowId);
            workFlowLog.setProcessInstanceId(order.getProcessInstanceId());
            workFlowLog.setTaskId(order.getCurrentTaskId());
            //如果是漏点定位和停水操作 创建子单
            if(actionId==4||actionId==5){
                WorkOrderManage workOrderManage=new WorkOrderManage();
                workOrderManage.setTenantId(currentUser.getTenantId());
                workOrderManage.setCreateBy(currentUser.getId().toString());
                workOrderManage.setDateCreate(new Date());
                workOrderManage.setOrderStatus(0);
                workOrderManage.setTaskNo(DatesUtil.formatDate(new Date(),"yyyyMMddHHmmss")+String.valueOf((int) (Math.random()*(9999-1000)+1000)));
                workOrderManage.setOrderPid(flowId);
                workOrderManage.setEventType(order.getEventType());
                workOrderManage.setCompanyOrgId(order.getCompanyOrgId());
                workOrderManage.setDepartmentOrgId(order.getDepartmentOrgId());
                workOrderManage.setTaskDesc(order.getTaskDesc());
                workOrderManage.setAddress(order.getAddress());
                workOrderManage.setGeo(order.getGeo());
                workOrderManage.setContactUser(order.getContactUser());
                workOrderManage.setContactPhone(order.getContactPhone());
                workOrderManage.setPictures(order.getPictures());
                workOrderManage.setVideos(order.getVideos());
                workOrderManage.setDeviceId(order.getDeviceId());
                workOrderManage.setDeviceName(order.getDeviceName());
                workOrderManage.setScenesId(order.getScenesId());
                workOrderManage.setScenesName(order.getScenesName());
                workOrderManage.setOrderTime(order.getOrderTime());
                workOrderManage.setOrderTypeId(actionId==4?4:2);
                workOrderManageService.insertSelective(workOrderManage);
            }else if(actionId==6){
                //判断子单完成情况后才可以提交
                List<WorkOrderManageDto> childOrder=workOrderManageService.selectOrderDetail(flowId);
                if(childOrder.size()>1){
                    for(int i=1;i<childOrder.size();i++) {
                        WorkOrderManageDto child=childOrder.get(i);
                        if(child.getOrderTypeId()==4&&child.getOrderStatus()!=2&&child.getOrderStatus()!=3) {
                            return new AjaxMessage<>(ResultStatus.CHILD_ORDER_ING);
                        }
                    }
                }
                //判断父单完成情况后才可以提交
                WorkOrderManage parentOrder=workOrderManageService.selectByPrimaryKey(order.getOrderPid());
                if(parentOrder!=null&&order.getOrderTypeId()==2&&parentOrder.getOrderStatus()!=2&&parentOrder.getOrderStatus()!=3) {
                    return new AjaxMessage<>(ResultStatus.PARENT_ORDER_ING);
                }
            }
            if(action!=null){
                List<TaskPorcessResult> handleResult = workFlowService.handleTask(action,order.getCurrentTaskId(), args, null);
                order.setCurrentTaskId(handleResult.size()>0?handleResult.get(0).getCurrentTaskId():null);
                order.setCurrentUsers(handleResult.size()>0?handleResult.get(0).getCurrentTaskUsers():null);
                order.setCurrentTaskName(handleResult.size()>0?handleResult.get(0).getCurrentTaskName():null);
                order.setUpdateBy(currentUser.getId().toString());
                order.setDateUpdate(new Date());
                if(actionId==6){
                    order.setInProcessStatus(2);
                }else if(actionId==8||actionId==3){
                    order.setInProcessStatus(1);
                }else if(actionId==1){
                    order.setInProcessStatus(3);
                }else if(actionId==7){
                    order.setInProcessStatus(null);
                }
                if(handleResult.size()==0||handleResult==null) {
                    order.setOrderStatus(2);
                    order.setFinishDate(new Date());
                }else if(actionId==7){
                    order.setOrderStatus(4);
                }else{
                    order.setOrderStatus(1);
                }
                workOrderManageService.updateByPrimaryKey(order);
            }
        }
        //记录日志
        workFlowLogService.insert(workFlowLog);
        return new AjaxMessage<>(ResultStatus.OK);
    }
    /**
     * APP查询工单详情
     * @return Response对象
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ApiOperation(value = "APP查询工单详情")
    public AjaxMessage<List<WorkOrderManageDto>> selectOrderDetail(
            @ApiParam(value = "工单id", required = true) @RequestParam Integer flowId) {
        List<WorkOrderManageDto> result=workOrderManageService.selectOrderDetail(flowId);
        setName(result);
        return new AjaxMessage<>(ResultStatus.OK,  result);
    }
    @RequestMapping(value = "saveDetail", method = RequestMethod.GET)
    @ApiOperation(value = "保存工单和任务的详情数据")
    public AjaxMessage<Integer> saveDetail(
            @ApiParam(value = "1任务、2工单", required = true) @RequestParam Integer flowType,
            @ApiParam(value = "任务、工单id", required = true) @RequestParam Integer flowId,
            @ApiParam(value = "json格式存储对应任务详情", required = true) @RequestParam String flowDetail){
        LoginUser currentUser = UserUtil.getCurrentUser();
        WorkFlowDetail workFlowDetail =new WorkFlowDetail();
        workFlowDetail.setFlowType(flowType);
        workFlowDetail.setFlowId(flowId);
        workFlowDetail.setFlowDetail(flowDetail);
        Integer detailId = workFlowDetailService.selectDetailId(workFlowDetail);

        //插入或更新详情
        if(detailId==null) {
            workFlowDetail.setCreateBy(currentUser.getId().toString());
            workFlowDetail.setDateCreate(new Date());
            workFlowDetailService.insertSelective(workFlowDetail);
        }else{
            workFlowDetail.setUpdateBy(currentUser.getId().toString());
            workFlowDetail.setDateUpdate(new Date());
            workFlowDetail.setId(detailId);
            workFlowDetailService.updateByPrimaryKeySelective(workFlowDetail);
        }
        return new AjaxMessage<>(ResultStatus.OK);
    }

    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "addImage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage<String> addImage(@ApiParam(value = "图片", required = true) @RequestParam("avatarfile") MultipartFile file) {
        String avatar = "";
        if (!file.isEmpty()) {
            try {
                avatar = FileUploadUtil.uploadWeb(baseDir, file);
            } catch (IOException e) {
                return new AjaxMessage<>(ResultStatus.ERROR, e.getMessage());
            }
        }
        return new AjaxMessage<>(ResultStatus.OK, avatar);
    }
    @ApiOperation(value = "上传视频")
    @RequestMapping(value = "addVideo", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage<String> addVideo(@ApiParam(value = "视频", required = true) @RequestParam("avatarfile") MultipartFile file) {
        String avatar = "";
        if (!file.isEmpty()) {
            try {
                avatar = FileUploadUtil.uploadWeb(videoDir, file);
            } catch (IOException e) {
                return new AjaxMessage<>(ResultStatus.ERROR, e.getMessage());
            }
        }
        return new AjaxMessage<>(ResultStatus.OK, avatar);
    }

    @ApiOperation(value = "上传APP安装包")
    @RequestMapping(value = "addAppPackage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage<String> addAppPackage(@ApiParam(value = "上传APP安装包", required = true) @RequestParam("avatarfile") MultipartFile file,
                                             @RequestPart("filePath") String filePath) {
        String avatar = "";
        if (!file.isEmpty()) {
            try {
                if(filePath == null){
                    return new AjaxMessage<>(ResultStatus.ERROR,"参数文件路径不能为空");
                }
                //上传简单文件名
                String originalFilename = file.getOriginalFilename();
                String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
                //存储路径
                if(!suffixName.toLowerCase().equals(".apk")&&!suffixName.toLowerCase().equals(".ipa")){
                    return new AjaxMessage<>(ResultStatus.ERROR, "上传文件类型不正确");
                }
                long size = file.getSize();
                if (size >  1024 * 1024 * 200) {
                    return   new AjaxMessage<>(ResultStatus.ERROR, "文件不能超过200M");
                }
                avatar = new StringBuffer(appPackageDir).append(filePath).append(originalFilename).toString();
                File dest = new File(avatar);
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(new File(avatar));
            } catch (IOException e) {
                return new AjaxMessage<>(ResultStatus.ERROR, e.getMessage());
            }
        }else{
            return new AjaxMessage<>(ResultStatus.ERROR, "上传文件不能为空");
        }
        return new AjaxMessage<>(ResultStatus.OK, avatar);
    }

    @GetMapping("/event/select")
    @ApiOperation(value = "查询事件隐患/所有工单")
    public AjaxMessage<Pagination<WorkOrderManageDto>> selectEvent(
            @ApiParam(value = "页数", required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "条数", required = true)@RequestParam Integer pageSize,
            @ApiParam(value = "状态(0:事件隐患;null:所有工单;1:执行中;2:完成)", required = false) @RequestParam(required = false) Integer orderStatus,
            @ApiParam(value = "工单类型(1表务、2停通水、3抢修、4漏点定位、5测漏、6违章跑水、10压力调度)", required = false) @RequestParam(required = false) Integer orderTypeId,
            @ApiParam(value = "事件类型(1:运维上报,2:用户上报,3:设备告警)", required = false) @RequestParam(required = false) Integer eventType,
            @ApiParam(value = "单号", required = false) @RequestParam(required = false) String taskNo,
            @ApiParam(value = "计划起始日期(yyyy-MM-dd)", required = false) @RequestParam(required = false) String startDate,
            @ApiParam(value = "计划截至日期(yyyy-MM-dd)", required = false) @RequestParam(required = false) String endDate){
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        //根据用户编号，获取用户的权限
        LoginUser loginUser = UserUtil.getCurrentUser();
        workOrderManageDto.setTaskNo(taskNo);
        workOrderManageDto.setOrderStatus(orderStatus);
        workOrderManageDto.setEventType(eventType);
        workOrderManageDto.setTenantId(loginUser.getTenantId());
        workOrderManageDto.setOrderTypeId(orderTypeId);
        workOrderManageDto.setProgramItems(loginUser.getProgramItemList());
        workOrderManageDto.setUserType(loginUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        workOrderManageDto.setPermissonType(loginUser.getPermissonType());

        if(!org.springframework.util.StringUtils.isEmpty(startDate)&& !StringUtils.isEmpty(endDate)) {
            workOrderManageDto.setStartDate(startDate);
            workOrderManageDto.setEndDate(endDate);
        }
        IPage<WorkOrderManageDto> iPage = new Page<>(pageNum, pageSize);
        iPage = workOrderManageService.selectPage(iPage, workOrderManageDto);
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    /**
     * 事件列表查询 ，按创建事件排序
     * @param pageNum 分页参数
     * @param pageSize 分页参数
     * @return
     */
    @GetMapping("/event/list")
    @ApiOperation(value = "App事件列表")
    public AjaxMessage<Pagination<WorkOrderManageDto>> selectEventList(
            @ApiParam(value = "页数", required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "条数", required = true)@RequestParam Integer pageSize){
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        //根据用户编号，获取用户的权限
        LoginUser loginUser = UserUtil.getCurrentUser();
        workOrderManageDto.setTenantId(loginUser.getTenantId());
        if(loginUser.getCompanyId()!=null) {
            workOrderManageDto.setCompanyOrgId(loginUser.getCompanyId().toString());
        }
        if(loginUser.getDepartmentId() != null) {
            workOrderManageDto.setDepartmentOrgId(loginUser.getDepartmentId().toString());
        }
        workOrderManageDto.setCreateBy(loginUser.getId().toString());
        IPage<WorkOrderManageDto> iPage = new Page<>(pageNum, pageSize);
        iPage = workOrderManageService.findEventListPage(iPage, workOrderManageDto);
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @GetMapping("/order/selectByNo")
    @ApiOperation(value = "查询事件隐患/所有工单")
    public AjaxMessage<Pagination<WorkOrderManageDto>> selectByNo(
            @ApiParam(value = "页数", required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "条数", required = true)@RequestParam Integer pageSize,
            @ApiParam(value = "单号", required = true) @RequestParam(required = true) String taskNo){
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        //根据用户编号，获取用户的权限
        workOrderManageDto.setTaskNo(taskNo);
        IPage<WorkOrderManageDto> iPage = new Page<>(pageNum, pageSize);
        iPage = workOrderManageService.selectByNo(iPage, workOrderManageDto);
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @GetMapping("/maintain/order")
    @ApiOperation(value = "维护列表/工单")
    public AjaxMessage<List<WorkOrderManageDto>> selectMaintainOrder(){
        //根据用户编号，获取用户的权限
        LoginUser loginUser = UserUtil.getCurrentUser();
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        workOrderManageDto.setTenantId(loginUser.getTenantId());
        workOrderManageDto.setProgramItems(loginUser.getProgramItemList());
        workOrderManageDto.setUserType(loginUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        workOrderManageDto.setPermissonType(loginUser.getPermissonType());
        List<WorkOrderManageDto> list = workOrderManageService.selectMaintainOrder(workOrderManageDto);
        for(WorkOrderManageDto dto : list){
            if(dto.getFlowDetail() != null){
              JSONObject jsonDetail = (JSONObject) JSONObject.parse(dto.getFlowDetail());
              if(jsonDetail.containsKey("预计完成时间")){
                  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  Date planFinishDate = null;
                  try {
                      planFinishDate = dateFormat.parse(jsonDetail.getString("预计完成时间"));
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
                  dto.setPlanFinishDate(planFinishDate);
              }
            }
        }
        setName(list);
        return new AjaxMessage<>(ResultStatus.OK, list);
    }

    @GetMapping("/maintain/user")
    @ApiOperation(value = "维护列表/人员")
    public AjaxMessage<List<Map<String,Object>>> selectMaintainUser(
            @ApiParam(value = "wkid", required = false) @RequestParam(required = false) String wkid,
            @ApiParam(value = "偏移量(x,y)", required = false) @RequestParam(required = false) String moveXY){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        AjaxMessage<List<UserEntity>> listAjaxMessage = userCenterClient.findUserListByType();
        for(UserEntity userEntity : listAjaxMessage.getData()){
            Map<String, Object> orderStatusMap = workOrderManageService.selectOrderUserStatus(userEntity.getId().toString());

            String orderStatus =  "空闲";
            Map<String, Object> map = new HashMap<>();
            map.put("id", userEntity.getId());
            map.put("userName", userEntity.getUsername());
            map.put("phone", userEntity.getPhone());
            map.put("deptName", userEntity.getDeptOrgName());
            if (orderStatusMap != null) {
                orderStatus = orderStatusMap.get("S").toString();
                if(orderStatus.equals("空闲")){
                    Map<String, Object> planStatusMap = workOrderManageService.selectPlanUserStatus(userEntity.getId().toString());
                    if(planStatusMap != null){
                        orderStatus =  planStatusMap.get("S").toString();
                    }
                }
                map.put("status", orderStatus);
            }
            else {
                Map<String, Object> planStatusMap = workOrderManageService.selectPlanUserStatus(userEntity.getId().toString());
                if(planStatusMap != null){
                    orderStatus =  planStatusMap.get("S").toString();
                }
                map.put("status",orderStatus);
            }
            Map<String, Object> onLineStatusMap = workOrderManageService.selectMaintainUserStatus(userEntity.getId().toString());
            if(onLineStatusMap != null) {
                if (!org.apache.commons.lang3.StringUtils.isEmpty(wkid)
                        && wkid.equals("2360")
                        && onLineStatusMap.get("X") != null
                        && onLineStatusMap.get("Y") != null) {
                    MyPoint myPoint = ConvertXY.ConvertXYToXian80(onLineStatusMap.get("X").toString(),
                            onLineStatusMap.get("Y").toString(), moveXY);
                    map.put("geo", String.format("[%s,%s]", myPoint.getX(), myPoint.getY()));
                } else if (!org.apache.commons.lang3.StringUtils.isEmpty(wkid)
                        && wkid.equals("3857")
                        && onLineStatusMap.get("X") != null
                        && onLineStatusMap.get("Y") != null) {
                    MyPoint myPoint = ConvertXY.ConvertXYToMercato(onLineStatusMap.get("X").toString(),
                            onLineStatusMap.get("Y").toString(), moveXY);
                    map.put("geo", String.format("[%s,%s]", myPoint.getX(), myPoint.getY()));
                } else if (onLineStatusMap.get("X") != null && onLineStatusMap.get("Y") != null) {
                    map.put("geo", String.format("[%s,%s]", onLineStatusMap.get("X"), onLineStatusMap.get("Y")));
                }
                map.put("online", onLineStatusMap.get("L").toString());
            }
            else{
                map.put("coords", null);
                map.put("online", "离线");
            }
            list.add(map);
        }
        return new AjaxMessage<>(ResultStatus.OK, list);
    }

    @GetMapping("/pending")
    @ApiOperation(value = "查询待处理工单")
    public AjaxMessage<Pagination<WorkOrderManageDto>> selectPendingOrder(
            @ApiParam(value = "页数", required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "条数", required = true)@RequestParam Integer pageSize,
            @ApiParam(value = "工单类型(1表务、2停通水、3抢修、4漏点定位、5测漏、6违章跑水)", required = false) @RequestParam(required = false) Integer orderTypeId,
            @ApiParam(value = "单号", required = false) @RequestParam(required = false) String taskNo,
            @ApiParam(value = "计划起始日期(yyyy-MM-dd)", required = false) @RequestParam(required = false) String startDate,
            @ApiParam(value = "计划截至日期(yyyy-MM-dd)", required = false) @RequestParam(required = false) String endDate){
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        //根据用户编号，获取用户的权限
        LoginUser loginUser = UserUtil.getCurrentUser();
        if(!StringUtils.isEmpty(startDate)&& !StringUtils.isEmpty(endDate)) {
            workOrderManageDto.setStartDate(startDate);
            workOrderManageDto.setEndDate(endDate);
        }
        workOrderManageDto.setTaskNo(taskNo);
        workOrderManageDto.setOrderTypeId(orderTypeId);
        workOrderManageDto.setOrderTypeId(orderTypeId);
        workOrderManageDto.setTenantId(loginUser.getTenantId());
        //workOrderManageDto.setProgramItems(loginUser.getProgramItemList());
        //workOrderManageDto.setUserType(loginUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        //workOrderManageDto.setPermissonType(loginUser.getPermissonType());
        if(loginUser.getId() != null) {
            workOrderManageDto.setCurrentUsers(String.format("%s", loginUser.getId()));
        }
        IPage<WorkOrderManageDto> iPage = new Page<>(pageNum, pageSize);
        iPage = workOrderManageService.selectPage(iPage, workOrderManageDto);
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @GetMapping("/select/children")
    @ApiOperation(value = "查询子单")
    public AjaxMessage<Pagination<WorkOrderManageDto>> selectSub(
            @ApiParam(value = "工单ID", required = false) @RequestParam(required = false) Integer id){
        WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
        workOrderManageDto.setOrderPid(id);
        IPage<WorkOrderManageDto> iPage = new Page<>(1, 100);
        iPage = workOrderManageService.selectPage(iPage, workOrderManageDto);
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @GetMapping("/resubmit")
    @ApiOperation(value = "重新派单")
    public AjaxMessage reSubmitOrder(
            @ApiParam(value = "工单ID", required = true) @RequestParam(required = true) Integer id,
            @ApiParam(value = "工单类型编号", required = true) @RequestParam(required = true) Integer orderTypeId,
            @ApiParam(value = "紧急程度", required = true) @RequestParam(required = true) String urgency,
            @ApiParam(value = "时限", required = true) @RequestParam(required = true) String dateLimit,
            @ApiParam(value = "接单人编号", required = true) @RequestParam(required = true) String orderUserId,
            @ApiParam(value = "父单ID", required = false) @RequestParam(required = false) String orderPid){
        LoginUser loginUser = UserUtil.getCurrentUser();
        WorkOrderManage workOrderManage = workOrderManageService.selectByPrimaryKey(id);
        if(workOrderManage == null){
            return new AjaxMessage(ResultStatus.ERROR,"工单ID错误！");
        }
        if(StringUtils.isEmpty(workOrderManage.getCurrentTaskId())){
            return new AjaxMessage(ResultStatus.ERROR,"任务ID错误！");
        }
        Map<String,String> dictMap=userCenterClient.selectListByPCodes("SC_WORK_ORDER_TYPE,SC_TASK_TYPE");
        //1表务、2停通水、3抢修、4漏点定位、5测漏、6违章跑水
        String orderType =dictMap.get(orderTypeId.toString());
        Map<String,Object> args=new HashMap<>();
        args.put("assineeFormUserId",orderUserId);
        args.put("工单类型",orderType);
        args.put("工单编号",workOrderManage.getTaskNo());
        args.put("url",String.format("?id=%s",workOrderManage.getId().toString()));
        workFlowService.stopProcessInstance(workOrderManage.getProcessInstanceId());
        ProcessDefinition processDefinition = workFlowService.findProcessDefinition(
                loginUser.getTenantId(),
                loginUser.getCompanyId(),
                orderTypeId);
        if(processDefinition == null){
            return new AjaxMessage(ResultStatus.ERROR,"没有创建流程，不能派单！");
        }
        args.put("templateId",7);
        args.put("msgType",7);
        String startProcess = workFlowService.startProcess(processDefinition,args);
        Task task = workFlowService.getProcessRuntimeTask(startProcess).get(0);
        Set<String> taskParticipator = workFlowService.getTaskParticipator(task.getId(),false,null);
        String currentUsers = "";
        for (String str : taskParticipator) {
            currentUsers += String.format("%s,",str);
        }
        workOrderManage.setProcessInstanceId(task.getProcessInstanceId());
        workOrderManage.setProcessDefId(task.getProcessDefinitionId());
        workOrderManage.setCurrentTaskId(task.getId());
        workOrderManage.setCurrentUsers(currentUsers);
        workOrderManage.setCurrentTaskName(task.getName());

        workOrderManage.setUpdateBy(loginUser.getId().toString());
        workOrderManage.setDateUpdate(new Date());
        workOrderManage.setOrderStatus(1);//已执行
        workOrderManage.setOrderTypeId(orderTypeId);//工单类型ID
        workOrderManage.setUrgency(urgency);//紧急程度
        workOrderManage.setOrderUserId(orderUserId);//接单人ID
        workOrderManage.setDateLimit(dateLimit);
        if(workOrderManage.getOrderPid() != null) {
            workOrderManage.setOrderPid(Integer.parseInt(orderPid));
        }
        if(loginUser.getId() != null) {
            workOrderManage.setUpdateBy(String.valueOf(loginUser.getId()));
            workOrderManage.setSendBy(String.valueOf(loginUser.getId()));//派单人
        }
        workOrderManage.setSendTime(new Date());// 派单时间
        workOrderManage.setDateUpdate(new Date());// 更新时间
        int rows = workOrderManageService.updateByPrimaryKey(workOrderManage);
        if(rows > 0){
            //记录日志
            WorkFlowLog workFlowLog=new WorkFlowLog();
            workFlowLog.setFlowId(id);
            workFlowLog.setFlowType(2);
            workFlowLog.setFlowResult("重新派单");
            workFlowLog.setCreateBy(loginUser.getId().toString());
            workFlowLog.setDateCreate(new Date());
            workFlowLog.setHandleUserId(loginUser.getId()!=null?loginUser.getId().toString():null);
            workFlowLog.setHandleUserName(loginUser.getUsername());
            workFlowLog.setProcessInstanceId(workOrderManage.getProcessInstanceId());
            workFlowLog.setTaskId(workOrderManage.getCurrentTaskId());
            workFlowLogService.insert(workFlowLog);
            return new AjaxMessage<>(ResultStatus.OK);
        }
        return new AjaxMessage<>(ResultStatus.ERROR);
    }

    @GetMapping("/submit")
    @ApiOperation(value = "派单")
    public AjaxMessage submitOrder(
            @ApiParam(value = "工单ID", required = true) @RequestParam(required = true) Integer id,
            @ApiParam(value = "工单类型编号", required = true) @RequestParam(required = true) Integer orderTypeId,
            @ApiParam(value = "工单类型名称", required = true) @RequestParam(required = true) String orderType,
            @ApiParam(value = "紧急程度", required = true) @RequestParam(required = true) String urgency,
            @ApiParam(value = "时限", required = true) @RequestParam(required = true) String dateLimit,
            @ApiParam(value = "接单人编号", required = true) @RequestParam(required = true) String orderUserId,
            @ApiParam(value = "父单ID", required = false) @RequestParam(required = false) String orderPid){
        LoginUser loginUser = UserUtil.getCurrentUser();
        WorkOrderManage workOrderManage = workOrderManageService.selectByPrimaryKey(id);
//        ProcessDefinition processDefinition = workFlowService.findProcessDefinition(
//                loginUser.getTenantId(),
//                loginUser.getCompanyId(),
//                planManage.getTaskType());
        //流程查询, 测试参数:(test1 1 1)
        ProcessDefinition processDefinition = workFlowService.findProcessDefinition(
                loginUser.getTenantId(),
                loginUser.getCompanyId(),
                orderTypeId);
        if(processDefinition == null){
           return new AjaxMessage(ResultStatus.ERROR,"没有创建流程，不能派单！");
        }
        Map<String,Object> vars = new HashMap<>();
        vars.put("assineeFormUserId",orderUserId);
        //巡检发送系统消息所需参数
        vars.put("工单类型",orderType);
        vars.put("工单编号",workOrderManage.getTaskNo());
        vars.put("url",String.format("?id=%s",workOrderManage.getId().toString()));
        vars.put("templateId",7);
        vars.put("msgType",7);
        String startProcess = workFlowService.startProcess(processDefinition,vars);
        Task task = workFlowService.getProcessRuntimeTask(startProcess).get(0);
        Set<String> taskParticipator = workFlowService.getTaskParticipator(task.getId(),false,null);
        String currentUsers = "";
        for (String str : taskParticipator) {
            currentUsers += String.format("%s,",str);
        }
        //更新计划表的流程相关字段值。
        workOrderManage.setOrderStatus(1);//已执行
        workOrderManage.setOrderTypeId(orderTypeId);//工单类型ID
        workOrderManage.setUrgency(urgency);//紧急程度
        workOrderManage.setOrderUserId(orderUserId);//接单人ID
        workOrderManage.setDateLimit(dateLimit);
        if(orderPid != null) {
            workOrderManage.setOrderPid(Integer.parseInt(orderPid));
        }
        if(loginUser.getId() != null) {
            workOrderManage.setUpdateBy(String.valueOf(loginUser.getId()));
            workOrderManage.setSendBy(String.valueOf(loginUser.getId()));//派单人
        }
        workOrderManage.setSendTime(new Date());// 派单时间
        workOrderManage.setDateUpdate(new Date());// 更新时间
        workOrderManage.setProcessInstanceId(task.getProcessInstanceId());
        workOrderManage.setProcessDefId(task.getProcessDefinitionId());
        workOrderManage.setCurrentTaskId(task.getId());
        workOrderManage.setCurrentUsers(currentUsers);
        workOrderManage.setCurrentTaskName(task.getName());
        int rows = workOrderManageService.updateByPrimaryKeySelective(workOrderManage);
        if(rows > 0) {
            //记录日志
            WorkFlowLog workFlowLog=new WorkFlowLog();
            workFlowLog.setFlowId(id);
            workFlowLog.setFlowType(2);
            workFlowLog.setFlowResult("开始派单【启动流程】");
            workFlowLog.setCreateBy(loginUser.getId().toString());
            workFlowLog.setDateCreate(new Date());
            workFlowLog.setHandleUserId(loginUser.getId()!=null?loginUser.getId().toString():null);
            workFlowLog.setHandleUserName(loginUser.getUsername());
            workFlowLog.setProcessInstanceId(workOrderManage.getProcessInstanceId());
            workFlowLog.setTaskId(workOrderManage.getCurrentTaskId());
            workFlowLogService.insert(workFlowLog);
            return new AjaxMessage<>(ResultStatus.OK);
        }
        return new AjaxMessage<>(ResultStatus.ERROR);
    }

    @GetMapping("/selectOrderUserByOrgId")
    @ApiOperation(value = "查询派单时的用户信息")
    public AjaxMessage<Object> selectOrderUserByOrgId(
            @ApiParam(value = "机构ID", required = true) @RequestParam(required = true) String ids,
            @ApiParam(value = "wkid", required = false) @RequestParam(required = false) String wkid,
            @ApiParam(value = "偏移量(x,y)", required = false) @RequestParam(required = false) String moveXY){
        List<Map<String,Object>> result = new ArrayList<>();
        AjaxMessage<List<UserEntity>> listAjaxMessage = userCenterClient.findUserIdsByOrgIdAndType(String.format("[%s]",ids));
        for(UserEntity userEntity : listAjaxMessage.getData()){
            try {
                Map<String, Object> orderStatusMap = workOrderManageService.selectOrderUserStatus(userEntity.getId().toString());
                Map<String, Object> map = new HashMap<>();
                map.put("id", userEntity.getId());
                map.put("userName", userEntity.getUsername());
                map.put("phone", userEntity.getPhone());
                map.put("deptName", userEntity.getDeptOrgName());
                if (orderStatusMap != null) {
                    map.put("status", orderStatusMap.get("S").toString());
                    String X = orderStatusMap.get("X")==null?"-":orderStatusMap.get("X").toString();
                    String Y = orderStatusMap.get("Y")==null?"-":orderStatusMap.get("Y").toString();
                    map.put("address",String.format("%s,%s",X,Y));
                    if(!org.apache.commons.lang3.StringUtils.isEmpty(wkid)
                            && wkid.equals("2360")
                            && orderStatusMap.get("X")!=null
                            && orderStatusMap.get("Y")!=null){
                        MyPoint myPoint= ConvertXY.ConvertXYToXian80(orderStatusMap.get("X").toString(),
                                orderStatusMap.get("Y").toString(),moveXY);
                        map.put("coords",myPoint.getX()+","+myPoint.getY());
                    }else if(!org.apache.commons.lang3.StringUtils.isEmpty(wkid)
                            && wkid.equals("3857")
                            && orderStatusMap.get("X")!=null
                            && orderStatusMap.get("Y")!=null){
                        MyPoint myPoint= ConvertXY.ConvertXYToMercato(orderStatusMap.get("X").toString(),
                                orderStatusMap.get("Y").toString(),moveXY);
                        map.put("coords",myPoint.getX()+","+myPoint.getY());
                    }else
                    {
                        map.put("coords","");
                    }
                }
                else {
                    map.put("status", "");
                    map.put("address", "");
                    map.put("coords","");
                }
                map.put("distance", "");
                result.add(map);
            }catch (Exception e){

            }
        }
        return new AjaxMessage<>(ResultStatus.OK,result);
    }

    @GetMapping("/delProcInst")
    @ApiOperation(value = "终止流程")
    public AjaxMessage deleteProcessInstance(
            @ApiParam(value = "任务ID", required = true) @RequestParam(required = true) Integer id,
            @ApiParam(value = "流程ID", required = true) @RequestParam(required = true) String processInstanceId,
            @ApiParam(value = "流程备注", required = false) @RequestParam(required = false) String remark) {
        workFlowService.stopProcessInstance(processInstanceId);
        WorkOrderManage workOrderManage = new WorkOrderManage();
        workOrderManage.setId(id);
        workOrderManage.setOrderStatus(3);//工单终止状态
        workOrderManage.setCurrentUsers("");
        workOrderManage.setFinishDate(new Date());
        workOrderManageService.updateByPrimaryKeySelective(workOrderManage);
        LoginUser currentUser = UserUtil.getCurrentUser();
        WorkFlowLog workFlowLog=new WorkFlowLog();
        workFlowLog.setFlowId(id);
        workFlowLog.setFlowType(2);
        workFlowLog.setFlowResult(remark);
        workFlowLog.setCreateBy(currentUser.getId()!=null?currentUser.getId().toString():null);
        workFlowLog.setDateCreate(new Date());
        workFlowLog.setHandleUserId(currentUser.getId()!=null?currentUser.getId().toString():null);
        workFlowLog.setHandleUserName(currentUser.getUsername());
        //记录日志
        workFlowLogService.insert(workFlowLog);
        return new AjaxMessage<>(ResultStatus.OK);
    }

    @RequestMapping(value="batchDelete" , method = RequestMethod.DELETE)
    @ApiOperation(value = "批量删除")
    public AjaxMessage<Integer> batchDelete( @ApiParam(value = "工单Ids") @RequestParam List<Integer> ids){
        return new AjaxMessage<>(ResultStatus.OK, workOrderManageService.batchDelete(ids));
    }

    /**
     * 批量插入工单信息（报警生成的）
     */
    @RequestMapping(value = "saveByAlarms", method = RequestMethod.POST)
    @ApiOperation(value = "批量插入工单信息（报警生成的）")
    public Integer saveByAlarms(
            @ApiParam(value = "工单信息", required = true) @RequestBody List<WorkOrderManageByAlarmDto> workOrderManages){
        return workOrderManageService.batchInsertByAlarms(workOrderManages);
    }

    @RequestMapping(value = "findWorkOrderByDeviceIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据设备id查询工单信息（报警）")
    public List<WorkOrderManageByAlarmDto> findWorkOrderByDeviceIds(
            @ApiParam(value = "设备id", required = true) @RequestParam List<Long> deviceIds){
        return workOrderManageService.findWorkOrderByDeviceIds(deviceIds);
    }

    @RequestMapping(value = "updateByAlarms", method = RequestMethod.POST)
    @ApiOperation(value = "修改工单信息（报警生成的）")
    public void updateByAlarms(
            @ApiParam(value = "工单信息", required = true) @RequestBody List<WorkOrderManageByAlarmDto> workOrderManages){
            workOrderManageService.updateByAlarms(workOrderManages);
    }

    /**
     * 报警恢复时，删除未派单的工单
     */
    @RequestMapping(value = "batchDeleteByAlarms", method = RequestMethod.POST)
    @ApiOperation(value = "报警恢复时，删除未派单的工单")
    public Integer batchDeleteByAlarms(
            @ApiParam(value = "设备id", required = true) @RequestParam List<Long> deviceIds){

        return workOrderManageService.batchDeleteByAlarms(deviceIds);
    }

    @GetMapping("/selectOrderPower")
    @ApiOperation(value = "获取工单派单权限")
    public  AjaxMessage<Map<String,Object>> selectOrderPower(
            @ApiParam(value = "工单ID", required = true) @RequestParam(required = true) Integer id){
        Map<String,Object> result = new HashMap<String,Object>();
        WorkOrderManage workOrderManage = workOrderManageService.selectByPrimaryKey(id);
        //抢修工单,可以派漏点定位和停水工单
        if(workOrderManage.getOrderTypeId() == 3 && workOrderManage.getOrderStatus() == 1){
            result.put("2","true");
            result.put("4","true");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("orderPid",workOrderManage.getId());
            List<WorkOrderManage> workOrderManageList = workOrderManageService.selectByPId(map);
            for(WorkOrderManage wom: workOrderManageList){
                if (wom.getOrderStatus() == 0 || wom.getOrderStatus() == 1){
                    if(wom.getOrderTypeId()==2 ){
                        result.put("2","false");
                    }
                    else if(wom.getOrderTypeId()==4){
                        result.put("4","false");
                    }
                }
            }
        }
        return new AjaxMessage<>(ResultStatus.OK,result);
    }


    @GetMapping("/pending/power")
    @ApiOperation(value = "待处理权限")
    public AjaxMessage<Boolean> selectPendingPower(
            @ApiParam(value = "工单ID", required = true) @RequestParam(required = true) Integer id){
        String currentUsers = null;
        LoginUser loginUser = UserUtil.getCurrentUser();
        if(loginUser.getId() != null) {
            currentUsers = String.format("%s", loginUser.getId());
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",id);
        map.put("currentUsers",currentUsers);
        int rows = workOrderManageService.selectPendingPower(map);
        if(rows>0){
            return new AjaxMessage<Boolean>(ResultStatus.OK, true);
        }
        return new AjaxMessage<Boolean>(ResultStatus.OK, false);
    }
    /**
     * 获取并设置用户、任务工单类型名称
     * @param result
     */
    private void setName(List<WorkOrderManageDto> result){
        if(result.size()>0){
            try{
                List<Long> idList = new ArrayList<Long>();
                for(WorkOrderManageDto workOrder:result) {
                    try {
                        if (workOrder.getSendBy() != null) {
                            idList.add(Long.valueOf(workOrder.getSendBy()));
                        }
                        if (workOrder.getOrderUserId() != null) {
                            idList.add(Long.valueOf(workOrder.getOrderUserId()));
                        }
                        if (workOrder.getCreateBy() != null) {
                            idList.add(Long.valueOf(workOrder.getCreateBy()));
                        }
                        if (workOrder.getUpdateBy() != null) {
                            idList.add(Long.valueOf(workOrder.getUpdateBy()));
                        }
                        if (workOrder.getCurrentUsers() != null) {
                            String[] currentUserIds = workOrder.getCurrentUsers().split(",");
                            for (String currentUserId : currentUserIds) {
                                if (!StringUtils.isEmpty(currentUserId)) {
                                    idList.add(Long.valueOf(currentUserId));
                                }
                            }
                        }
                    }catch (Exception e){

                    }
                }
                Long[] ids = idList.toArray(new Long[0]);
                List<UserEntity> userEntityList=userCenterClient.findUserIdsByUserIds(ids);
                Map<Long,String> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getUsername));
                Map<Long,String> userPhoneMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getPhone));
                Map<String,String> dictMap=userCenterClient.selectListByPCodes("SC_WORK_ORDER_TYPE,SC_TASK_TYPE");
                for(int i = 0; i < result.size(); i++) {
                    WorkOrderManageDto workOrder = result.get(i);
                    try {
                        if (workOrder.getOrderTypeId() != null) {
                            workOrder.setTypeName(dictMap.get(workOrder.getOrderTypeId().toString()));
                        }
                        if (workOrder.getSendBy() != null) {
                            workOrder.setSendByName(userMap.get(Long.valueOf(workOrder.getSendBy())));
                        }
                        if (workOrder.getOrderUserId() != null) {
                            workOrder.setOrderUserName(userMap.get(Long.valueOf(workOrder.getOrderUserId())));
                            workOrder.setOrderUserPhone(userPhoneMap.get(Long.valueOf(workOrder.getOrderUserId())));
                        }
                        if (workOrder.getCreateBy() != null) {
                            workOrder.setCreateByName(userMap.get(Long.valueOf(workOrder.getCreateBy())));
                            workOrder.setCreateUserPhone(userPhoneMap.get(Long.valueOf(workOrder.getCreateBy())));
                        }
                        if (workOrder.getUpdateBy() != null) {
                            workOrder.setUpdateByName(userMap.get(Long.valueOf(workOrder.getUpdateBy())));
                        }
                        if (workOrder.getWorkFlowDetail() != null) {
                            WorkFlowDetail workFlowDetail = workOrder.getWorkFlowDetail();
                            if (workFlowDetail.getCreateBy() != null) {
                                workFlowDetail.setCreateByName(userMap.get(Long.valueOf(workFlowDetail.getCreateBy())));
                            }
                            if (workFlowDetail.getUpdateBy() != null) {
                                workFlowDetail.setUpdateByName(userMap.get(Long.valueOf(workFlowDetail.getUpdateBy())));
                            }
                        }
                        if (workOrder.getWorkFlowLogList() != null) {
                            for (WorkFlowLog workFlowLog : workOrder.getWorkFlowLogList()) {
                                try {
                                    if (workFlowLog.getCreateBy() != null) {
                                        workFlowLog.setCreateByName(userMap.get(Long.valueOf(workFlowLog.getCreateBy())));
                                    }
                                    if (workFlowLog.getUpdateBy() != null) {
                                        workFlowLog.setUpdateByName(userMap.get(Long.valueOf(workFlowLog.getUpdateBy())));
                                    }
                                }catch (Exception e){

                                }
                            }
                        }
                        String currentUsersName = null;
                        if(workOrder.getCurrentUsers() != null) {
                            String[] currentUserIds = workOrder.getCurrentUsers().split(",");
                            for (String currentUserId : currentUserIds) {
                                if(!currentUserId.equals("")) {
                                    if (currentUsersName == null) {
                                        currentUsersName = userMap.get(Long.valueOf(currentUserId));
                                    } else {
                                        currentUsersName = currentUsersName + "," + userMap.get(Long.valueOf(currentUserId));
                                    }
                                }
                            }
                        }
                        workOrder.setCurrentUsersName(currentUsersName);
                    }catch (Exception e){

                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 综合展示/App-查询工单执行情况
     * @return Response对象
     */
    @RequestMapping(value = "selectOrderStatus", method = RequestMethod.GET)
    @ApiOperation(value = "综合展示/App-查询工单执行情况")
    public AjaxMessage<List<WorkOrderManageDto>> selectOrderStatus(
            @ApiParam(value = "公司机构id", required = false)@RequestParam(required = false) Integer companyOrgId,
            @ApiParam(value = "0或null本月、1本年、2近一年", required = false)@RequestParam(required = false) Integer statsType) {
        WorkOrderManageDto workOrderManageDto=new WorkOrderManageDto();
        workOrderManageDto.setCompanyOrgId(companyOrgId!=null?companyOrgId.toString():null);
        workOrderManageDto.setStatsType(statsType);

        LoginUser loginUser = UserUtil.getCurrentUser();
        workOrderManageDto.setTenantId(loginUser.getTenantId());
        workOrderManageDto.setProgramItems(loginUser.getProgramItemList());
        workOrderManageDto.setUserType(loginUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        workOrderManageDto.setPermissonType(loginUser.getPermissonType());
        List<WorkOrderManageDto> result=workOrderManageService.selectOrderStatus(workOrderManageDto);
        return new AjaxMessage<>(ResultStatus.OK, result );
    }


    /**
     * APP运维管理全部查询
     * @return Response对象
     */
    @ApiOperation(value = "APP运维管理全部查询")
    @RequestMapping(value = "findWorkOrderPage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage<Pagination<WorkOrderManageDto>> findWorkOrderPage(@RequestBody @Valid WorkOrderEvaluationDto dto) {
        IPage<WorkOrderManageDto> iPage = new Page<>(dto.getPageNum(), dto.getPageSize());
        iPage = workOrderManageService.selectByTime(iPage,  dto.getTenantId(), dto.getUserId(), dto.getStartTime(), dto.getEndTime());
        Pagination<WorkOrderManageDto> pages = new Pagination<>(iPage);
        setName(pages.getList());
        if (CollectionUtil.isEmpty(pages.getList())) {
            return new AjaxMessage<>(ResultStatus.OK, pages);
        }
        /**
         *任务：  开始时间：date_create  计划完成时间：plan_end_date  + " 23:59:59"  完成时间：finish_date
         *工单：  开始时间：date_create  计划完成时间：send_time + date_limit分钟     完成时间：finish_date
         */
        Date planFinishDate = null;
        for (WorkOrderManageDto workOrderManageDto : pages.getList()) {
            if (EvaluationUtil.isWork(workOrderManageDto.getOrderTypeId())) {
                planFinishDate = DatesUtil.addMinuteOfDate(workOrderManageDto.getSendTime(), EvaluationUtil.minute(workOrderManageDto.getDateLimit()));
            } else {
                if (workOrderManageDto.getPlanFinishDate() != null) {
                    planFinishDate = DatesUtil.parseDate(DatesUtil.formatDate(workOrderManageDto.getPlanFinishDate(), "yyyy-MM-dd") + " 23:59:59",
                            "yyyy-MM-dd HH:mm:ss");
                }
            }
            workOrderManageDto.setPlanFinishDate(planFinishDate);
            workOrderManageDto.setOrderStatusName(EvaluationUtil.getOrderStatusName(workOrderManageDto.getOrderStatus()));
        }
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value = "findWorkFlowById", method = RequestMethod.GET)
    @ApiOperation(value = "查询工单工作流")
    public AjaxMessage<WorkOrderManageDto> findWorkFlowById(
            @ApiParam(value = "工单id", required = true) @RequestParam Integer flowId) {
        WorkOrderManageDto result= workOrderManageService.findWorkFlowById(flowId);
        List<WorkOrderManageDto> list = new ArrayList<>();
        if (result != null) {
            list.add(result);
            setName(list);
        }
        return new AjaxMessage<>(ResultStatus.OK,  result);
    }
}




