<template>
  <div class="query-table">
    <query-form :init-data="initQuery" @search="handleSearch" @reset="handleSearch">
      <template v-slot="slotProps">
        <slot name="search" :formData="slotProps.formData"></slot>
      </template>
    </query-form>
    
    <cell>
      <template #default>
        <slot name="title"></slot>
      </template>
      <template #action>
        <slot name="action"></slot>
      </template>
    </cell>

    <el-table
      :data="modelValue"
      row-key="rowKey"
      v-loading="loading"
      border
      stripe
      style="width: 100%">
      <slot name="table"></slot>
    </el-table>
    <Pagination :config="pagination" @pageChange="handlePageChange" />
  </div>
</template>

<script>
import { watch, ref } from 'vue'
import Pagination from '../Pagination/index.vue'

export default {
  components: {
    Pagination,
  },

  props: {
    initQuery: Object,
    modelValue: Array,
    rowKey: [String, Function],
    request: Function,
  },

  setup(props, context) {
    const loading = ref(false)
    const pagination = ref({ current: 1, pageSize: 10, total: 0 })
    const queryParams = ref({})

    const handleSearch = formData => {
      queryParams.value = {
        ...queryParams.value,
        ...formData,
        pageNum: 1,
      }
    }

    const handlePageChange = page => {
      pagination.current = page
      queryParams.value = {
        ...queryParams.value,
        pageNum: page,
      }
    }

    watch(queryParams, () => {
      loading.value = true
      props.request(queryParams.value).then(res => {
        const { records, ...page } = res
        
        context.emit('update:modelValue', records)
        pagination.value = {
          current: page.current,
          pageSize: page.size,
          total: page.total
        }
        loading.value = false
      }).catch(e => {
        console.error(e)
        loading.value = false
      })
    }, {immediate: true, deep:true})
    
    return {
      loading,
      pagination,
      handleSearch,
      handlePageChange,
    }
  }
}
</script>
