<script lang="ts" setup>
import type { RadioChangeEvent } from 'element-plus';

import type { VbenFormProps } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { ColPage, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElMessage, ElMessageBox, ElRadioGroup, ElRadioButton } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  unPublishList,
  workflowDefinitionActive,
  workflowDefinitionCopy,
  workflowDefinitionDelete,
  workflowDefinitionExport,
  workflowDefinitionList,
  workflowDefinitionUnPublish,
  workflowDefinitionPublish,
} from '#/api/workflow/definition';
import { commonDownloadExcel, downloadByData } from '#/utils/file/download';

import CategoryTree from './category-tree.vue';
import { columns, querySchema } from './config-data';
import ProcessDefinitionDrawer from './process-definition-drawer.vue';
import ProcessDefinitionDeployDrawer from './process-definition-deploy-drawer.vue';

// 左边分类树选中的节点
const selectedCode = ref<number>(0);

// 头部查询表单配置
const formOptions: VbenFormProps = {
  handleReset: onQueryRest,
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 重置查询
async function onQueryRest() {
  selectedCode.value = 0;
  const { formApi, reload } = GridApi;
  await formApi.resetForm();
  const formValues = formApi.form.values;
  formApi.setLatestSubmissionValues(formValues);
  await reload(formValues);
}

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 分类树选择处理
        if (selectedCode.value) {
          formValues.category = selectedCode.value;
        } else {
          Reflect.deleteProperty(formValues, 'category');
        }

        const resp = await currentTableApi.value({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'workflow-definition-index',
};

// 列表组件配置
const [BasicTable, GridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 左边的切换选项
const statusOptions = [
  { label: '已发布流程', value: 1 },
  { label: '未发布流程', value: 0 },
];
const currentStatus = ref(1);
const currentTableApi = computed(() => {
  if (currentStatus.value === 1) {
    return workflowDefinitionList;
  }
  return unPublishList;
});

// 状态切换事件处理
async function handleStatusChange(e: RadioChangeEvent) {
  currentStatus.value = e;
  
  await GridApi.reload();
}

// 单个删除流程
async function confirmEvent(row: Recordable<any>) {
  await ElMessageBox.confirm(
    `确认删除流程[${row.flowName}]吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  );
  await workflowDefinitionDelete(row.id);
  await GridApi.reload();
}

// 多选删除流程
function handleDeletes() {
  // 获取全部选中的数据
  const checkRecords = GridApi.grid.getCheckboxRecords();
  // 数据转换只要id
  const ids = checkRecords.map((item: any) => item.id);
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除流程
    await workflowDefinitionDelete(ids);
    // 重置查询
    await GridApi.reload();
  });
}

const router = useRouter();
/**
 * 流程设计/预览
 * @param row 流程定义数据
 */
function handleDesign(row: any) {
  router.push({
    path: '/workflow/design/index',
    query: { definitionId: row.id },
  });
}

/**
 * 激活/挂起流程
 * @param row 流程定义数据
 * @param status 激活状态
 */
async function handleActive(row: any, status: boolean | number | string) {
  const lastStatus = status === 1 ? 0 : 1;
  try {
    await workflowDefinitionActive(row.id, !!status);
    await GridApi.reload();
  } catch (error) {
    row.activityStatus = lastStatus;
    console.error(error);
  }
}

/**
 * 发布流程
 * @param row 流程定义数据
 */
async function handlePublish(row: any) {
  await workflowDefinitionPublish(row.id);
  await GridApi.reload();
}

async function handleUnPublish(row: any) {
  await workflowDefinitionUnPublish(row.id);
  await GridApi.reload();
}

/**
 * 复制流程
 * @param row 流程定义数据
 */
async function handleCopy(row: any) {
  await workflowDefinitionCopy(row.id);
  // 跳转到未发布流程tab
  currentStatus.value = 0;
  await GridApi.reload();
}

/**
 * 导出流程
 * @param row 流程定义数据
 */
async function handleExportXml(row: any) {
  try {
    await commonDownloadExcel(workflowDefinitionExport, row.flowName, { id: row.id });
    ElMessage.success('导出成功');
  } catch (error: any) {
    ElMessage.error(error.message || '导出失败');
  }
}

/**
 * 部署流程
 */
function handleDeploy() {
  if (selectedCode.value === 0) {
    ElMessage.warning('请先选择流程分类');
    return;
  }
  const selectedCategory = selectedCode.value;
  if (selectedCategory === 0) {
    ElMessage.warning('不可选择根目录进行部署, 请选择子分类');
    return;
  }
  deployDrawerApi.setData({ category: selectedCategory }).open();
}

// 新增流程
function handleAdd() {
  console.log(selectedCode.value);
  processDrawerApi.setData({ category: selectedCode.value }).open();
}

// 编辑流程
function handleEdit(row: any) {
  row.category = row.category * 1 || 0;
  processDrawerApi.setData({ ...row, update: true }).open();
}
const { hasAccessByCodes } = useAccess();

// 侧拉组件连接
const [ProcessDefinitionDrawerComponent, processDrawerApi] = useVbenDrawer({
  connectedComponent: ProcessDefinitionDrawer,
});

// 部署流程侧拉组件连接
const [ProcessDefinitionDeployDrawerComponent, deployDrawerApi] = useVbenDrawer({
  connectedComponent: ProcessDefinitionDeployDrawer,
});
</script>

<template>
  <div>
    <ColPage :left-width="20" auto-content-height>
      <template #left>
        <div
          :style="{ minWidth: '260px' }"
          class="border-border bg-card mr-2 h-full rounded-[var(--radius)] border p-2"
        >
          <CategoryTree
            v-model:select-code="selectedCode"
            @reload="() => GridApi.reload()"
            @select="() => GridApi.reload()"
          />
        </div>
      </template>
      <div
        class="border-border bg-card mr-2 h-full rounded-[var(--radius)] border p-2"
      >
        <BasicTable class="flex-1 overflow-hidden">
          <template #toolbar-actions>
            <ElRadioGroup v-model="currentStatus" @change="handleStatusChange">
              <ElRadioButton
                v-for="option in statusOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </ElRadioButton>
            </ElRadioGroup>
          </template>
          <template #toolbar-tools>
            <ElSpace>
              <ElButton
                type="danger"
                :disabled="!(GridApi?.grid?.getCheckboxRecords?.()?.length > 0)"
                @click="handleDeletes"
                v-access:code="['workflow:definition:delete']"
              >
                {{ $t('pages.common.delete') }}
              </ElButton>
              <ElButton
                @click="handleDeploy"
                v-access:code="['workflow:definition:deploy']"
              >
                部署
              </ElButton>
              <ElButton
                type="primary"
                @click="handleAdd"
                v-access:code="['workflow:definition:add']"
              >
                {{ $t('pages.common.add') }}
              </ElButton>
            </ElSpace>
          </template>
          <template #activityStatus="{ row }">
            <ElSwitch
              v-model="row.activityStatus"
              inline-prompt
              active-text="激活"
              inactive-text="挂起"
              :active-value="1"
              :inactive-value="0"
              @change="() => handleActive(row, row.activityStatus)"
              :disabled="!hasAccessByCodes(['workflow:definition:edit']).length > 0"
            />
          </template>
          <template #action="{ row }">
            <ElSpace>
              <ElButton
                size="small"
                type="primary"
                plain
                @click="handleEdit(row)"
                v-access:code="['workflow:definition:edit']"
              >
                编辑信息
              </ElButton>
              <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
                <template #reference>
                  <ElButton
                    v-if="!row.isPublish && row.useExpression === 'N'"
                    size="small"
                    type="danger"
                    plain
                    v-access:code="['workflow:definition:delete']"
                  >
                    删除流程
                  </ElButton>
                </template>
              </ElPopconfirm>
              <ElButton
                size="small"
                type="primary"
                plain
                @click="handleDesign(row)"
                v-access:code="['workflow:definition:design']"
              >
                {{ row.isPublish ? '查看流程' : '设计流程' }}
              </ElButton>
              <ElPopconfirm
                placement="left"
                :title="`确认发布流程[${row.flowName}]?`"
                @confirm="handlePublish(row)">
                <template #reference>
                  <ElButton
                    v-if="!row.isPublish"
                    size="small"
                    type="primary"
                    plain
                    v-access:code="['workflow:definition:publish']"
                  >
                    发布流程
                  </ElButton>
                </template>
              </ElPopconfirm>
              <ElPopconfirm
                placement="left"
                :title="`确认取消发布流程[${row.flowName}]?`"
                @confirm="handleUnPublish(row)">
                <template #reference>
                  <ElButton
                    v-if="row.isPublish && row.useExpression === 'N'"
                    size="small"
                    type="warning"
                    plain
                    v-access:code="['workflow:definition:publish']"
                  >
                    取消发布
                  </ElButton>
                </template>
              </ElPopconfirm>
              <ElPopconfirm
                :title="`确认复制流程[${row.flowName}]?`"
                @confirm="handleCopy(row)" >
                <template #reference>
                  <ElButton
                    size="small"
                    type="primary"
                    plain
                    v-access:code="['workflow:definition:copy']"
                  >
                    复制流程
                  </ElButton>
                </template>
              </ElPopconfirm>
              <!-- <ElButton size="small" type="primary" plain @click="handleExportXml(row)" v-access:code="['workflow:definition:export']" >
                导出流程
              </ElButton> -->
            </ElSpace>
          </template>
        </BasicTable>
      </div>
    </ColPage>
    <ProcessDefinitionDrawerComponent @reload="GridApi.reload" />
    <ProcessDefinitionDeployDrawerComponent @reload="GridApi.reload" />
  </div>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>









