<template>
  <!-- 只有当数据加载完成且 isVisible 为 true 时才显示页面 -->
  <div class="introduce-update-container" v-if="isVisible && !isLoading">
    <div class="input-group">
      <label for="title-input">标题：</label>
      <input id="title-input" v-model="updatedIntro.title" type="text" placeholder="请输入修改后标题">
    </div>
    <div class="input-group">
      <label>内容：</label>
      <!-- 使用富文本框组件 -->
      <RichTextEditor v-model="updatedIntro.intro" />
    </div>
    <div class="button-container">
      <button @click="updateIntro" :disabled="isUpdating" class="submit-button">提交更新</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import RichTextEditor from './RichTextEditor.vue';
import { ElMessage } from 'element-plus';

// 定义 targetId 和 isVisible 为 prop
const props = defineProps({
  targetId: {
    type: Number,
    required: true
  },
  isVisible: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['updateSuccess']);

// 存储更新用的介绍数据
const updatedIntro = ref({
  title: '',
  intro: ''
});
// 更新状态
const isUpdating = ref(false);
// 加载状态
const isLoading = ref(true);

// 从后端获取介绍数据
const fetchData = async () => {
  try {
    isLoading.value = true;
    const response = await axios.get(`https://soilgd.com:5000/software-intro/${props.targetId}`);
    const { title, intro } = response.data;
    // 仅将换行符替换为 <br>，避免影响视频标签
    let processedIntro = intro.replace(/\r\n/g, '<br>');
    updatedIntro.value.title = title;
    updatedIntro.value.intro = processedIntro;
  } catch (err: any) {
    console.error('请求数据时发生错误:', err.message);
  } finally {
    // 数据加载完成，将加载状态设为 false
    isLoading.value = false;
  }
};

onMounted(() => {
  console.log('子组件挂载时接收到的 targetId:', props.targetId);
  if (props.isVisible) {
    // 发起数据请求
    fetchData();
  }
});

// 监听 targetId 变化，当 targetId 改变时重新获取数据
watch(() => props.targetId, (newTargetId, oldTargetId) => {
  console.log(`targetId 从 ${oldTargetId} 变为 ${newTargetId}`);
  if (props.isVisible) {
    fetchData();
  }
});

// 更新介绍信息
const updateIntro = async () => {
  isUpdating.value = true;
  try {
    // 将 <br> 标签替换回换行符
    let processedIntro = updatedIntro.value.intro.replace(/<br>/gi, '\r\n');
    const dataToSend = {
      title: updatedIntro.value.title,
      intro: processedIntro
    };
    // 发送 PUT 请求更新数据http
    const response = await axios.put(`https://soilgd.com:5000/software-intro/${props.targetId}`, dataToSend, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    console.log('介绍更新成功！');
    ElMessage.success('更新成功!');
    emits('updateSuccess');
  } catch (err: any) {
    if (err.response) {
      console.error(`服务器错误: ${err.response.status} - ${err.response.data.message}`);
    } else if (err.request) {
      console.error('网络连接错误，请检查网络设置。');
    } else {
      console.error('请求设置错误: ' + err.message);
    }
  } finally {
    isUpdating.value = false;
  }
};
</script>

<style scoped lang="scss">
.introduce-update-container {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  /* 让容器高度自适应内容 */
  height: auto;
  overflow: auto;
}

.input-group {
  margin-bottom: 20px;
  display: flex;
  align-items: start; /* 让标签和输入框顶部对齐 */
}

.input-group label {
  min-width: 80px; /* 固定标签宽度 */
  margin-right: 10px;
  text-align: left; /* 文字左对齐 */
}

.input-group input,
.input-group .rich-text-editor { 
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 3px;
  /* 让输入框和富文本编辑器高度自适应内容 */
  height: auto;
  min-height: auto;
}

.button-container {
  text-align: right;
  margin-top: 10px; /* 增加按钮与输入框的间距 */
}

.submit-button {
  padding: 10px 20px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background-color 0.3s ease;

  &:hover {
    background-color: #0056b3;
  }

  &:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
}
</style>