<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button
          type="primary"
          v-auth="'xslmes:mes_xsl_mixer_ps_compile:add'"
          @click="handleAdd"
          preIcon="ant-design:plus-outlined"
        >
          新增
        </a-button>
        <!-- update-begin---author:GHT ---date:2026-06-05 for：【XSLMES-20260605-K8R2】校对/审核/批准改由审批流+集成方案驱动，列表不再提供手工操作入口 -->
        <!-- update-end---author:GHT ---date:2026-06-05 for：【XSLMES-20260605-K8R2】校对/审核/批准改由审批流+集成方案驱动 -->
        <a-button
          type="primary"
          v-auth="'xslmes:mes_xsl_mixer_ps_compile:exportXls'"
          preIcon="ant-design:export-outlined"
          @click="onExportXls"
        >
          导出
        </a-button>
        <j-upload-button
          type="primary"
          v-auth="'xslmes:mes_xsl_mixer_ps_compile:importExcel'"
          preIcon="ant-design:import-outlined"
          @click="onImportXls"
        >
          导入
        </j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0 && hasCompileSelection">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'xslmes:mes_xsl_mixer_ps_compile:deleteBatch'">
            批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              onClick: handleEdit.bind(null, record),
              auth: 'xslmes:mes_xsl_mixer_ps_compile:edit',
              ifShow: isCompileStatus(record),
            },
          ]"
          :dropDownActions="getDropDownAction(record)"
        />
      </template>
    </BasicTable>
    <MesXslMixerPsCompileModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="xslmes-mesXslMixerPsCompile" setup>
  import { computed, reactive } 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 Icon from '/@/components/Icon';
  import MesXslMixerPsCompileModal from './components/MesXslMixerPsCompileModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './MesXslMixerPsCompile.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getExportUrl,
    getImportUrl,
  } from './MesXslMixerPsCompile.api';

  const { createMessage } = useMessage();

  const queryParam = reactive<any>({});
  const [registerModal, { openModal }] = useModal();

  const { tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '密炼PS编制',
      api: list,
      columns,
      canResize: true,
      tableSetting: { cacheKey: 'mesXslMixerPsCompile_v20260520' },
      formConfig: {
        schemas: searchFormSchema,
        labelWidth: 90,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
      },
      actionColumn: {
        title: '操作',
        dataIndex: 'action',
        width: 160,
        fixed: 'right',
        slots: { customRender: 'action' },
      },
      beforeFetch: (params) => Object.assign(params, queryParam),
    },
    exportConfig: {
      name: '密炼PS编制',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;
  const superQueryConfig = reactive(superQuerySchema);

  const isCompileStatus = (record?: Recordable) => !record?.status || record.status === 'compile';

  const hasCompileSelection = computed(
    () => selectedRows.value.length > 0 && selectedRows.value.every((row) => isCompileStatus(row)),
  );

  function handleSuperQuery(params) {
    Object.keys(params).forEach((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

  function handleAdd() {
    openModal(true, { isUpdate: false, showFooter: true });
  }

  function handleEdit(record: Recordable) {
    if (record.status && record.status !== 'compile') {
      createMessage.warning('仅编制状态的单据允许编辑');
      return;
    }
    openModal(true, { record, isUpdate: true, showFooter: true });
  }

  function handleDetail(record: Recordable) {
    openModal(true, { record, isUpdate: true, showFooter: false });
  }

  function handleDelete(record: Recordable) {
    if (!isCompileStatus(record)) {
      createMessage.warning('仅编制状态的单据允许删除');
      return;
    }
    deleteOne({ id: record.id }, handleSuccess);
  }

  function batchHandleDelete() {
    if (!hasCompileSelection.value) {
      createMessage.warning('仅编制状态的单据允许删除，请取消已流转记录的勾选');
      return;
    }
    batchDelete({ ids: selectedRowKeys.value.join(',') }, handleSuccess);
  }

  function handleSuccess() {
    reload();
    selectedRowKeys.value = [];
  }

  function getDropDownAction(record: Recordable) {
    return [
      { label: '详情', onClick: handleDetail.bind(null, record) },
      {
        label: '删除',
        popConfirm: { title: '是否确认删除', confirm: handleDelete.bind(null, record) },
        auth: 'xslmes:mes_xsl_mixer_ps_compile:delete',
        ifShow: isCompileStatus(record),
      },
    ];
  }
</script>
