<script setup lang="tsx">
import type { ProColumns } from '@pubinfo/pro-components';
import { ProTable } from '@pubinfo/pro-components';
import { message } from 'ant-design-vue';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { getBpmProcessDefinitionGet } from '@/api/modules/bpmDefinition/bpMliuchengdingyidexinxibiaokongzhiqi';
import { postBpmProcessInstanceCancelByStartUser, postBpmProcessInstanceMyPage } from '@/api/modules/bpmTask/guanlihoutailiuchengshili';
import { ACTION } from '../../enum';
import { BpmProcessInstanceStatus } from '../../flow-manage/enum';

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

// const BpmProcessInstanceStatus = {
//   NOT_START: -1, // 未开始
//   RUNNING: 1, // 审批中
//   APPROVE: 2, // 审批通过
//   REJECT: 3, // 审批不通过
//   CANCEL: 4, // 已取消
// };
// const drawerFlowTypeRef = ref<InstanceType<typeof DrawerFlowType>>();

const tableRef = ref<typeof ProTable>();

async function request(params: any) {
  const { current, pageSize, ...rest } = params;
  const res = await postBpmProcessInstanceMyPage({
    doSearchTotal: true,
    currentPage: current,
    pageSize,
    ...rest,
  });
  return {
    success: res.success,
    data: res.data?.records ?? [],
    total: res.data?.total ?? 0,
  };
}
const columns: ProColumns<API.BpmCategoryRespVO> = [
  {
    valueType: 'a-input',
    bind: 'value',
    title: '流程名称',
    dataIndex: 'name',
    ellipsis: true,
    fieldProps: {
      placeholder: '请输入流程名称',
      allowClear: true,
    },
  },
  {
    hideInSearch: true,
    title: '摘要',
    dataIndex: 'summary',
    ellipsis: true,
  },
  {
    hideInSearch: true,
    title: '流程分类',
    dataIndex: 'categoryName',
    ellipsis: true,
  },
  {
    hideInSearch: true,
    title: '流程状态',
    dataIndex: 'status',
    ellipsis: true,
  },
  {
    hideInSearch: true,
    title: '发起时间',
    dataIndex: 'startTime',
    ellipsis: true,
  },
  {
    hideInSearch: true,
    title: '结束时间',
    dataIndex: 'endTime',
    ellipsis: true,
  },
  {
    hideInSearch: true,
    width: 200,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
];

function reloadData() {
  tableRef.value?.reload();
}

const router = useRouter();
const activeId = ref<string>('');
const cancelModalOpen = ref(false);
const cancelReason = ref('');

function handleOk() {
  postBpmProcessInstanceCancelByStartUser({ id: activeId.value, reason: cancelReason.value }).then((res: API.ResponseDataBoolean) => {
    if (res.success) {
      message.success('流程已取消');
      cancelModalOpen.value = false;
      cancelReason.value = '';
      reloadData();
    }
  });
};

function onAction(key: string, record?: any): void {
  switch (key) {
    case ACTION.DETAIL:
      router.push({
        name: 'myProcessDetail',
        params: { processInstanceId: record.id },
      });
      break;
    case ACTION.CANCEL:
      activeId.value = record.id;
      cancelModalOpen.value = true;
      break;
    case ACTION.RESTART:
      onRestart(record);
      break;
  }
}

async function onRestart(row: any) {
  // 如果是【业务表单】，不支持重新发起
  if (row?.id) {
    const res = await getBpmProcessDefinitionGet({ id: row.processDefinitionId });
    if (res.data?.formType === 20) {
      message.error('重新发起流程失败，原因：该流程使用业务表单，不支持重新发起');
      return;
    }
  }
  // 跳转发起流程界面
  await router.push({
    name: 'QingJia',
    params: { id: row.processDefinitionId },
    query: { processInstanceId: row?.id },
  });
}

function getShowName(tasks: any[]) {
  if (tasks.length === 0) {
    return '';
  }
  else {
    for (let i = 0; i < tasks.length; i++) {
      if (tasks[i].assigneeUser) {
        return tasks[i].assigneeUser.nickname;
      }
    }
  }
}
</script>

<template>
  <div
    py-10px
    px-10px
    w-full
    h-full
  >
    <ProTable
      ref="tableRef"
      row-key="id"
      :request="request"
      :columns="columns"
      auto-height
      :scroll="{ x: 1100 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'summary'">
          <div v-if="record.summary && record.summary.length > 0" class="flex flex-col">
            <div v-for="(item, index) in record.summary" :key="index">
              {{ item.key }} : {{ item.value }}
            </div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <!-- 审批中状态 -->
          <template v-if="record.status === BpmProcessInstanceStatus.RUNNING && record.tasks?.length > 0">
            <!-- 单人审批 -->
            <template v-if="record.tasks.length === 1">
              <span>
                {{ record.tasks[0].assigneeUser?.nickname }}
                ({{ record.tasks[0].name }}) 审批中
              </span>
            </template>
            <!-- 多人审批 -->
            <template v-else>
              <span>
                {{ getShowName(record.tasks) }}
                等 {{ record.tasks.length }} 人 ({{ record.tasks[0].name }})审批中
              </span>
            </template>
          </template>
          <!-- 非审批中状态 -->
          <template v-else>
            <span v-if="record.status === BpmProcessInstanceStatus.APPROVE" class="green">
              审批通过
            </span>
            <span v-else-if="record.status === BpmProcessInstanceStatus.REJECT" class="red">
              审批不通过
            </span>
            <span v-else class="grey">
              已取消
            </span>
          </template>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a class="flex items-center" @click="onAction(ACTION.DETAIL, record)">
              <span class="ml-4px">{{ ACTION.DETAIL }}</span>
            </a>
            <a v-if="record.status === BpmProcessInstanceStatus.RUNNING" class="flex items-center hover:opacity-80">
              <span class="ml-4px text-red-500!" @click="onAction(ACTION.CANCEL, record)">{{ ACTION.CANCEL }}</span>
            </a>
            <a v-else class="flex items-center hover:opacity-80">
              <span class="ml-4px" @click="onAction(ACTION.RESTART, record)">{{ ACTION.RESTART }}</span>
            </a>
          </a-space>
        </template>
      </template>
    </ProTable>
    <a-modal v-model:open="cancelModalOpen" title="取消流程" @ok="handleOk">
      <div>原因：</div>
      <a-textarea v-model:value="cancelReason" placeholder="请输入取消原因" />
    </a-modal>
  </div>
</template>

<style scoped>
.blue {
  padding: 2px 9px;
  color: #409eff;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
}
.grey {
  padding: 2px 9px;
  color: #909399;
  background-color: rgb(243.9, 244.2, 244.8);
  border: 1px solid rgb(232.8, 233.4, 234.6);
  border-radius: 4px;
}
</style>
