<template>
  <a-modal
    v-if="asDialog"
    v-model:visible="innerVisible"
    title="选择依据"
    :width="1500"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :centered="true"
  >
    <div style="padding: 0px">
      <a-space style="margin: 0px 0px 8px 10px" v-if="isDetailView">
        <a-button @click="backToMainTable">返回</a-button>
      </a-space>
      <a-table
        v-if="!isDetailView"
        :columns="config?.columns"
        :data-source="mainData"
        row-key="id"
        :pagination="pagination"
        @change="handleTableChange"
        style="height: 400px; overflow-y: auto"
      />
      <a-table
        v-else
        style="height: 400px; overflow-y: auto"
        :columns="detailConfig?.columns"
        :data-source="detailConfig?.data"
        row-key="id"
        :row-selection="
          detailConfig.enableRowSelection
            ? {
                selectedRowKeys: selectedRowKeys,
                onChange: handleRowSelectionChange,
              }
            : null
        "
        :pagination="false"
      />
    </div>
  </a-modal>
  <div v-else v-show="visible">
    <a-space style="margin: 0px 0px 8px 10px" v-if="isDetailView">
      <a-button @click="backToMainTable">返回</a-button>
    </a-space>
    <a-table
      v-if="!isDetailView"
      :columns="config?.columns"
      :data-source="mainData"
      row-key="id"
      :pagination="pagination"
      @change="handleTableChange"
      style="height: 400px; overflow-y: auto"
    />
    <a-table
      v-else
      style="height: 400px; overflow-y: auto"
      :columns="detailConfig?.columns"
      :data-source="detailConfig?.data"
      row-key="id"
      :row-selection="
        detailConfig.enableRowSelection
          ? {
              selectedRowKeys: selectedRowKeys,
              onChange: handleRowSelectionChange,
            }
          : null
      "
      :pagination="false"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, defineExpose, watch } from 'vue';

  const props = defineProps({
    asDialog: {
      type: Boolean,
      default: true,
    },
    visible: {
      type: Boolean,
      default: true,
    },
    autoLoad: { type: Boolean, default: false },
  });
  // 监听 visible，自动加载内容
  watch(
    () => props.visible,
    async (val) => {
      if (val && !props.asDialog && props.autoLoad && config.value) {
        // 只在非弹窗、autoLoad为true时触发
        isDetailView.value = false;
        // await loadMainData();
        mainData.value = await config.value.fetchData(1, 10);
      }
    }
  );

  const emit = defineEmits(['save']);

  const innerVisible = ref(false);
  const isDetailView = ref(false);
  const mainData = ref([]);
  const detailConfig = ref<any>(null);
  const config = ref<any>(null);
  const resolvePromise = ref<any>(null);
  const selectedRowKeys = ref<number[]>([]);
  const selectedRows = ref<any[]>([]);
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共 ${total} 条`,
    showQuickJumper: true,
    showSizeChanger: true,
  });

  // 打开主表
  async function openSelector(options: { multiple?: boolean; config: any }) {
    config.value = options.config;
    isDetailView.value = false;
    pagination.value.current = 1; // 打开时重置页码
    await loadMainData();
    return new Promise((resolve) => {
      resolvePromise.value = resolve;
      // 仅弹窗模式下显示
      if (props.asDialog) {
        innerVisible.value = true;
      }
    });
  }
  const loadMainData = async () => {
    const page = pagination.value.current;
    const pageSize = pagination.value.pageSize;
    const res = await config.value.fetchData(page, pageSize);
    mainData.value = res.records;
    pagination.value.total = res.total;
  };

  const handleTableChange = (paginationInfo: any) => {
    pagination.value.current = paginationInfo.current;
    pagination.value.pageSize = paginationInfo.pageSize;
    loadMainData();
  };

  // 展示详情表
  function setDetail(detail: { title?: string; columns: any[]; data: any[] }) {
    detailConfig.value = detail;
    isDetailView.value = true;
  }

  // 返回主表
  function backToMainTable() {
    isDetailView.value = false;
  }

  function handleCancel() {
    innerVisible.value = false;
  }
  function handleRowSelectionChange(keys: any[], rows: any[]) {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
  }
  const handleOk = () => {
    if (resolvePromise.value) {
      resolvePromise.value({
        selectedRows: selectedRows.value,
        selectedRowKeys: selectedRowKeys.value,
      });
      emit('save', selectedRowKeys.value);
    }
    innerVisible.value = false;
  };
  function unselectRowById(id: number) {
    const index = selectedRowKeys.value.indexOf(id);
    if (index !== -1) {
      selectedRowKeys.value.splice(index, 1);
      selectedRows.value = selectedRows.value.filter((row) => row.id !== id);
    }
  }
  defineExpose({
    openSelector,
    setDetail,
    handleOk,
    unselectRowById,
  });
</script>

<style scoped>
  .ant-table-wrapper {
    margin-bottom: 16px;
  }
</style>
