<!--
 * 文件: operateButton.vue
 * 功能: 渲染流程任务的操作按钮集合（通过、拒绝、抄送、转办、委派、加签、减签、退回、取消等）。
 * 主要逻辑:
 * - 使用 Vue <script setup> 和一组 `ref` 管理按钮弹出框状态、选择的人员列表、审批意见等临时数据。
 * - 通过 `selectUser` 打开人员选择器，并将选中用户映射到相应列表（抄送/转办/委派/加签等）。
 * - 每个操作有对应的处理函数（如 `passApprove`/`rejectApprove`/`handleCopyClick` 等），调用后端 API 接口完成业务并在 Promise 返回后重置相关状态。
 * - 使用 `clickedMap` 与 `lastClickInsideMap` 及全局 `mousedown` 事件，控制多个弹出框的打开/关闭与点击内部判断，避免弹出框冲突。
 * - 暴露 `loadTodoTask`、`loadProcessInstance`、`loadProcessDefinition` 方法供父组件传入数据并刷新视图。
 * - 提供工具函数：`isEndProcessStatus`、`isShowButton`、`isHandleTaskStatus`、`getDeleteSignUserLabel`，用于决定按钮显示、标签格式化与权限判断。
 * - 与 `userStore`、`OperationButtonType`、`BpmProcessInstanceStatus`、`TaskStatusEnum` 等共享常量和状态，控制可见性与操作权限。
 * 注意事项:
 * - 减签操作从当前任务的 `children` 中选择需移除的签收人条目；
 * - 加签支持向前/向后两种模式。
 * - 弹出框中用户选择与操作提交后会清理对应的列表和输入（如 `reason`、各类 userList）。
 * - 修改时尽量保持对 API 调用返回的错误与异常做进一步处理（当前实现以简单 then 处理为主）。
-->

<script setup lang="ts">
import { useUserStore } from 'pubinfo';
import { ref } from 'vue';
import {
  postBpmTaskClaim,
} from '@/api/modules/bpmTask/guanlihoutailiuchengrenwushili';
import { OperationButtonType } from '../../flow-create/flow-model/createComponents/flow/ts/enum';
import { BpmProcessInstanceStatus, TaskStatusEnum } from '../enum';
import DrawerHandle from './drawerHandle.vue';

defineOptions({
  name: 'OperateButton',
});

const emit = defineEmits(['refresh']);
const drawerHandleRef = ref<InstanceType<typeof DrawerHandle>>();
const userStore = useUserStore();

const runningTask = ref<any>(null);
const processInstance = ref<any>(null);
const processDefinition = ref<any>(null);

/** 流程状态是否为结束状态 */
function isEndProcessStatus(status: number) {
  let isEndStatus = false;
  if (
    BpmProcessInstanceStatus.APPROVE === status
    || BpmProcessInstanceStatus.REJECT === status
    || BpmProcessInstanceStatus.CANCEL === status
  ) {
    isEndStatus = true;
  }
  return isEndStatus;
}

/** 是否显示按钮 */
function isShowButton(btnType: OperationButtonType) {
  let isShow = true;
  if (runningTask.value?.buttonsSetting && runningTask.value?.buttonsSetting[btnType]) {
    isShow = runningTask.value.buttonsSetting[btnType].enable;
  }
  return isShow;
}

/** 任务是否为处理中状态 */
function isHandleTaskStatus() {
  let canHandle = false;
  if (TaskStatusEnum.RUNNING === runningTask.value?.status) {
    canHandle = true;
  }
  return canHandle;
}

// 针对审批方式为认领审批
const route = useRoute();
function handleQianShou() {
  const taskId = route.query.taskId as string;
  postBpmTaskClaim({ id: taskId }).then((res: any) => {
    // console.log('Claim Response:', res);
    emit('refresh');
  });
}
function onAction(optType: OperationButtonType, runningTask: any, processInstanceTemp?: any) {
  drawerHandleRef.value?.open(optType, runningTask, processInstanceTemp);
}

function loadTodoTask(task: any) {
  runningTask.value = task;
}

function loadProcessInstance(instance: any) {
  processInstance.value = instance;
}

function loadProcessDefinition(definition: any) {
  processDefinition.value = definition;
}

defineExpose({ loadTodoTask, loadProcessInstance, loadProcessDefinition });
</script>

<template>
  <a-space>
    <!-- 【通过】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.APPROVE)" type="primary" @click="onAction(OperationButtonType.APPROVE, runningTask)">
      通过
    </a-button>
    <!-- 【拒绝】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.REJECT)" danger @click="onAction(OperationButtonType.REJECT, runningTask)">
      拒绝
    </a-button>
    <!-- 【抄送】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.COPY)" type="text" @click="onAction(OperationButtonType.COPY, runningTask)">
      抄送
    </a-button>
    <!-- 【转办】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.TRANSFER)" type="text" @click="onAction(OperationButtonType.TRANSFER, runningTask)">
      转办
    </a-button>

    <!-- 【委派】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.DELEGATE)" type="text" @click="onAction(OperationButtonType.DELEGATE, runningTask)">
      委派
    </a-button>

    <!-- 【加签】按钮 加签分为向前加签、向后加签; 当前任务审批人为A，向前加签选了一个C，则需要C先审批，然后再是A审批，向后加签B，A审批完，需要B再审批完，才算完成这个任务节点  -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.ADD_SIGN)" type="text" @click="onAction(OperationButtonType.ADD_SIGN, runningTask)">
      加签
    </a-button>
    <!-- 【减签】按钮 -->
    <a-button v-if="runningTask?.children?.length > 0" type="text" @click="onAction(OperationButtonType.DELETE_SIGN, runningTask)">
      减签
    </a-button>
    <!-- 【退回】按钮 -->
    <a-button v-if="runningTask && isHandleTaskStatus() && isShowButton(OperationButtonType.RETURN)" type="text" @click="onAction(OperationButtonType.RETURN, runningTask)">
      退回
    </a-button>

    <a-button v-if="runningTask && runningTask.needClaim" size="small" type="primary" @click="handleQianShou">
      签收
    </a-button>

    <!-- 【取消】按钮 这个对应发起人的取消, 只有发起人可以取消 -->
    <a-button v-if="userStore.user.userId === processInstance?.startUser?.id && !isEndProcessStatus(processInstance?.status)" type="text" @click="onAction(OperationButtonType.CANCEL, runningTask, processInstance)">
      取消
    </a-button>
    <!-- <a-button v-if="userStore.user.userId === processInstance?.startUser?.id && isEndProcessStatus(processInstance?.status)" type="text" @click="handleReCreate()">
      再次提交
    </a-button> -->
    <DrawerHandle ref="drawerHandleRef" @submit="emit('refresh');" />
  </a-space>
</template>
