package com.zbf.web.controller.flowable;


import cn.hutool.system.UserInfo;
import com.zbf.common.core.controller.BaseController;
import com.zbf.common.core.domain.AjaxResult;
import com.zbf.common.core.domain.entity.SysUser;
import com.zbf.common.core.page.TableDataInfo;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.common.utils.StringUtils;
import com.zbf.system.config.D_Service;
import com.zbf.system.domain.OutBound;
import com.zbf.system.domain.SysPost;
import com.zbf.system.domain.TCkOrders;
import com.zbf.system.domain.TaskInfo;
import com.zbf.system.mapper.OutBoundMapper;
import com.zbf.system.mapper.SysPostMapper;
import com.zbf.system.service.ISysPostService;
import com.zbf.system.service.ISysUserService;
import com.zbf.system.service.ITCkOrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.pro.packaged.O;
import org.flowable.engine.FormService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.user.UserRegistryMessageHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.swing.text.StyledEditorKit;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(value = "待办任务接口")
@Controller
@RequestMapping("/task/manage")
public class TaskController extends BaseController {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    FormService formService;

    @Resource
    private HistoryService historyService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private ITCkOrdersService tCkOrdersService;

    @Autowired
    private D_Service d_service;
    @Autowired
    private OutBoundMapper outBoundMapper;
    private String prefix = "flowable/task";

    @GetMapping("/mytask")
    public String mytasks() {
        return prefix + "/mytasks";
    }

    @GetMapping("/alltasks")
    public String alltasks() {
        return prefix + "/alltasks";
    }

    /**
     * 查询我的待办任务列表
     */
    @ApiOperation("查询我的待办任务列表")
    @PostMapping("/mylist")
    @ResponseBody
    public TableDataInfo mylist(TaskInfo param) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String username = getUsername();
        TaskQuery condition = taskService.createTaskQuery().taskAssignee(username);
        if (StringUtils.isNotEmpty(param.getTaskName())) {
            condition.taskName(param.getTaskName());
        }
        if (StringUtils.isNotEmpty(param.getProcessName())) {
            condition.processDefinitionName(param.getProcessName());
        }
        // 过滤掉流程挂起的待办任务
        int total = condition.active().orderByTaskCreateTime().desc().list().size();
        int start = (param.getPageNum() - 1) * param.getPageSize();
        List<Task> taskList = condition.active().orderByTaskCreateTime().desc().listPage(start, param.getPageSize());
        List<TaskInfo> tasks = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        taskList.stream().forEach(a -> {
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(a.getProcessInstanceId()).singleResult();
            TaskInfo info = new TaskInfo();
            SysUser user1 = userService.selectUserByUserName(a.getAssignee());
            if (user1 == null) {
                info.setAssignee(a.getAssignee());
            } else {
                info.setAssignee(user1.getNickName());
            }
//            info.setAssignee(a.getAssignee());
            info.setBusinessKey(process.getBusinessKey());
            info.setCreateTime(sdf.format(a.getCreateTime()));

            info.setExecutionId(a.getExecutionId());
            info.setProcessInstanceId(a.getProcessInstanceId());
            info.setProcessName(process.getProcessDefinitionName());
            info.setStarter(process.getStartUserId());
            info.setStartTime(sdf.format(process.getStartTime()));
            info.setTaskId(a.getId());
            String formKey = formService.getTaskFormData(a.getId()).getFormKey();
            info.setFormKey(formKey);
            if (formKey.contains("outbound")) {
                info.setTaskName("出库通知单审批申请");
            } else {
                info.setTaskName(a.getName());
            }
            tasks.add(info);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(tasks);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 查询所有待办任务列表
     */
    @ApiOperation("查询所有待办任务列表")
    @PostMapping("/alllist")
    @ResponseBody
    public TableDataInfo alllist(TaskInfo param) {
        TaskQuery condition = taskService.createTaskQuery();
        if (StringUtils.isNotEmpty(param.getTaskName())) {
            condition.taskName(param.getTaskName());
        }
        if (StringUtils.isNotEmpty(param.getProcessName())) {
            condition.processDefinitionName(param.getProcessName());
        }
        int total = condition.active().orderByTaskCreateTime().desc().list().size();
        int start = (param.getPageNum() - 1) * param.getPageSize();
        List<Task> taskList = condition.active().orderByTaskCreateTime().desc().listPage(start, param.getPageSize());
        List<TaskInfo> tasks = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        taskList.stream().forEach(a -> {
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(a.getProcessInstanceId()).singleResult();
            TaskInfo info = new TaskInfo();
            SysUser user1 = userService.selectUserByUserName(a.getAssignee());
            if (user1 == null) {
                info.setAssignee(a.getAssignee());
            } else {
                info.setAssignee(user1.getNickName());
            }
//            info.setAssignee(a.getAssignee());
            info.setBusinessKey(process.getBusinessKey());
            info.setCreateTime(sdf.format(a.getCreateTime()));
//            info.setTaskName(a.getName());
            info.setExecutionId(a.getExecutionId());
            info.setProcessInstanceId(a.getProcessInstanceId());
            info.setProcessName(process.getProcessDefinitionName());
            info.setStarter(process.getStartUserId());
            info.setStartTime(sdf.format(process.getStartTime()));
            info.setTaskId(a.getId());
            String formKey = formService.getTaskFormData(a.getId()).getFormKey();
            info.setFormKey(formKey);
            if (formKey.contains("outbound")) {
                info.setTaskName("出库通知单审批申请");
            } else {
                info.setTaskName(a.getName());
            }
            tasks.add(info);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(tasks);
        rspData.setTotal(total);
        return rspData;
    }


    /**
     * 用taskid查询formkey
     **/
    @ApiOperation("用taskid查询formkey")
    @PostMapping("/forminfo/{taskId}")
    @ResponseBody
    public AjaxResult alllist(@PathVariable String taskId) {
        String formKey = formService.getTaskFormData(taskId).getFormKey();
        return AjaxResult.success(formKey);
    }

    @ApiOperation("办理一个用户任务")
    @RequestMapping(value = "/completeTask/{taskId}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult completeTask(@PathVariable("taskId") String taskId, @RequestBody(required = false) Map<String, Object> variables) {
        logger.info("办理一个代办：{}",taskId);
        String username = getUsername();
        taskService.setAssignee(taskId, username);
        //存储审核结果
        variables.put(username, variables.get("result"));
        SysUser user = userService.selectUserByUserName(username);
        // 查出流程实例id
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        if (variables == null) {
            taskService.complete(taskId);
        } else {
            // 添加审批意见
            String comment = StringUtils.EMPTY;
            if (variables.get("comment") != null) {
                taskService.addComment(taskId, processInstanceId, (String) variables.get("comment"));
                comment = (String) variables.get("comment");
                variables.remove("comment");
            }
            String deliveryId = (String)runtimeService.getVariable(processInstanceId, "deliveryId");
            TCkOrders tCkOrders1 = tCkOrdersService.selectTCkOrdersByDeliveryId(deliveryId);
            TCkOrders tCkOrders = new TCkOrders();
            tCkOrders.setId(tCkOrders1.getId());
            String auditMan = tCkOrders1.getAuditMan();
            if (StringUtils.isNotBlank(auditMan)) {
                tCkOrders.setAuditMan(auditMan + "->" + user.getNickName());
            } else {
                tCkOrders.setAuditMan(user.getNickName());
            }
            tCkOrders.setAuditDate(new Date());
            //更新出库明细
            String dResult = StringUtils.EMPTY;
            if ("false".equals(variables.get("result"))) {
                dResult = "refuse";
                if (StringUtils.isNotBlank(comment)) {
                    if (StringUtils.isNotBlank(tCkOrders1.getRejectReason())) {
                        tCkOrders.setRejectReason(tCkOrders1.getRejectReason() + "|" + user.getNickName() + ":拒绝,原因:" + comment);
                    } else {
                        tCkOrders.setRejectReason(user.getNickName() + ":拒绝,原因:" + comment);
                    }
                } else {
                    if (StringUtils.isNotBlank(tCkOrders1.getRejectReason())) {
                        tCkOrders.setRejectReason(tCkOrders1.getRejectReason() + "|" + user.getNickName() + ":拒绝");
                    } else
                        tCkOrders.setRejectReason(user.getNickName() + ":拒绝");
                }
            } else {
                dResult = "agree";
                if (StringUtils.isNotBlank(comment)) {
                    if (StringUtils.isNotBlank(tCkOrders1.getRejectReason())) {
                        tCkOrders.setRejectReason(tCkOrders1.getRejectReason() + "|" + user.getNickName() + ":同意,意见:" + comment);
                    } else {
                        tCkOrders.setRejectReason(user.getNickName() + ":同意,意见:" + comment);
                    }
                } else {
                    if (StringUtils.isNotBlank(tCkOrders1.getRejectReason())) {
                        tCkOrders.setRejectReason(tCkOrders1.getRejectReason() + "|" + user.getNickName() + ":同意");
                    } else
                        tCkOrders.setRejectReason(user.getNickName() + ":同意");

                }
            }
            tCkOrders.setRemark(dResult);
            if("refuse".equalsIgnoreCase(dResult)){
                tCkOrders.setIsAudit("3");
            }
            tCkOrdersService.updateTCkOrders(tCkOrders);
            String instanceId = (String)runtimeService.getVariable(processInstanceId, "instanceId");
            taskService.complete(taskId, variables);
            //更新下一个任务id
            List<Task> nextTasks = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)  // 根据流程实例 ID 查询
                    .orderByTaskCreateTime().desc()  // 按任务创建时间排序
                    .list();

            if (!nextTasks.isEmpty()) {
                Task nextTask = nextTasks.get(0);  // 获取下一个任务
                String nextTaskId = nextTask.getId();
                System.out.println("下一个任务的 ID: " + nextTaskId);
                OutBound outBound = new OutBound();
                outBound.setfInstanceId(processInstanceId);
                List<OutBound> outBounds = outBoundMapper.selectOutBoundList(outBound);
                if(!outBounds.isEmpty()){
                    OutBound outBound1 = outBounds.get(0);
                    OutBound outBound44 = new OutBound();
                    outBound44.setId(outBound1.getId());
                    outBound44.setTaskId(nextTaskId);
                    outBound44.setUpdateTime(new Date());
                    outBound44.setFinishName(username);
                    outBoundMapper.updateOutBound(outBound44);
                }
            }
            //同步钉钉
            //根据taskId查询钉钉实例ID
//            Map<String, Object> variables1 = taskService.getVariables(taskId);
//            String instanceId = (String)runtimeService.getVariable(processInstanceId, "instanceId");
//            String instanceId =(String) variables1.get("instanceId");
            logger.info("发起同步钉钉,钉钉实例ID=====》》》》{} ",instanceId);
//            logger.info("发起同步钉钉,获取所有变量：==》》》》{} ",variables1);
//            variables1.forEach((key, value) ->  logger.info(key + ": " + value));
            if(StringUtils.isNotBlank(instanceId)) {
                d_service.auditStatusToDd(instanceId, username, dResult);
            }
        }
        return AjaxResult.success();
    }

    @ApiOperation("任务办理时间轴")
    @RequestMapping(value = "/history/{taskId}", method = RequestMethod.GET)
    @ResponseBody
    public List<TaskInfo> history(@PathVariable String taskId) {
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        List<HistoricActivityInstance> history = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).activityType("userTask").orderByHistoricActivityInstanceStartTime().asc().list();
        List<TaskInfo> infos = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        history.stream().forEach(h -> {
            TaskInfo info = new TaskInfo();
            info.setProcessInstanceId(h.getProcessInstanceId());
            info.setStartTime(sdf.format(h.getStartTime()));
            if (h.getEndTime() != null) {
                info.setEndTime(sdf.format(h.getEndTime()));
            }
            //根据用户名或者昵称
            Map<String, Object> variables = taskService.getVariables(taskId);

            SysUser user = userService.selectUserByUserName(h.getAssignee());
//            info.setAssignee(h.getAssignee());
            StringBuilder userInfo = new StringBuilder();
            if (user != null) {
                List<SysPost> sysPosts = sysPostMapper.selectPostsByUserName(user.getUserName());
                userInfo.append("【 " + user.getDept().getDeptName() + " 】");
                userInfo.append("【 ");
                for (SysPost post : sysPosts) {
                    userInfo.append(post.getPostName()).append(" ");
                }
                ;
                userInfo.append("】");
                userInfo.append(user.getNickName());
            } else {
                userInfo.append(h.getAssignee());
            }
            String result = (String) variables.get(h.getAssignee());
            info.setAssignee(userInfo.toString());
            if ("true".equals(result)) {
                info.setResult("同意");
            } else if ("false".equals(result)) {
                info.setResult("拒绝");
            }

//            info.setTaskName(h.getActivityName());
//            info.setTaskName("出库通知单申请");
            List<Comment> comments = taskService.getTaskComments(h.getTaskId());
            if (comments.size() > 0) {
                info.setComment(comments.get(0).getFullMessage());
            }
            infos.add(info);
        });
        return infos;
    }
}
