<template>
  <a-modal
    :width="800"
    :visible="props.multipleDialog"
    title="弹窗配置"
    :destroyOnClose="true"
    @ok="submitDialog"
    @cancel="closeDialog"
    :okText="t('确认')"
    :cancelText="t('取消')"
    :bodyStyle="{ padding: '16px 16px 0' }"
  >
    <a-spin :spinning="state.spinning">
      <a-table
        :dataSource="state.dataSourceList"
        :columns="sourceColumns"
        :pagination="paginationProps"
        rowKey="id"
        :row-selection="{
          selectedRowKeys: [selectedRowKeys],
          onChange: onSelectChange,
          type: 'radio',
          getCheckboxProps: () => ({
            disabled: disabled,
          }),
        }"
        :scroll="{ y: '500px' }"
      />
    </a-spin>
  </a-modal>
</template>

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

  import type { ColumnProps } from 'ant-design-vue/lib/table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getModalManagePage } from '/@/api/dataconfig/modalmanage';
  const { t } = useI18n();
  const props = defineProps({
    multipleDialog: { type: Boolean },
    value: {
      type: String,
    },
    disabled: { type: Boolean, default: false },
  });
  const emit = defineEmits(['update:multipleDialog', 'update:value', 'submit']);

  onMounted(async () => {
    selectedRowKeys.value = props.value;
    await getDatasourceList(1, paginationProps.pageSize);
  });

  const state = reactive({
    dataSourceList: [] as any[],
    spinning: false,
  });
  const selectedRowKeys = ref();
  const sourceColumns: ColumnProps[] = [
    {
      resizable: true,
      dataIndex: 'code',
      title: '编码',
    },
    {
      resizable: true,
      dataIndex: 'name',
      title: '名称',
    },
    {
      resizable: true,
      dataIndex: 'category',
      title: '弹窗分类',
    },
    {
      resizable: true,
      dataIndex: 'remark',
      title: '备注',
    },
  ];

  const paginationProps = reactive({
    current: 1,
    total: 0,
    pageSize: 10,
    showQuickJumper: true,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '30', '40', '50'],
    onChange: (page, pageSize) => getDatasourceList(page, pageSize),
    showTotal: (total) => {
      return `共 ${total} 条`;
    },
  });

  const closeDialog = () => {
    emit('update:multipleDialog', false);
  };

  const submitDialog = () => {
    emit('update:multipleDialog', false);
    emit('update:value', selectedRowKeys.value);
    emit('submit', selectedRowKeys.value);
  };

  const getDatasourceList = async (page, pageSize) => {
    state.spinning = true;
    paginationProps.current = page;
    paginationProps.pageSize = pageSize;
    let res = await getModalManagePage({ limit: page, size: pageSize });
    state.dataSourceList = res.list || [];
    paginationProps.total = res.total;
    state.spinning = false;
  };

  const onSelectChange = (rowKeys) => {
    selectedRowKeys.value = rowKeys[0];
  };
</script>
