<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; goodType?: string; source?: string }>()
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 skuCodes = [...new Set(selection.value.map(({ goodNo }) => goodNo))]
  if (skuCodes.length !== 1) {
    ElMessage.warning('选择的订单的商品编号必须一致')
    return
  }

  const types = [...new Set(selection.value.map(({ goodType }) => goodType))]
  const sources = [...new Set(selection.value.map(({ source }) => source))]

  if (types.length !== 1 || sources.length !== 1) {
    ElMessage.warning('选择订单的商品类型和商品来源必须一致')
    return
  }

  if(props.goodType){
    selection.value.some(item => item.goodType !== props.goodType || item.source !== props.source)
    ElMessage.warning('选择的订单商品类型和商品来源与已选择的订单不一致')
    return
  }

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

<template>
    <ElDialog class="relative" v-model="visible" title="选择C端无发票订单" center top="10px">
      <PageContainer
        v-if="visible"
        :hooks="hooks"
        :events="events"
        :searchConfig="searchConfig"
        :contentConfig="contentConfig"
        :isPageStart="true"
        @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>
