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

   const result = []
   selection.value.forEach(single => {
      if (single.ProductsCombind.length === 0) { 
        result.push({ ...single, goodNum: 1 })
      } else {
        single.ProductsCombind.forEach(child => {
          result.push({ ...single, spbl: 1 ,goodNum: 1, childCode: child.products.skuCode, childNum: single.child_num, childActionNum: single.child_num })
        })
      }
   })

   visible.value = false
   emit('submit', result)
}
</script>

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