<!-- eslint-disable no-use-before-define -->
<script setup lang="ts">
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 { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { ElMessage, ElMessageBox, ElPopconfirm, ElRadioGroup, ElSpace, ElSwitch } from 'element-plus';

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

import CategoryTree from './category-tree.vue';
import { columns, querySchema } from './data';
import processDefinitionDeployModal from './process-definition-deploy-modal.vue';
import processDefinitionModal from './process-definition-modal.vue';

// 左边部门用
const selectedCode = ref<number[] | string[]>([]);

const formOptions: VbenFormProps = {
  schema: querySchema(),
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  handleReset: async () => {
    selectedCode.value = [];
    const { formApi, reload } = tableApi;
    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,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 部门树选择处理
        if (selectedCode.value.length === 1) {
          formValues.category = selectedCode.value[0];
        } else {
          Reflect.deleteProperty(formValues, 'category');
        }

        return await currentTableApi.value({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  headerCellConfig: {
    height: 44,
  },
  cellConfig: {
    height: 100,
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'workflow-definition-index',
};

const [BasicTable, tableApi] = 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.target.value as number;
  await tableApi.reload();
}

async function handleDelete(row: Recordable<any>) {
  await ElMessageBox.confirm({
    title: '提示',
    content: `确认删除流程[${row.flowName}]吗？`,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  await workflowDefinitionDelete(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: any) => row.id);
  ElMessageBox.confirm({
    title: '提示',
    content: `确认删除选中的${ids.length}条记录吗？`,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await workflowDefinitionDelete(ids);
    await tableApi.query();
  });
}

const router = useRouter();
/**
 * 流程设计/预览
 * @param row row
 * @param _disabled true为预览，false为设计
 */
function handleDesign(row: any, _disabled: boolean) {
  router.push({
    path: '/workflow/design/index',
    query: { definitionId: row.id },
  });
}

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

/**
 * 发布流程
 * @param row row
 */
async function handlePublish(row: any) {
  await workflowDefinitionPublish(row.id);
  await tableApi.query();
}

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

const [ProcessDefinitionDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: processDefinitionModal,
});

/**
 * 新增流程
 */
function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

/**
 * 编辑流程
 */
function handleEdit(row: any) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

/**
 * 导出xml
 * @param row row
 */
async function handleExportXml(row: any) {
  const hideLoading = ElMessage.loading({ message: $t('pages.common.downloadLoading'), duration: 0 });
  try {
    const blob = await workflowDefinitionExport(row.id);
    downloadByData(blob, `${row.flowName}-${Date.now()}.json`);
  } catch (error) {
    console.error(error);
  } finally {
    hideLoading();
  }
}

const [ProcessDefinitionDeployDrawer, deployDrawerApi] = useVbenDrawer({
  connectedComponent: processDefinitionDeployModal,
});

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

// 部署流程json
async function handleDeploySuccess() {
  // 跳转到未发布
  currentStatus.value = 0;
  await tableApi.reload();
}

// 新增完成需要跳转到未发布
async function handleReload(type: 'add' | 'update') {
  if (type === 'add') {
    currentStatus.value = 0;
  }
  await tableApi.reload();
}
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-[8px]">
      <CategoryTree
        v-model:select-code="selectedCode"
        class="w-[260px]"
        @reload="() => tableApi.reload()"
        @select="() => tableApi.reload()"
      />
      <BasicTable class="flex-1 overflow-hidden">
        <template #toolbar-actions>
          <ElRadioGroup
            v-model="currentStatus"
            @change="handleStatusChange"
          >
            <el-radio-button v-for="option in statusOptions" :key="option.value" :label="option.value">
              {{ option.label }}
            </el-radio-button>
          </ElRadioGroup>
        </template>
        <template #toolbar-tools>
          <ElSpace>
            <el-button
              :disabled="!vxeCheckboxChecked(tableApi)"
              type="danger"
              v-access:code="['system:user:remove']"
              @click="handleMultiDelete"
            >
              {{ $t('pages.common.delete') }}
            </el-button>
            <el-button v-access:code="['system:user:add']" @click="handleDeploy">
              部署
            </el-button>
            <el-button
              type="primary"
              v-access:code="['system:user:add']"
              @click="handleAdd"
            >
              {{ $t('pages.common.add') }}
            </el-button>
          </ElSpace>
        </template>
        <template #activityStatus="{ row }">
          <ElSwitch
            v-model="row.activityStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="激活"
            inactive-text="挂起"
            @change="(status) => handleActive(row, status)"
          />
        </template>
        <template #action="{ row }">
          <div class="flex flex-col gap-1">
            <div>
              <el-button size="small" type="text" @click="handleEdit(row)">
                编辑信息
              </el-button>
              <ElPopconfirm
                :teleported="false"
                placement="left"
                title="确认删除？"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button danger size="small" type="text">
                    删除流程
                  </el-button>
                </template>
              </ElPopconfirm>
            </div>
            <div>
              <el-button
                size="small"
                type="text"
                @click="handleDesign(row, !!row.isPublish)"
              >
                {{ row.isPublish ? '查看流程' : '设计流程' }}
              </el-button>
              <ElPopconfirm
                :teleported="false"
                placement="left"
                :title="`确认发布流程[${row.flowName}]?`"
                @confirm="handlePublish(row)"
              >
                <template #reference>
                  <el-button v-if="!row.isPublish" size="small" type="text">
                    发布流程
                  </el-button>
                </template>
              </ElPopconfirm>
            </div>
            <div>
              <ElPopconfirm
                :teleported="false"
                placement="left"
                :title="`确认复制流程[${row.flowName}]?`"
                @confirm="handleCopy(row)"
              >
                <template #reference>
                  <el-button size="small" type="text"> 复制流程 </el-button>
                </template>
              </ElPopconfirm>
              <el-button size="small" type="text" @click="handleExportXml(row)">
                导出流程
              </el-button>
            </div>
          </div>
        </template>
      </BasicTable>
    </div>
    <ProcessDefinitionDrawer @reload="handleReload" />
    <ProcessDefinitionDeployDrawer @reload="handleDeploySuccess" />
  </Page>
</template>
