package com.ho.flow.controller.process;

import cn.hutool.core.date.DateUtil;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import com.ho.business.entity.Station;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.common.tools.annotation.HzPermission;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.PermissionConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.OrderForm;
import com.ho.common.tools.entity.ProcessOrder;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.entity.file.OrderFile;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import com.ho.flow.entity.process.MovementDTO;
import com.ho.flow.entity.process.PreDoUser;
import com.ho.flow.entity.process.TaskOrderInfo;
import com.ho.flow.feignclient.BusinessFeignClient;
import com.ho.flow.feignclient.UserFeignClient;
import com.ho.flow.mapper.EventMapper;
import com.ho.flow.monitor.EventToProcessMonitor;
import com.ho.flow.service.ProcessFlowService;
import com.ho.flow.service.process.service.ProcessFlowNewService;
import com.ho.flow.util.PDFutil;
import com.ho.flow.vo.Event;
import com.ho.flow.vo.req.workorder.*;
import com.ho.flow.vo.resp.workorder.*;
import com.ho.user.api.entity.SysUser;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author yule
 * @Date 2023/8/29 10:41
 * @desc ${}
 */
@RequestMapping(ContextConstant.FLOW_CONTEXT + "processFlowNew")
@RestController
@Api(tags = "工单模块")
public class ProcessFlowNewController {

    @Autowired
    ProcessFlowNewService processFlowNewService;

    @Autowired
    ProcessFlowService processFlowService;

    @Autowired
    RedisService redisService;


    @PostMapping("deployment")
    @ApiOperation(value = "部署")
    public DataResult<String> deployment(@RequestBody @Valid ProcessOrder processOrder, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        processOrder.setUserId(simpleUser.getUserId());
        return DataResult.success(processFlowNewService.deployment(processOrder));
    }

    @PostMapping("initProcessInstance")
    @ApiOperation(value = "发起工单")
    public DataResult initProcessInstance(@RequestBody @Valid ProcessOrder processOrder, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        processOrder.setTenantId(String.valueOf(simpleUser.getGroupId()));
        processOrder.setUserId(simpleUser.getUserId());
        processFlowNewService.initProcessInstance(processOrder);
        return DataResult.success();
    }

    @PostMapping("preForward")
    @ApiOperation(value = "转发前选择候选人")
    public DataResult<List<PreDoUser>> preForward(HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        simpleUser.setTenantId(String.valueOf(simpleUser.getGroupId()));
        return DataResult.success(processFlowNewService.preForward(simpleUser));
    }

    @PostMapping("forward")
    @ApiOperation(value = "转发")
    public DataResult forward(@RequestBody @Valid TaskDone taskDone, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        simpleUser.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskDone.setSender(simpleUser.getUserId());
        processFlowNewService.forward(taskDone);
        return DataResult.success();
    }

    @PostMapping("queryTodoList")
    @ApiOperation(value = "查询代办列表")
    public DataResult<List<TaskDone>> queryTodoList(@RequestBody(required = false) @Valid DoListTaskReq doListTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        simpleUser.setTenantId(String.valueOf(simpleUser.getGroupId()));
        doListTaskReq.setUserId(simpleUser.getUserId());
        Map<String, List<Task>> taskMap = processFlowNewService.getTodoList(simpleUser);
        List<TaskDone> todoList = new ArrayList<>();
        //代办不分页,转换为TaskDone对象
        if (!taskMap.isEmpty()) {
            todoList = processFlowNewService.getToDoListFromTask(taskMap, doListTaskReq);
        }
        if (!todoList.isEmpty()) {
            //根据优先级排序然后根据时间和条件进行过滤
            todoList = todoList.stream().filter(s -> {
                boolean flag = true;
                String title = doListTaskReq.getTitle();
                if (!StringUtils.isEmpty(title)) {
                    if (!StringUtils.isEmpty(s.getTitle()) && !s.getTitle().contains(title)) {
                        flag = false;
                    }
                }
                Integer stationId = doListTaskReq.getStationId();
                if (stationId != null) {
                    if (s.getStationId() != null && !stationId.equals(s.getStationId())) {
                        flag = false;
                    }
                }
                return flag;
            }).sorted(
                    Comparator.comparing(TaskDone::getPriority, Comparator.nullsLast(String::compareTo)).reversed().
                            thenComparing(TaskDone::getStartTime, Comparator.nullsLast(Date::compareTo)).reversed()
            ).collect(Collectors.toList());
        }
        return DataResult.success(todoList);
    }


    @PostMapping("queryTodoCount")
    @ApiOperation(value = "查询代办数量")
    public DataResult<Integer> queryTodoCount(@RequestBody(required = false) @Valid DoListTaskReq doListTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        simpleUser.setTenantId(String.valueOf(simpleUser.getGroupId()));
        if (doListTaskReq == null) {
            doListTaskReq = new DoListTaskReq();
            doListTaskReq.setUserId(simpleUser.getUserId());
        }
        Map<String, List<Task>> taskMap = processFlowNewService.getTodoList(simpleUser);
        List<TaskDone> todoList = new ArrayList<>();
        //代办不分页,转换为TaskDone对象
        if (!taskMap.isEmpty()) {
            todoList = processFlowNewService.getToDoListFromTask(taskMap, doListTaskReq);
            return DataResult.success(todoList.size());
        }else {
            return DataResult.success(0);
        }
    }

    @PostMapping("queryDoneList")
    @ApiOperation(value = "查询已办列表")
    public DataResult<PageResult<TaskDone>> queryDoneList(@RequestBody @Valid DoListTaskReq doListTaskReq, HttpServletRequest request) {
        Date date = new Date();
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        simpleUser.setTenantId(String.valueOf(simpleUser.getGroupId()));
        doListTaskReq.setUserId(simpleUser.getUserId());
        List<HistoricTaskInstance> taskList = processFlowNewService.getDoneList(simpleUser);
        List<TaskDone> doneList = new ArrayList<>();
        doneList = processFlowNewService.getDoneListFromTask(taskList, doListTaskReq);
        doneList = doneList.stream().filter(s -> {
            boolean flag = true;
            String title = doListTaskReq.getTitle();
            if (!StringUtils.isEmpty(title)) {
                if (!StringUtils.isEmpty(s.getTitle()) && !s.getTitle().contains(title)) {
                    flag = false;
                }
            }
            Integer stationId = doListTaskReq.getStationId();
            if (stationId != null) {
                if (s.getStationId() != null && !stationId.equals(s.getStationId())) {
                    flag = false;
                }
            }
            return flag;
        }).sorted(
                //根据时间倒序排序
                Comparator.comparing(TaskDone::getStartTime).reversed()
        ).collect(Collectors.toList());
        if (!doneList.isEmpty()) {
            //获取到代办任务
            DataResult<List<TaskDone>> listDataResult = queryTodoList(doListTaskReq, request);
            //代办的任务
            List<TaskDone> todoList = listDataResult.getData();
            todoList = todoList.stream().filter(s->{
                if (s.getProcessInstanceId() != null){
                    return true;
                }else {
                    return false;
                }
            }).collect(Collectors.toList());
            Map<String, List<TaskDone>> todoMap = todoList.stream().collect(Collectors.groupingBy(TaskDone::getProcessInstanceId));
            //移除在代办任务中存在的任务对象
            doneList.removeIf(s -> {
                boolean flag = false;
                if (todoMap.get(s.getProcessInstanceId()) != null) {
                    flag = true;
                }
                return flag;
            });
        }
        PageResult pageResult = new PageResult<>();
        if (!doneList.isEmpty()) {
            List list = PageUtils.dealList(doneList, doListTaskReq.getPageNum(), doListTaskReq.getPageSize());
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(doneList.size());
            pageResult.setPageSize(doListTaskReq.getPageSize());
            pageResult.setTotalPages(doneList.size() / doListTaskReq.getPageSize() + 1);
        }
        return DataResult.success(pageResult);
    }

    @PostMapping("queryInspectionList")
    @ApiOperation(value = "查询巡检任务列表")
    public DataResult<List<TaskDone>> queryInspectionList(@RequestBody(required = false) @Valid DoListTaskReq doListTaskReq, HttpServletRequest request) {
        DataResult result = new DataResult();
        //查询巡检相关的工单号列表
        List<OrderForm> orderFormList = processFlowNewService.getInspectionOrders(doListTaskReq.getStationId());
        //未发起流程的工单id集合
        List<Integer> orderFormId = orderFormList.stream().filter(e ->e.getProcessInstanceId() == null&& e.getStatus() == 0).map(OrderForm::getId).collect(Collectors.toList());
        //已发起工单的流程实例id集合
        List<String> processInstanceId = orderFormList.stream().filter(e ->e.getProcessInstanceId() != null&& e.getStatus() == 1).map(OrderForm::getProcessInstanceId).collect(Collectors.toList());
        List<TaskDone> totalTask = new ArrayList<>();
        DataResult<List<TaskDone>> toDoList = queryTodoList(doListTaskReq,request);
//        DataResult<PageResult<TaskDone>> doneList = queryDoneList(doListTaskReq,request);
        totalTask.addAll(toDoList.getData());
//        totalTask.addAll(doneList.getData().getList());
        //筛选巡检相关的待办工单（未发起流程的工单比较id，发起流程的工单比较processInstanceId）
        totalTask = totalTask.stream().filter(e ->
                        (orderFormId.size()>0 && orderFormId.contains(e.getId()))||(processInstanceId.size()>0 && processInstanceId.contains(e.getProcessInstanceId())))
                .collect(Collectors.toList());
        result.setData(totalTask);
        return result;
    }



    @PostMapping("preDo")
    @ApiOperation(value = "流转前的方法")
    public DataResult<List<PreDoUser>> preDo(@RequestBody @Valid TaskUserReq taskUserReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        taskUserReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskUserReq.setUserId(simpleUser.getUserId());
        taskUserReq.setDeptId(String.valueOf(simpleUser.getDeptId()));
        List<PreDoUser> users = new ArrayList<>();
        if (taskUserReq.getProcessInstId() != null) {
            users = processFlowNewService.getPreDo(taskUserReq);
        } else {
            users = processFlowNewService.getFristPreDo(taskUserReq);
        }
        return DataResult.success(users);
    }

    @PostMapping("approval")
    @ApiOperation(value = "审批通过(流转)")
    public DataResult approval(@RequestBody @Valid DoTaskReq doTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置发送者的id
        doTaskReq.setSenderId(simpleUser.getUserId());
        //设置租户id
        doTaskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        //完成任务的责任人必须和自己相同,否则需要给出提示
        doTaskReq.setAssigneeUser(simpleUser.getUserId());
        if (doTaskReq.getProcessInstId() != null) {
            processFlowNewService.approval(doTaskReq);
        } else {
            processFlowNewService.getFristApproval(doTaskReq);
        }

        return DataResult.success();
    }

    @PostMapping("approvalFailed")
    @ApiOperation(value = "审批不通过")
    public DataResult approvalFailed(@RequestBody @Valid DoTaskReq doTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置发送者的id
        doTaskReq.setSenderId(simpleUser.getUserId());
        //设置租户id
        doTaskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        //完成任务的责任人必须和自己相同,否则需要给出提示
        doTaskReq.setAssigneeUser(simpleUser.getUserId());
        processFlowNewService.approvalFailed(doTaskReq);
        return DataResult.success();
    }


    @PostMapping("fallBackTaskList")
    @ApiOperation(value = "回退任务列表")
    public DataResult<List<FallBackTaskResp>> fallBackTask(@RequestBody FallBackTaskReq fallBackTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        fallBackTaskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        List<FallBackTaskResp> fallBackTaskResps = new ArrayList<>();
        if (fallBackTaskReq.getProcessInstId() != null) {
            fallBackTaskResps = processFlowNewService.getFallBackTask(fallBackTaskReq);
        }
        return DataResult.success(fallBackTaskResps);
    }

    @PostMapping("fallBackTask")
    @ApiOperation(value = "回退任务")
    public DataResult rejectTask(@RequestBody RejectTaskReq rejectTaskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置发送人
        rejectTaskReq.setUserId(simpleUser.getUserId());
        //设置租户id
        rejectTaskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        processFlowNewService.fallBackTask(rejectTaskReq);
        return DataResult.success();
    }

    @PostMapping("detailsTask")
    @ApiOperation(value = "工单详情")
    public DataResult<List<HisTaskResp>> detailsTask(@RequestBody CirculationTaskReq taskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setAssigneeUser(simpleUser.getUserId());
        List<HisTaskResp> hisTaskRespList = new ArrayList<>();
        if (taskReq.getProcessInstId() != null) {
            hisTaskRespList = processFlowNewService.detailsTask(taskReq);
        } else {
            hisTaskRespList = processFlowNewService.detailsFirstTask(taskReq);
        }
        return DataResult.success(hisTaskRespList);
    }

    @PostMapping("taskInfo")
    @ApiOperation(value = "任务详情")
    public DataResult<TaskOrderInfo> taskInfo(@RequestBody CirculationTaskReq taskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setAssigneeUser(simpleUser.getUserId());
        TaskOrderInfo taskOrderInfo = new TaskOrderInfo();
        if (taskReq.getProcessInstId() != null) {
            taskOrderInfo = processFlowNewService.taskInfo(taskReq);
        } else {
            taskOrderInfo = processFlowNewService.firstTaskInfo(taskReq);
        }
        return DataResult.success(taskOrderInfo);
    }

    @PostMapping("claimTask")
    @ApiOperation(value = "接收任务")
    public DataResult claimTask(@RequestBody @Valid TaskUserReq taskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setUserId(simpleUser.getUserId());
        processFlowNewService.doClaimTask(taskReq);
        //代办应该分页,做个java内存分页处理
        return DataResult.success();
    }

    @PostMapping("save")
    @ApiOperation(value = "保存")
    public DataResult save(@RequestBody @Valid TaskUserReq taskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setUserId(simpleUser.getUserId());
        if (taskReq.getProcessInstId() != null) {
            processFlowNewService.save(taskReq);
        } else {
            processFlowNewService.saveOrderForm(taskReq);
        }
        //代办应该分页,做个java内存分页处理
        return DataResult.success();
    }

    @PostMapping("cancel")
    @ApiOperation(value = "作废")
    public DataResult cancel(@RequestBody @Valid TaskUserReq taskReq, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        //设置租户id
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setUserId(simpleUser.getUserId());
        processFlowNewService.cancel(taskReq);
        //代办应该分页,做个java内存分页处理
        return DataResult.success();
    }

    @Autowired
    PDFutil pdFutil;

    @PostMapping("exportPDF")
    @ApiOperation(value = "导出PDF")
    public void exportPDF(@RequestBody CirculationTaskReq taskReq, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        taskReq.setTenantId(String.valueOf(simpleUser.getGroupId()));
        taskReq.setAssigneeUser(simpleUser.getUserId());
        List<List<HisTaskResp>> list = new ArrayList<>();

        if (!taskReq.getProcessInstIds().isEmpty()) {
            for (String processInstId : taskReq.getProcessInstIds()) {
                taskReq.setProcessInstId(processInstId);
                List<HisTaskResp> hisTaskRespList = new ArrayList<>();
                if (taskReq.getProcessInstId() != null) {
                    hisTaskRespList = processFlowNewService.detailsTask(taskReq);
                } else {
                    hisTaskRespList = processFlowNewService.detailsFirstTask(taskReq);
                }
                list.add(hisTaskRespList);
            }
        }
        // 设置页面编码格式
        String pdfName = "流程跟踪";
        try {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((pdfName).getBytes(), "ISO-8859-1") + ".pdf");
            // 1).定义A4纸
            Document document = new Document(PageSize.A4, 48, 48, 60, 65);
            // 2).建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中
            // 3).写入数据之前要打开文档
            ServletOutputStream os = response.getOutputStream();
            PdfWriter contentWriter = PdfWriter.getInstance(document, os);
            document.open();
            for (List<HisTaskResp> hisTaskRespList : list) {
                //创建需要导出的对象并赋值
                WorkOrderPDF workOrderPDF = new WorkOrderPDF();
                List<WorkOrderPDFText> workOrderPDFTexts = new ArrayList<>();
                int maxFileNum = getWorkOrderPDF(hisTaskRespList, workOrderPDF, workOrderPDFTexts);

                //添加中文字体
                BaseFont bfCN = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                // 正文的字体
                Font titleFont = new Font(bfCN, 12f);
                Font textFont = new Font(bfCN, 10f);
                Font fileFont = new Font(bfCN, 10f);
                fileFont.setColor(BaseColor.BLUE);
                // 创建表格
                PdfPTable table = new PdfPTable(4);
                // 设置表格宽度百分比
                table.setWidthPercentage(100);
                float[] columnWidths = {0.5f, 0.5f, 0.5f, 0.5f};
                table.setWidths(columnWidths);
                setTitlePDF(titleFont, textFont, table, workOrderPDF);
                //电站数据表
                PdfPTable stationTable = new PdfPTable(4);
                stationTable.setWidthPercentage(100);
                stationTable.setWidths(columnWidths);
                setStationPDF(titleFont, textFont, stationTable, workOrderPDF);
                // 创建表格
                PdfPTable tableText = new PdfPTable(4 + maxFileNum);
                // 设置表格宽度百分比
                tableText.setWidthPercentage(100);
                // 设置表格列宽度
                float[] textColumnWidths = new float[4 + maxFileNum];
                textColumnWidths[0] = 1.5f;
                textColumnWidths[1] = 0.8f;
                textColumnWidths[2] = 1.8f;
                textColumnWidths[3] = 1.8f;
                for (int i = 0; i < maxFileNum; i++) {
                    textColumnWidths[4 + i] = 2.0f;
                }
                tableText.setWidths(textColumnWidths);
                //添加流程跟踪数据
                setPDFText(workOrderPDFTexts, maxFileNum, titleFont, textFont,fileFont, tableText);
                document.add(table);
                document.add(stationTable);
                document.add(tableText);
                document.newPage();
            }

            document.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setStationPDF(Font titleFont, Font textFont, PdfPTable table, WorkOrderPDF workOrderPDF) {
        String string = "";

        //第一行
        pdFutil.cellFillChar(table, "电站", textFont);
        if (workOrderPDF.getStationName() != null) {
            string = workOrderPDF.getStationName();
        }
        pdFutil.cellFillChar(table, string, textFont);

        string = "";
        pdFutil.cellFillChar(table, "设备", textFont);
        if (workOrderPDF.getDeviceName() != null) {
            string = workOrderPDF.getDeviceName();
        }
        pdFutil.cellFillChar(table, string, textFont);

        //第二行
        string = "";
        pdFutil.cellFillChar(table, "告警", textFont);
        if (workOrderPDF.getEventDecs() != null) {
            string = workOrderPDF.getEventDecs();
        }
        PdfPCell title = new PdfPCell(new Paragraph(string, textFont));
        title.setColspan(3);
        title.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(title);
    }

    private void setPDFText(List<WorkOrderPDFText> workOrderPDFTexts, int maxFileNum, Font titleFont, Font textFont,Font fileFont,PdfPTable tableText) {
        pdFutil.cellFillChar(tableText, "任务状态", textFont);
        pdFutil.cellFillChar(tableText, "处理人", textFont);
        pdFutil.cellFillChar(tableText, "处理时间", textFont);
        pdFutil.cellFillChar(tableText, "意见", textFont);
        if (maxFileNum != 1) {
            PdfPCell title = new PdfPCell(new Paragraph("文件", titleFont));
            title.setColspan(maxFileNum);
            title.setHorizontalAlignment(Element.ALIGN_CENTER);
            title.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            tableText.addCell(title);
        } else {
            pdFutil.cellFillChar(tableText, "文件", textFont);
        }
        for (WorkOrderPDFText workOrderPDFText : workOrderPDFTexts) {
            String string1 = "";
            if (workOrderPDFText.getTaskStatus() != null) {
                string1 = workOrderPDFText.getTaskStatus();
            }
            pdFutil.cellFillChar(tableText, string1, textFont);

            String string2 = "";
            if (workOrderPDFText.getAssignee() != null) {
                string2 = workOrderPDFText.getAssignee();
            }
            pdFutil.cellFillChar(tableText, string2, textFont);

            String string3 = "";
            if (workOrderPDFText.getEndTime() != null) {
                string3 = workOrderPDFText.getEndTime();
            }
            pdFutil.cellFillChar(tableText, string3, textFont);

            String string4 = "";
            if (workOrderPDFText.getSuggestion() != null) {
                string4 = workOrderPDFText.getSuggestion();
            }
            pdFutil.cellFillChar(tableText, string4, textFont);

            List<OrderFile> files = workOrderPDFText.getFiles();
            for (int i = 0; i < maxFileNum; i++) {
                if (files != null && files.size() > i && files.get(i) != null) {
                    String fileName = files.get(i).getFileName();
                    if (fileName != null && fileName.contains("jdg") || fileName.contains("png")) {
                        pdFutil.cellFillImage(tableText, files.get(i).getUrl());
                    }else {
                        pdFutil.cellFillFile(tableText, files.get(i).getUrl(),fileName,fileFont);
                    }
                } else {
                    pdFutil.cellFillChar(tableText, "", textFont);
                }
            }
        }
    }

    private void setTitlePDF(Font titleFont, Font textFont, PdfPTable table, WorkOrderPDF workOrderPDF) {


        //第一行
        String string1 = "";
        if (workOrderPDF.getTitle() != null) {
            string1 = workOrderPDF.getTitle();
        }
        PdfPCell title = new PdfPCell(new Paragraph(string1, titleFont));
        title.setColspan(4);
        title.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(title);


        //第二行
        String string2 = "";
        pdFutil.cellFillChar(table, "工单类型", textFont);
        if (workOrderPDF.getWorkOrderType() != null) {
            string2 = workOrderPDF.getWorkOrderType();
        }
        pdFutil.cellFillChar(table, string2, textFont);

        String string22 = "";
        pdFutil.cellFillChar(table, "创建人", textFont);
        if (workOrderPDF.getCreateName() != null) {
            string22 = workOrderPDF.getCreateName();
        }
        pdFutil.cellFillChar(table, string22, textFont);

        //第三行
        String string3 = "";
        pdFutil.cellFillChar(table, "创建时间", textFont);
        if (workOrderPDF.getCreatTime() != null) {
            string3 = workOrderPDF.getCreatTime();
        }
        pdFutil.cellFillChar(table, string3, textFont);

        String string32 = "";
        pdFutil.cellFillChar(table, "计划处理时间", textFont);
        if (workOrderPDF.getPlanTime() != null) {
            string32 = workOrderPDF.getPlanTime();
        }
        pdFutil.cellFillChar(table, string32, textFont);


    }

    @Autowired
    BusinessFeignClient businessFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    EventMapper eventMapper;

    private int getWorkOrderPDF(List<HisTaskResp> hisTaskRespList, WorkOrderPDF workOrderPDF, List<WorkOrderPDFText> workOrderPDFTexts) {
        if (!hisTaskRespList.isEmpty()) {
            HisTaskResp hisTaskResp = hisTaskRespList.get(0);
            OrderForm orderForm = hisTaskResp.getOrderForm();
            if (orderForm != null) {
                workOrderPDF.setTitle(orderForm.getTitle());
                if (orderForm.getUserId() != null){
                    DataResult<SysUser> result = userFeignClient.getUserById(orderForm.getUserId());
                    if (result.isSuccess() && result.getData() != null){
                        workOrderPDF.setCreateName(result.getData().getRealName());
                    }else {
                        workOrderPDF.setCreateName("");
                    }
                }
                workOrderPDF.setCreatTime(DateUtil.format(orderForm.getCreateTime(), CommonConstant.DATE));
                workOrderPDF.setPlanTime(DateUtil.format(orderForm.getPlannedTime(), CommonConstant.DATE));
                if (orderForm.getOrderType() != null) {
                    switch (orderForm.getOrderType()){
                        case 3:
                            workOrderPDF.setWorkOrderType("清洗工单");
                            break;
                        case 2:
                            workOrderPDF.setWorkOrderType("巡检单");
                            break;
                        default:
                            workOrderPDF.setWorkOrderType("故障检修单");
                            break;
                    }
                }
                if (orderForm.getStationId() != null){
                    DataResult<Station> result = businessFeignClient.selectByStationId(orderForm.getStationId());
                    if (result.isSuccess() && result.getData() != null){
                        workOrderPDF.setStationName(result.getData().getName());
                    }else {
                        workOrderPDF.setStationName("");
                    }
                }

                if (orderForm.getDeviceId() != null && orderForm.getStationId() != null){
                    Map<Integer, List<Integer>> map = new HashMap<>();
                    List<Integer> deviceSrcIds = new ArrayList<>();
                    deviceSrcIds.add(orderForm.getDeviceId());
                    map.put(orderForm.getStationId(),deviceSrcIds);
                    DataResult<List<DeviceRespVO>> result = businessFeignClient.selectDeviceByStationIdsAndSrcId(map);
                    if (result.isSuccess() && result.getData() != null){
                        List<DeviceRespVO> deviceRespVOS = result.getData();
                        if (!deviceRespVOS.isEmpty()) {
                            workOrderPDF.setDeviceName(deviceRespVOS.get(0).getDeviceName());
                        }
                    }else {
                        workOrderPDF.setDeviceName("");
                    }
                }

                if (orderForm.getEventId() != null){
                    Event event = eventMapper.selectByPrimaryKey(orderForm.getEventId());
                    if (event != null){
                        workOrderPDF.setEventDecs(event.getDescription());
                    }else {
                        workOrderPDF.setEventDecs("");
                    }
                }

            }
        }
        int maxFileNum = 1;
        for (HisTaskResp hisTaskResp : hisTaskRespList) {
            WorkOrderPDFText text = new WorkOrderPDFText();
            text.setAssignee(hisTaskResp.getUserName());
            text.setTaskStatus(hisTaskResp.getName());
            text.setEndTime(DateUtil.format(hisTaskResp.getEndTime(), CommonConstant.DATE));
            text.setSuggestion(hisTaskResp.getSuggestion());
            if (hisTaskResp.getOrderForm() != null && !hisTaskResp.getOrderForm().getOrderFiles().isEmpty()) {
                List<OrderFile> orderFiles = hisTaskResp.getOrderForm().getOrderFiles();
                text.setFiles(orderFiles);
                if (orderFiles.size() > maxFileNum) {
                    maxFileNum = orderFiles.size();
                }
            }
            workOrderPDFTexts.add(text);
        }
        return maxFileNum;
    }

    EventToProcessMonitor monitor = new EventToProcessMonitor();


    @PostMapping("movement")
    @ApiOperation(value = "手动转工单")
    @HzPermission(value = {PermissionConstant.EVENT_MANUAL_TRANSFER_WORK_ORDER})
    public DataResult movement(@RequestBody @Valid MovementDTO movementDTO, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        if ( movementDTO.getEvents() != null ) {
            movementDTO.setUserId(simpleUser.getUserId());
            monitor.setEvents(movementDTO);
            return DataResult.success();
        } else {
            throw new BusinessException(BaseResponseCode.MOVEMENT_ERROR);
        }
    }
}
