<template>
  <BasicModal v-bind="$attrs" @register="registerSelectUserModal" @ok="handleSubmit" width="1000px">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  // import { getUserPageList } from '/@/api/system/user';
  import { useTable, FormSchema, BasicColumn, BasicTable } from '/@/components/Table';

  import { getRoleInterfaceList } from '/@/api/system/role';
  import { getAllInterface } from '/@/api/system/interface';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      componentProps: {
        placeholder: t('输入接口名称或接口地址搜索'),
      },
      colProps: { span: 8 },
    },
  ];

  export const columns: BasicColumn[] = [
    {
      title: t('名称'),
      dataIndex: 'name',
      width: 120,
    },
    {
      title: t('接口地址'),
      dataIndex: 'path',
      width: 120,
    },
    {
      title: t('请求类型'),
      dataIndex: 'method',
      width: 120,
    },
  ];

  export default defineComponent({
    name: 'SelectInterfaceModal',
    components: { BasicModal, BasicTable },
    props: {
      value: {
        type: String,
        default: '',
      },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const roleId = ref<string>();
      const selectIds = ref<string[]>([]);
      const [registerTable, { setSelectedRowKeys, getSelectRowKeys }] = useTable({
        api: getAllInterface,
        rowKey: 'id',
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
        },
        rowSelection: {
          type: 'checkbox',
          checkStrictly: false,
        },
        pagination: false,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
      });

      const [registerSelectUserModal, { setModalProps, closeModal }] = useModalInner(
        async (data) => {
          roleId.value = data.id;
          setModalProps({ confirmLoading: false, title: data.title });
          selectIds.value = await getRoleInterfaceList({ roleId: data.id });

          setSelectedRowKeys(selectIds.value || []);
        },
      );

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const selectRows = getSelectRowKeys();
          closeModal();
          emit('success', selectRows);
        } catch (error) {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerSelectUserModal, registerTable, handleSubmit, t };
    },
  });
</script>
