<!-- UserTask 自定义配置：
     1. 审批类型
     2. 审批人拒绝时
     3. 审批人为空时
     4. 审批人与提交人为同一人时
     5. 操作按钮
     6. 字段权限
     7. 是否需要签名
-->
<script setup lang="tsx">
import type { TableProps } from 'ant-design-vue';
import type { User } from '../../ts/flow.ts';
import { selectUser } from '@pubinfo/module-rbac';
import { reactive } from 'vue';
import { useElementsInfoStore } from '../../stores/elementsInfo.ts';
import { useSelectedInfoStore } from '../../stores/selectedInfo.ts';

defineOptions({ name: 'CustomConfiguration' });

const lf: any = inject('lf');
const elementsInfoStore = useElementsInfoStore();
const selectedInfoStore = useSelectedInfoStore();

const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});

const formState = ref<any>({
  approveType: '1', // 审批类型
  rejectHandlerType: '1', // 审批人拒绝时
  rejectReturnTaskId: '', // 驳回节点
  assignEmptyHandlerType: '1', // 审批人为空时
  assignEmptyUserIds: [], // 指定用户
  assignStartUserHandlerType: '1', // 审批人与提交人为同一人时
  buttonsSetting: [], // 操作按钮
  fieldsPermission: [], // 字段权限
  signEnable: false, // 是否需要签名
  reasonRequire: false, // 审批意见
});

const returnTaskList = ref<any[]>([]);
const selectedUsers = ref<User[]>([]);
function chooseUsers() {
  selectUser({
    modelValue: selectedUsers.value, // 回显时选中的数据
    multiple: true,
    onSubmit(selected = []) {
      // console.log(selected); // 点击确认后返回选中的数据
      selectedUsers.value = selected.map((user) => {
        return {
          orgId: user.orgId as string,
          userId: user.userId as string,
          userName: user.userName as string,
        };
      });
    },
  });
}
function handleUsersClose(tag: User) {
  selectedUsers.value = selectedUsers.value.filter(item => item.userId !== tag.userId);
}

watch(
  () => selectedUsers.value,
  (newVal) => {
    formState.value.assignEmptyUserIds = newVal.map(item => item.userId);
  },
  { deep: true },
);

const columns = [
  {
    title: '操作按钮',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '显示名称',
    dataIndex: 'displayName',
    key: 'displayName',
  },
  {
    title: '启用',
    dataIndex: 'enable',
    key: 'enable',
  },
];

const settingColumns: TableProps['columns'] = [
  {
    title: '字段名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '只读',
    key: 'readonly',
    align: 'center',
  },
  {
    title: '可编辑',
    key: 'editable',
    align: 'center',
  },
  {
    title: '隐藏',
    key: 'hidden',
    align: 'center',
  },
];

const elementInfo = computed(() => {
  return elementsInfoStore.getElementById(selectedInfoStore.selectId) || {};
});

watch(elementInfo, (val) => {
  formState.value = val.customConfiguration || formState.value;
  const ids = getAllNode(val);
  returnTaskList.value = ids.map((id) => {
    return {
      label: id,
      value: id,
    };
  });
}, { immediate: true, deep: true });

watch(formState, (newVal) => {
  elementsInfoStore.updateElement(selectedInfoStore.selectId, {
    customConfiguration: newVal,
  });
  lf.value.setProperties(selectedInfoStore.selectId, {
    customConfiguration: newVal,
  });
}, { deep: true });

function getAllNode(val: any) {
  // 返回给定节点（或节点 id）的所有上游节点 id（不包含自身）
  const startId: string | undefined = typeof val === 'string' ? val : val?.id;
  if (!startId) {
    return [] as string[];
  }

  const visited = new Set<string>();
  const result: string[] = [];
  // 使用栈进行深度优先遍历（也可以使用队列做广度优先）
  const stack: string[] = [];

  // 首先获取直接上游节点并入栈
  const firstIncoming = lf.value.getNodeIncomingNode(startId) || [];
  firstIncoming.forEach((n: any) => {
    const nid = typeof n === 'string' ? n : n?.id;
    const ntype = typeof n === 'object' ? n?.type : undefined;
    // 跳过 start-node 类型
    if (nid && nid !== startId && ntype !== 'start-node') {
      stack.push(nid);
    }
  });

  while (stack.length) {
    const currentId = stack.pop() as string;
    if (!currentId || visited.has(currentId)) {
      continue;
    }
    visited.add(currentId);
    result.push(currentId);

    // 获取 currentId 的直接上游节点
    const incoming = lf.value.getNodeIncomingNode(currentId) || [];
    incoming.forEach((node: any) => {
      const nid = typeof node === 'string' ? node : node?.id;
      const ntype = typeof node === 'object' ? node?.type : undefined;
      // 跳过 start-node 类型
      if (nid && !visited.has(nid) && nid !== startId && ntype !== 'start-node') {
        stack.push(nid);
      }
    });
  }

  // 返回按发现顺序的去重 id 列表
  return result;
}
</script>

<template>
  <div>
    <a-form
      :model="formState"
      name="basic"
      autocomplete="off"
    >
      <a-form-item
        label="审批类型"
        name="approveType"
      >
        <a-radio-group v-model:value="formState.approveType" :disabled="elementInfo.type === 'normal-task-node'">
          <a-radio value="1">
            人工审批
          </a-radio>
          <a-radio value="2">
            自动通过
          </a-radio>
          <a-radio value="3">
            自动拒绝
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="审批人拒绝时"
        name="rejectHandlerType"
      >
        <a-radio-group v-model:value="formState.rejectHandlerType" :disabled="elementInfo.type === 'normal-task-node'">
          <a-radio value="1">
            终止流程
          </a-radio>
          <a-radio value="2" :disabled="returnTaskList.length === 0">
            驳回到指定节点
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="formState.rejectHandlerType === '2'"
        label="驳回节点"
        name="rejectReturnTaskId"
      >
        <a-select
          v-model:value="formState.rejectReturnTaskId"
          style="width: 100%;"
          placeholder="请选择驳回节点"
          :options="returnTaskList"
        />
      </a-form-item>
      <a-form-item
        label="审批人为空时"
        name="assignEmptyHandlerType"
      >
        <a-radio-group v-model:value="formState.assignEmptyHandlerType" :disabled="elementInfo.type === 'normal-task-node'">
          <a-radio :style="radioStyle" value="1">
            自动通过
          </a-radio>
          <a-radio :style="radioStyle" value="2">
            自动拒绝
          </a-radio>
          <a-radio :style="radioStyle" value="3">
            指定用户审批
          </a-radio>
          <a-radio :style="radioStyle" value="4">
            转交给流程管理员
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="formState.assignEmptyHandlerType === '3'"
        label="指定用户"
        name="assignEmptyUserIds"
      >
        <a-tag v-for="(tag, index) in selectedUsers" :key="index" closable @close="handleUsersClose(tag)">
          {{ tag.userName }}
        </a-tag>
        <a-button size="small" type="primary" @click="chooseUsers">
          选择人员
        </a-button>
      </a-form-item>

      <a-form-item
        label="审批人与提交人为同一人时"
        name="assignStartUserHandlerType"
      >
        <a-radio-group v-model:value="formState.assignStartUserHandlerType" :disabled="elementInfo.type === 'normal-task-node'">
          <a-radio value="1">
            由发起人对自己审批
          </a-radio>
          <a-radio value="2">
            自动跳转
          </a-radio>
          <a-radio value="3">
            转交给部分负责人审批
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <div text-14px>
        操作按钮：
      </div>
      <a-table class="my-16px" size="small" bordered :columns="columns" :data-source="formState.buttonsSetting" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'displayName'">
            <a-input v-model:value="record.displayName" :disabled="elementInfo.type === 'normal-task-node'" />
          </template>
          <template v-else-if="column.key === 'enable'">
            <a-switch v-model:checked="record.enable" :disabled="elementInfo.type === 'normal-task-node'" />
          </template>
        </template>
      </a-table>
      <div v-show="false" text-14px>
        字段权限：
      </div>
      <a-table
        v-show="false"
        class="my-16px"
        size="small"
        bordered
        :columns="settingColumns"
        :data-source="formState.fieldsPermission"
        :pagination="false"
        row-key="key"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'editable'">
            <a-radio
              :checked="record.permission === '2'"
              :disabled="elementInfo.type === 'normal-task-node'"
              @change="record.permission = '2';"
            />
          </template>
          <template v-if="column.key === 'readonly'">
            <a-radio
              :checked="record.permission === '1'"
              :disabled="elementInfo.type === 'normal-task-node'"
              @change="record.permission = '1';"
            />
          </template>
          <template v-if="column.key === 'hidden'">
            <a-radio
              :checked="record.permission === '3'"
              :disabled="elementInfo.type === 'normal-task-node'"
              @change="record.permission = '3';"
            />
          </template>
        </template>
      </a-table>
      <a-form-item
        label="是否需要签名"
        name="signEnable"
      >
        <a-switch v-model:checked="formState.signEnable" checked-children="是" un-checked-children="否" :disabled="elementInfo.type === 'normal-task-node'" />
      </a-form-item>
      <a-form-item
        label="审批意见"
        name="reasonRequire"
      >
        <a-switch v-model:checked="formState.reasonRequire" checked-children="必填" un-checked-children="非必填" :disabled="elementInfo.type === 'normal-task-node'" />
      </a-form-item>
    </a-form>
  </div>
</template>
