<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="数字人名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入数字人名称" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述"
        />
      </el-form-item>

      <el-form-item label="头像" prop="avatar_url">
        <el-upload
          class="avatar-uploader"
          action="/api/system/admin_upload/"
          :headers="uploadHeaders"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="form.avatar_url" :src="form.avatar_url" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { UpdateObj } from '../api';

const props = defineProps({
  modelValue: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = ref(props.modelValue);
const formRef = ref<FormInstance>();
const title = ref('编辑数字人');

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  description: '',
  avatar_url: '',
  status: 1,
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入数字人名称', trigger: 'blur' }],
  avatar_url: [{ required: true, message: '请上传头像', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// 上传相关
const uploadHeaders = {
  Authorization: `JWT ${localStorage.getItem('token') || ''}`
};

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleAvatarSuccess = (res: any) => {
  form.avatar_url = res.data.url;
};

// 初始化表单数据
const initForm = () => {
  Object.assign(form, props.rowData);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await UpdateObj(form);
        ElMessage.success('更新成功');
        emit('success');
        visible.value = false;
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新失败');
      }
    }
  });
};

// 关闭弹窗时重置表单
const handleClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('update:modelValue', false);
};

// 监听 visible 变化
watch(() => props.modelValue, (val) => {
  visible.value = val;
  if (val) {
    initForm();
  }
});

watch(() => visible.value, (val) => {
  emit('update:modelValue', val);
});
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 