<script setup lang="ts">
import { ref, shallowRef } from "vue";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import Modal from "./modal.vue"
import { ElMessage } from "element-plus";

import { httpStatus } from "/@/api/serviceParam/supplierCat";
import { useTask } from "/@/hooks/core";

const PageName = "supplierCat";
const instance = ref<any>(null);
const visible = shallowRef(false)

const selection = ref([])

const hooks: PageHooks = { pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig) };
const events: PageEvents = { content: { create(){ visible.value = true } }};

const statusTask = useTask()

async function selectionChange(status = '1'){
  try{
    if(selection.value.length === 0){
      ElMessage.warning('请选择至少一条记录')
      return 
    }

    const statusSet = [...new Set(selection.value.map(({ status }) => status))]
    const text = status == '1' ? '启用' : '禁用'


    if(statusSet.length !== 1){
      ElMessage.warning('所选分类应全部为启用/禁用数据')
      return
    }

    if(statusSet[0] == status){
      ElMessage.warning(`所选分类数据已经${text},无需操作${text}功能`)
      return
    }

    const id = selection.value.map(({id}) => id)
    await statusTask.run(httpStatus({ id, status }))
    ElMessage.success(`${text}成功`)
    instance.value?.onSearch()
  }catch(err){}
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer
      :hooks="hooks"
      :events="events"
      :content-config="contentConfig"
      :search-config="searchConfig"
      :get-content-ref="ref => (instance = ref)"
      @content-select-change="(selected: any[]) => selection = selected"
    >
    <template #content_header>
        <ElButton size="small" type="success" @click="selectionChange('1')">批量启用</ElButton>
        <ElButton size="small" type="danger" @click="selectionChange('0')">批量禁用</ElButton>
      </template>
    </PageContainer>

    <Modal 
      v-model:visible="visible" 
      @refresh="instance?.onSearch()" 
    />
  </PageAuth>
</template>
