<script setup lang="ts">
import { ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElButton, ElMessage, ElRadio } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import FaImageUpload from '@/ui/components/FaImageUpload/index.vue'
import { updateVoice } from '@/api/modules/voice'
// 定义表单数据类型
type IFormData  = {
    "id": string|undefined,
    "name": string,
    "photoUrl": string,
    "feature": string,
    "gender": number
}

// 定义组件的属性
interface Props {
  visible: boolean
  modelValue?: IFormData | null
  mode?: 'create' | 'edit'
}

// 定义组件的事件
interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'cancel'): void
  (e: 'refresh'): void
}

// 接收属性和事件
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  modelValue: null,
  mode: 'create'
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => {
    // 这里可以触发一个事件来通知父组件更新 visible 的值
    emit('update:visible', value);
  },
});


// 表单引用
const editFormRef = ref<FormInstance>();

const photos = ref<string[]>([])

// 响应式数据 - 直接定义所有必需字段
const formData = ref<IFormData>({
  photoUrl: '',
  name: '',
  feature: '',
  id: undefined,
  gender: 1,
});



// 监听 props.modelValue 变化
watch(() => props.modelValue, (newModelValue) => {
  if (newModelValue) {
    formData.value = {
      ...formData.value,
      ...newModelValue
    };
    console.log(formData.value,newModelValue,4444)
    photos.value = newModelValue.photoUrl ? [newModelValue.photoUrl] : []
  }
});

// 表单验证规则
const formRules = ref<FormRules>({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  photoUrl: [
    { required: true, message: '请输入描述', trigger: 'blur' },
  ],
})

// 监听可见性变化
watch(() => props.visible, (newVisible) => {
  if(!newVisible){
    resetForm()
  }
})


// 重置表单
function resetForm() {
  console.log('reset')
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  formData.value = {
    photoUrl: '',
    name: '',
    feature: '',
    id: undefined,
    gender: 1,
  }
}

// 处理确认
async function handleConfirm() {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    const defaultData = {
      id: '',
      name: '',
      photoUrl: '',
      feature: '',
      gender: 1,
    }
    const avatar =  photos.value?.[0] ?? ''
    // 字段全后再对齐字段
    //@ts-ignore
    const d: any = { ...defaultData, ...formData.value, photoUrl: avatar }
    console.log(d)
    const { code } = await updateVoice(d)
    if (code === 0) {
      ElMessage.success('操作成功')
      emit('refresh')
    }
    // 关闭对话框
    emit('update:visible', false)
  } catch (error) {
    // 验证失败，不做处理
  }
}


function handleCancel() {
  emit('cancel')
  emit('update:visible', false)
}


function handleClose() {
  emit('update:visible', false)
}


</script>
<template>
  <div>

    <ElDialog :title="mode === 'create' ? '创建声音' : '编辑声音'" v-model="dialogVisible" align-center @close="handleClose"
      width="800" :z-index="2000">
      <ElForm ref="editFormRef" :model="formData" :rules="formRules" label-width="120px" class="mt-4 space-y-4 w-full">

        <ElFormItem label="name" prop="name" label-width="120">
           <ElInput v-model="formData.name" placeholder="Enter name"  />
        </ElFormItem>
        <!-- <ElFormItem label="性别" prop="gender">
          <ElRadioGroup v-model="formData.gender">
            <ElRadio :value="1">男</ElRadio>
            <ElRadio :value="2">女</ElRadio>
            <ElRadio :value="3">其他</ElRadio>
          </ElRadioGroup>
        </ElFormItem> -->


        <ElFormItem label="feature" prop="feature" label-width="120">
           <ElInput type="textarea" v-model="formData.feature" placeholder="Enter feature"  />
        </ElFormItem>

        <!-- <ElFormItem label="use voice" prop="voiceName" label-width="120">
           <LLMSelector v-model="formData.voiceId" />
        </ElFormItem> -->


        <ElFormItem label="Avatar" prop="avatar" label-width="120">
          <FaImageUpload
            v-model="photos"
            :max-count="1"
            list-type="avatar"
          />
        </ElFormItem>


      </ElForm>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <ElButton @click="handleCancel">取消</ElButton>
          <ElButton type="primary" @click="handleConfirm">确定</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>
