<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" v-auth="'xslmes:mes_xsl_integration_plan:add'" preIcon="ant-design:plus-outlined" @click="handleAdd">
          新增方案
        </a-button>
        <a-button
          v-auth="'xslmes:mes_xsl_integration_plan:edit'"
          preIcon="ant-design:thunderbolt-outlined"
          style="margin-left: 8px"
          @click="handleGenerateDefault"
        >
          按流程生成默认方案
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableActions(record)" :dropDownActions="getDropDownActions(record)" />
      </template>
    </BasicTable>
    <MesXslIntegrationPlanModal @register="registerModal" @success="handleSuccess" />
    <MesXslIntegrationActionDrawer ref="actionDrawerRef" />
    <MesXslIntegrationPlanWizard ref="wizardRef" @success="handleSuccess" />
    <GenerateDefaultPlanModal ref="generateModalRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="xslmes-mesXslIntegrationPlan" setup>
  import { ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import MesXslIntegrationPlanModal from './components/MesXslIntegrationPlanModal.vue';
  import MesXslIntegrationActionDrawer from './components/MesXslIntegrationActionDrawer.vue';
  import MesXslIntegrationPlanWizard from './MesXslIntegrationPlanWizard.vue';
  import GenerateDefaultPlanModal from './components/GenerateDefaultPlanModal.vue';
  import { columns, searchFormSchema } from './MesXslIntegrationPlan.data';
  import { list, deleteOne, publishPlan, disablePlan } from './MesXslIntegrationPlan.api';

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const actionDrawerRef = ref();
  const wizardRef = ref();
  const generateModalRef = ref();

  const { tableContext } = useListPage({
    tableProps: {
      title: '集成方案管理',
      api: list,
      columns: [
        ...columns,
        // 状态列用 tag 渲染覆盖默认
      ],
      canResize: true,
      formConfig: {
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: false,
      },
      actionColumn: { width: 200, fixed: 'right' },
      customRow: () => ({}),
    },
  });

  const [registerTable, { reload }] = tableContext;

  function handleAdd() {
    wizardRef.value?.open();
  }

  function handleGenerateDefault() {
    generateModalRef.value?.open();
  }

  function handleEdit(record: Recordable) {
    openModal(true, { record, isUpdate: true });
  }

  function handleManageActions(record: Recordable) {
    actionDrawerRef.value?.open(record);
  }

  async function handlePublish(record: Recordable) {
    try {
      await publishPlan(record.id);
      createMessage.success('发布成功');
      reload();
    } catch (e: any) {
      createMessage.error(e?.message || '发布失败');
    }
  }

  async function handleDisable(record: Recordable) {
    try {
      await disablePlan(record.id);
      createMessage.success('已停用');
      reload();
    } catch (e: any) {
      createMessage.error(e?.message || '停用失败');
    }
  }

  async function handleDelete(record: Recordable) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  function handleSuccess() {
    reload();
  }

  function getTableActions(record: Recordable) {
    const actions: any[] = [
      { label: '编辑', onClick: handleEdit.bind(null, record), auth: 'xslmes:mes_xsl_integration_plan:edit', disabled: record.status === '1' },
      { label: '管理动作', icon: 'ant-design:setting-outlined', onClick: handleManageActions.bind(null, record) },
    ];
    if (record.status === '0' || record.status === '2') {
      actions.push({
        label: '发布',
        color: 'success',
        auth: 'xslmes:mes_xsl_integration_plan:publish',
        onClick: handlePublish.bind(null, record),
      });
    }
    if (record.status === '1') {
      actions.push({
        label: '停用',
        color: 'error',
        auth: 'xslmes:mes_xsl_integration_plan:publish',
        onClick: handleDisable.bind(null, record),
      });
    }
    return actions;
  }

  function getDropDownActions(record: Recordable) {
    return [
      {
        label: '删除',
        auth: 'xslmes:mes_xsl_integration_plan:delete',
        disabled: record.status === '1',
        popConfirm: {
          title: '确认删除该方案（同时删除所有动作）？',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
      },
    ];
  }
</script>
