<script setup lang="ts">
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { useVModel } from "@vueuse/core";
import { ElDialog, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { ref } from "vue";
import { cloneDeep, keys } from "lodash";
import { watch } from "vue";

const props = defineProps<{ visible: boolean; otherSearchParameter?: any }>()
const emit = defineEmits(['submit'])

const visible = useVModel(props, 'visible')

const router = useRouter();

const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig)
};

const searchConfigRef = ref(cloneDeep(searchConfig))

const selection= ref([])

const events: PageEvents = {
  content: {
    preview: ({ id }) => router.push("/invoiceInOut/productManagerDetail?id=" + id),
    create: () => router.push('/invoiceInOut/productManagerDetail')
  }
};

function handleSubmit(){
   if(selection.value.length === 0){
       ElMessage.warning('请选择至少一个子商品')
       return
   }

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

watch(() => props.otherSearchParameter, () =>{
  if(!props.otherSearchParameter) return
  const keys = ['timer', 'skuCode', ...Object.keys(props.otherSearchParameter)]
  searchConfigRef.value.formItems = searchConfig.formItems.filter(item => keys.includes(item.field))
},{
  deep: true,
  immediate: true
})
</script>

<template>
  <ElDialog class="reactive" v-model="visible" title="选择商品" center top="10px">
    <PageContainer 
      :only-self="true" 
      v-if="visible" 
      :hooks="hooks" 
      :events="events" 
      :searchConfig="searchConfigRef"
      :contentConfig="contentConfig" 
      :isPageStart="true"
      :other-search-parameter="otherSearchParameter"
      @content-select-change="values => selection = values.map(item => ({ ...item, child_num: '1', child_id: item.id }))" />
    <ElButton class="absolute bottom-[30px] right-[20px]" type="primary" @click="handleSubmit">保存 </ElButton>
  </ElDialog>
</template>
