<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;
  skuCode?: string
  isJT: boolean
}>()

  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 selectNoTotal = selection.value.filter(({ residue_stock }) => !residue_stock)
  // if (selectNoTotal.length !== 0) {
  //   ElMessage.warning(`商品${selectNoTotal.map(({ skuCode }) => skuCode).join('、')}结存数量为空`)
  //   return
  // }

   if(props.isJT){
     if(selection.value.length > 1){
       ElMessage.warning('只能选择一条计提商品')
       return
     }
   } else {
     const skuCodes = [...new Set(selection.value.map(({ skuCode }) => skuCode))]
     if (skuCodes.length !== 1) {
       ElMessage.warning('选择的商品的商品编号必须一致')
       return
     }

     if (props.skuCode && skuCodes[0] !== props.skuCode) {
       ElMessage.warning('选择的商品的商品编号必须和当前选择商品的商品编号必须一致')
       return
     }
   }

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

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

<template>
  <ElDialog class="relative" v-model="visible" :title="isJT ? '添加计提商品' : '选择商品'" 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 }))" />
    <ElButton class="absolute bottom-[30px] right-[20px]" type="primary" @click="handleSubmit">保存 </ElButton>
  </ElDialog>
</template>
