<script setup lang="tsx">
import { FormSchema } from '@/components/Form'
import { apiRuleList } from '@/api/system/menu'
import { ElDrawer } from 'element-plus'
import { reactive, ref } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await apiRuleList()
    if (searchParams.value) {
      const list: Record<string, any>[] = [] // 显式指定类型
      res.data.forEach((item: any) => {
        console.log(
          item.real_name.indexOf(searchParams.value),
          'item.real_name.indexOf(searchParams.value)'
        )
        if (item.real_name.indexOf(searchParams.value) !== -1) {
          list.push(item)
        }
      })
      return {
        list: list || []
      }
    } else {
      return {
        list: res.data || []
      }
    }
  }
})
const { getList } = tableMethods

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'title',
    label: '接口名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入接口名称'
    }
  }
])
const { dataList, loading } = tableState

const searchParams = ref('')
const setSearchParams = (data: any) => {
  searchParams.value = data.title
  getList()
}

const modelValue = defineModel<boolean>()

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'method',
    label: '请求',
    width: '60px'
  },
  {
    field: 'rule',
    label: '接口地址',
    width: '330px'
  },
  {
    field: 'real_name',
    label: '接口名'
  },
  {
    field: 'action',
    label: '操作',
    width: '90px',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => confirm(row)}>
              选择
            </BaseButton>
          </>
        )
      }
    }
  }
])

const emit = defineEmits(['confirm'])
const confirm = (row: any) => {
  emit('confirm', row)
}
</script>

<template>
  <ElDrawer v-model="modelValue" title="选择接口" size="700px">
    <ContentWrap>
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

      <Table
        :columns="tableColumns"
        default-expand-all
        node-key="id"
        stripe
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
      />
    </ContentWrap>
    <template #footer>
      <div>
        <BaseButton @click="() => (modelValue = false)">关闭</BaseButton>
      </div>
    </template>
  </ElDrawer>
</template>
