<template>
  <fs-page>
    <div class="digital-human-detail">
      <!-- 顶部操作栏 -->
      <div class="detail-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2 class="detail-title">{{ digitalHuman.name || '数字人详情' }}</h2>
        <div class="detail-actions">
          <el-button type="primary" @click="openEditForm" v-if="canEdit">编辑</el-button>
        </div>
      </div>

      <!-- 详情内容区 -->
      <div class="detail-content" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="avatar-container">
              <img :src="digitalHuman.avatar_url" alt="数字人头像" class="avatar-image" v-if="digitalHuman.avatar_url">
              <div class="avatar-placeholder" v-else>暂无头像</div>
            </div>
          </el-col>
          <el-col :span="18">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="名称">{{ digitalHuman.name }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="digitalHuman.status === 1 ? 'success' : 'danger'">
                  {{ digitalHuman.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="语音ID">{{ digitalHuman.config?.voice_id }}</el-descriptions-item>
              <el-descriptions-item label="风格">{{ digitalHuman.config?.style }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{ digitalHuman.creator_name }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ digitalHuman.create_datetime }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ digitalHuman.update_datetime }}</el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">{{ digitalHuman.description }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 编辑表单弹窗 -->
    <el-dialog
      v-model="showEditForm"
      title="编辑数字人"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form ref="formRef" :model="formData" label-width="100px" class="form-content">
        <el-form-item label="名称" prop="name" :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]">
          <el-input v-model="formData.name" placeholder="请输入数字人名称"></el-input>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入描述"></el-input>
        </el-form-item>
        
        <el-form-item label="头像" prop="avatar_url" :rules="[{ required: true, message: '请上传头像', trigger: 'change' }]">
          <el-upload
            class="avatar-uploader"
            :action="`${apiBaseUrl}/api/system/admin_upload/`"
            :headers="{
              'Authorization': `JWT ${Session.get('token') || ''}`
            }"
            :data="{
              tenant_id:Session.get('tenant_id')
            }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="formData.avatar_url" :src="formData.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-switch v-model="formData.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        
        <el-form-item label="语音ID" prop="config.voice_id">
          <el-select v-model="formData.config.voice_id" placeholder="请选择语音">
            <el-option label="小明(高级)" value="xiaoming_voice_premium"></el-option>
            <el-option label="小红" value="xiaohong_voice"></el-option>
            <!-- 可以根据实际情况添加更多选项 -->
          </el-select>
        </el-form-item>
        
        <el-form-item label="风格" prop="config.style">
          <el-select v-model="formData.config.style" placeholder="请选择风格">
            <el-option label="专业" value="professional"></el-option>
            <el-option label="友好" value="friendly"></el-option>
            <el-option label="严肃" value="serious"></el-option>
            <!-- 可以根据实际情况添加更多选项 -->
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditForm">取消</el-button>
          <el-button type="primary" @click="submitEditForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </fs-page>
</template>

<script lang="ts" setup name="digitalHumanDetail">
import { onMounted, ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus, ArrowLeft } from '@element-plus/icons-vue';
import { Session } from '/@/utils/storage';
import { GetObj, UpdateObj } from '../list/api';
import { auth } from '/@/utils/authFunction';

const apiBaseUrl = import.meta.env.VITE_API_URL;
const route = useRoute();
const router = useRouter();
const loading = ref(true);
const digitalHuman = ref({});
const canEdit = ref(auth('digitalHuma:Update'));

// 编辑表单相关
const showEditForm = ref(false);
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  description: '',
  avatar_url: '',
  tenant_id:Session.get('tenant_id'),
  status: 1,
  config: {
    voice_id: 'xiaoming_voice_premium',
    style: 'professional'
  }
});

// 获取数字人详情
const getDigitalHumanDetail = async () => {
  try {
    loading.value = true;
    const id = route.query.id;
    if (!id) {
      ElMessage.error('缺少数字人ID');
      goBack();
      return;
    }
    
    const res = await GetObj(id as string);
    digitalHuman.value = res.data;
    loading.value = false;
  } catch (error) {
    console.error('获取数字人详情失败', error);
    ElMessage.error('获取数字人详情失败');
    loading.value = false;
  }
};

// 返回列表页
const goBack = () => {
  router.push('/digitalHuman/list');
};

// 打开编辑表单
const openEditForm = () => {
  showEditForm.value = true;
  // 填充表单数据
  Object.assign(formData, {
    id: digitalHuman.value.id,
    name: digitalHuman.value.name,
    description: digitalHuman.value.description,
    avatar_url: digitalHuman.value.avatar_url,
    tenant_id: digitalHuman.value.tenant_id || 1,
    status: digitalHuman.value.status,
    config: {
      voice_id: digitalHuman.value.config?.voice_id || 'xiaoming_voice_premium',
      style: digitalHuman.value.config?.style || 'professional'
    }
  });
};

// 关闭编辑表单
const closeEditForm = () => {
  showEditForm.value = false;
};

// 头像上传成功处理
const handleAvatarSuccess = (res: any, file: any) => {
  // 根据实际接口返回格式调整
  console.log(res);
  formData.avatar_url = res.url;
};

// 头像上传前验证
const beforeAvatarUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await formRef.value.validate();
    await UpdateObj(formData);
    ElMessage.success('更新成功');
    closeEditForm();
    getDigitalHumanDetail(); // 刷新详情
  } catch (e) {
    console.error(e);
    ElMessage.error('更新失败');
  }
};

onMounted(() => {
  getDigitalHumanDetail();
});
</script>

<style scoped>
.digital-human-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.detail-title {
  flex: 1;
  margin: 0 20px;
  font-size: 20px;
}

.detail-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.avatar-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.avatar-placeholder {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 4px;
}

/* 编辑表单样式 */
.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

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

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

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.dialog-footer {
  text-align: right;
}
</style> 