<template>
  <div class="notification-detail-container">
    <a-spin :spinning="loading" tip="加载中...">
      <a-card v-if="projectNotice.id" class="notification-card">
        <a-button class="custom-button" @click="goBack">返回</a-button>
        <a-button v-if="!isEditing" class="custom-button" @click="enterEditMode" style="margin-left: 10px">编辑</a-button>
        <template v-else>
          <a-button class="custom-button" @click="saveNotice" style="margin-left: 10px">保存</a-button>
          <a-button class="custom-button" @click="cancelEdit" style="margin-left: 10px">取消</a-button>
        </template>

        <div class="header">
          <h1 v-if="!isEditing" class="title">{{ projectNotice.notificationTitle }}</h1>
          <a-input v-else v-model:value="editableNotice.notificationTitle" placeholder="请输入通知标题" />

          <div class="meta-info">
            <span class="project-id">项目ID: {{ projectNotice.projectId }}</span>
            <span class="create-time">创建时间: {{ projectNotice.createTime }}</span>
          </div>
        </div>

        <div class="divider"></div>

        <div class="content">
          <div class="content-header">
            <notification-outlined class="icon" />
            <h2>通知内容</h2>
          </div>

          <!-- 富文本显示和编辑区域 -->
          <div v-if="!isEditing" class="content-html" v-html="projectNotice.notificationContent"></div>
          <div v-else class="rich-text-group">
            <RichTextEditor
                v-model="editableNotice.notificationContent"
                :disable="false"
                @content-change="(html:any) => editableNotice.notificationContent = html"
                class="rich-text-editor"
            />
          </div>
        </div>

        <div class="divider"></div>
      </a-card>

      <a-empty v-else-if="!loading" :description="errorMessage || '未找到通知详情'" />
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import myAxios from "../../api/myAxios.ts";
import { NotificationOutlined } from '@ant-design/icons-vue';
import RichTextEditor from '../components/RichTextEditor.vue'; // 引入富文本编辑器
import '@vueup/vue-quill/dist/vue-quill.snow.css'; // 引入富文本编辑器样式
function encode64(text: string): string {
  return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, p1) => {
    return String.fromCharCode(parseInt(p1, 16));
  }));
}

function decode64(text: string): string {
  try {
    return decodeURIComponent(
        Array.from(atob(text), char =>
            '%' + ('00' + char.charCodeAt(0).toString(16)).slice(-2)
        ).join('')
    );
  } catch (error) {
    console.error('Base64解码失败:', error);
    return text; // 解码失败时返回原始文本
  }
}
interface NotificationDetail {
  id: string;
  notificationTitle: string;
  projectId: string;
  createTime: string;
  notificationContent: string;
}

const projectNotice = ref<Partial<NotificationDetail>>({
  id: '',
  notificationTitle: '',
  projectId: '',
  createTime: '',
  notificationContent: ''
});


const editableNotice = ref<Partial<NotificationDetail>>({});
const isEditing = ref(false);
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const errorMessage = ref("");

// 进入编辑模式
const enterEditMode = () => {

  editableNotice.value = {
    ...projectNotice.value
  };
  isEditing.value = true;
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
};

const saveNotice = async () => {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');

    // 对通知内容进行Base64编码
    const encodedContent = encode64(editableNotice.value.notificationContent || '');

    // 创建请求数据
    const requestData = {
      id: editableNotice.value.id,
      notificationTitle: editableNotice.value.notificationTitle,
      notificationContent: encodedContent, // 使用编码后的内容
      projectId: editableNotice.value.projectId
    };

    const res:any = await myAxios.post(
        "/projectNotification/update",
        requestData,
        {
          headers: {
            Authorization: storedToken,
            'Content-Type': 'application/json'
          }
        }
    );

    if (res.code === 1) {
      message.success('更新成功');

      projectNotice.value = {
        ...editableNotice.value, // 这里包含的是用户编辑的原始内容（未编码）
      };
      isEditing.value = false;
    } else {
      message.error(res.message || '更新失败');
    }
  } catch (error: any) {
    console.error('更新通知失败:', error);
    const errMsg = error.response?.data?.message ||
        error.message ||
        '更新通知失败，请检查网络';
    message.error(errMsg);
  } finally {
    loading.value = false;
  }
};
const fetchNotificationDetail = async (id: number) => {
  try {
    loading.value = true;
    errorMessage.value = "";
    const storedToken = localStorage.getItem('token');

    const res:any = await myAxios.post(
        "/projectNotification/queryById",
        { id },
        {
          headers: {
            Authorization: storedToken,
            'Content-Type': 'application/json'
          }
        }
    );

    if (res.code === 1 && res.data) {
      // 对通知内容进行Base64解码
      const decodedContent = decode64(res.data.notificationContent);

      projectNotice.value = {
        id: res.data.id,
        notificationTitle: res.data.notificationTitle,
        notificationContent: decodedContent,
        projectId: res.data.projectId,
        createTime: res.data.createTime
      };
    } else {
      errorMessage.value = res.message || '获取通知详情失败';
      message.error(errorMessage.value);
    }
  } catch (error: any) {
    console.error('获取通知详情失败:', error);
    errorMessage.value = error.response?.message ||
        error.message ||
        '获取通知详情失败，请检查网络';
    message.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  const id = Number(route.params.id || route.query.id);
  if (id && !isNaN(id)) {
    fetchNotificationDetail(id);
  } else {
    errorMessage.value = '无效的通知ID';
    message.error('无效的通知ID');
  }
});
</script>

<style scoped>
.notification-detail-container {
  width: 100%;
  padding: 24px;
  margin: 0;
}

.notification-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: none;
  overflow: hidden;
}

.header {
  padding: 24px 24px 0;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 16px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  color: #86909c;
  font-size: 14px;
  margin-bottom: 16px;
}

.divider {
  height: 1px;
  background: #f0f0f0;
  margin: 0 24px;
}

.content {
  padding: 24px;
}

.content-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.content-header h2 {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 0 8px;
  color: #1d2129;
}

.icon {
  font-size: 20px;
  color: #1890ff;
}

/* 富文本样式 */
.rich-text-group {
  border: 2px solid #e2e8f0;
  border-radius: 0.75rem;
  overflow: hidden;
  transition: all 0.3s ease;
  min-height: 320px;
  height: auto;
  flex-grow: 1;
  &:focus-within {
    border-color: #6366f1 !important;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
  }
}

.rich-text-editor {
  min-height: 300px;
}

/* 富文本内容显示样式 */
.content-html {
  font-size: 16px;
  line-height: 1.8;
  color: #4e5969;
}

.content-html * {
  max-width: 100%;
}

.content-html img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 10px 0;
}

.content-html h1,
.content-html h2,
.content-html h3 {
  color: #2c3e50;
  margin-top: 15px;
  margin-bottom: 10px;
}

.content-html p {
  margin-bottom: 10px;
}

.content-html ul,
.content-html ol {
  margin-left: 20px;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .notification-detail-container {
    padding: 16px;
  }

  .title {
    font-size: 20px;
  }

  .meta-info {
    flex-direction: column;
    gap: 8px;
  }

  .content {
    padding: 16px;
  }

  .rich-text-group {
    min-height: 250px;
  }
}

/*橙色按钮*/

.custom-button {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button:hover,
.custom-button:focus {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button[disabled] {
  background-color: #ffa940;
  border-color: #ffa940;
  opacity: 0.6;
  color: #fff;
}

/* 危险按钮样式 */
.custom-button.ant-btn-dangerous {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.custom-button.ant-btn-dangerous:hover,
.custom-button.ant-btn-dangerous:focus {
  background-color: #ff7875;
  border-color: #ff7875;
}
</style>