<script setup lang="ts">
import { ref , watch } from "vue"
import { httpCatList } from "/@/api/serviceParam/supplierCat"
import { useVModel } from "@vueuse/core"
import { useTask } from "/@/hooks/core"

import { ElMessage } from "element-plus"


const initialParameter = { page: 1, size: 10,  level: 3, total: 0 , search: '', pid: '' }
const props = defineProps<{ visible: boolean }>()
const emit = defineEmits(['change'])

const selection = ref<any[]>([])
const parameter = ref({ ...initialParameter })
const visible = useVModel(props, 'visible')
const categoryTask = useTask({ initialData: [], success(data: any){ parameter.value.total = data.count }})
const requestCategorylist = () => categoryTask.run(httpCatList(parameter.value))

function onSubmit(){
  if(selection.value.length === 0){
    ElMessage.warning('至少选择一个分类')
    return
  }

  visible.value = false
  emit('change', selection.value)
}

watch(() => visible.value, () => {
  if(!visible.value) { return }
  requestCategorylist()
})
</script>

<template>
  <ElDialog v-model="visible" title="添加分类" center @close="parameter = {...initialParameter}">
    <div class="flex flex-col" v-loading="categoryTask.loading">
      <div class="flex mb-[10px]">
        <ElInput placeholder="分类名" v-model="parameter.search" clearable @change="requestCategorylist" />
      </div>

      <ElTable 
        border 
        size="small" 
        :data="categoryTask.data.list"
        @selection-change="val => selection = val"
      >
        <ElTableColumn type="selection" width="40px" />
        <ElTableColumn type="index" width="50px" label="序号" />
        <ElTableColumn prop="search" label="分类名称" show-overflow-tooltip />
      </ElTable>

       <div class="flex justify-between mt-[10px]">
          <ElPagination
            v-model:current-page="parameter.page"
            v-model:page-size="parameter.size"
            @size-change="requestCategorylist"
            @current-change="requestCategorylist"
            :page-sizes="[10, 30, 50, 100]"
            layout="sizes, prev, pager, next"
            :total="parameter.total"
            :size="'small'"
            background
          />

          <ElButton 
            type="primary" 
            @click="onSubmit"
          >保存</ElButton>
        </div>
      </div>
  </ElDialog>
</template>
