<script setup lang="ts">
import { AddrQuery } from "/@/components/BasicForm"
import { computed, watch, ref } from "vue"
import { rules } from "../config/_options"
import { useVModel } from "@vueuse/core"
import { ElForm } from "element-plus"


const emit = defineEmits(['submit'])
const props = defineProps<{ visible: boolean, index: number, data: any }>()

const visible = useVModel(props, 'visible')
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const addrQueryRef = ref<InstanceType<typeof AddrQuery> | null>(null)
const formData = ref({ receipt_quantity: '', contactor: '', addr_code: '', mobile: '', addr: '' })

const title = computed(() => {
  const { index } = props
  const base = index === -1 ? '添加' : '编辑'
  return `${base}收货信息`
})

watch(() => props.visible, async () => {
  if(!props.visible) { return }

  const { 
    receipt_quantity = 1, 
    contactor = '',
    addr_code = '',
    mobile = '',
    addr_name = '',
    addr = ''
  } = props.data

  formData.value = {
    receipt_quantity,
    addr_name,
    addr_code,
    contactor,
    mobile,
    addr
   }


   if(addr_name){
    const result = await addrQueryRef.value.getRecurrentValue({ name: addr_name })
    formData.value = result
  }
})


function handleAddrChange({ search_name = '' }){ formData.value.addr_name = search_name }

async function onSubmit(){
  try{
    await formRef.value?.validate()
    emit('submit', formData.value, props.index)
    visible.value = false
  }catch (err) {
    console.log(err)
  }
}
</script>

<template>
  <ElDialog v-model="visible" :title="title" center>
    <ElForm ref="formRef" label-width="110px" :model="formData" :rules="rules">
      <ElFormItem label="收货总数" prop="receipt_quantity">
        <ElInputNumber
          :min="1"
          v-model="formData.receipt_quantity"
          style="width: 100%" 
          placeholder="收货总数" 
          controls-position="right" 
        />
      </ElFormItem>

      <ElFormItem label="收货联系人" prop="contactor">
        <ElInput 
          v-model="formData.contactor"
          placeholder="收货联系人"
        />
      </ElFormItem>

      <ElFormItem label="收货联系电话" prop="mobile">
        <ElInput 
          v-model="formData.mobile" 
          placeholder="收货联系电话"
          :maxlength="11"
        />
      </ElFormItem>

      <ElFormItem label="收货省市区" prop="addr_code">
        <AddrQuery
          ref="addrQueryRef"
          v-model="formData.addr_code"
          @change="handleAddrChange"
          placeholder="收货省市区"  
          :level="3"
       />
      </ElFormItem>

      <ElFormItem label="详细地址" prop="addr">
        <ElInput v-model="formData.addr" placeholder="详细地址" />
      </ElFormItem>

      <ElFormItem>
        <div class="w-full flex justify-end">
          <ElButton 
            type="primary" 
            @click="onSubmit"
          >保存</ElButton>
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>
