<template>
  <div class="user-profile">
    <h2>个人空间</h2>
    <div class="profile-info">
      <img src="../../assets/img/defaultAvatar.png" alt="Avatar" class="avatar" />
      <p><strong>用户名:</strong> {{ loginStore.userInfo.username }}</p>
    </div>
    <button @click="logout">登出</button>
    <button @click="showEditDialog = true">修改信息</button>
    <button @click="openConfirmationModal" class="logout-button">注销此账号</button>
  </div>

  <!-- 文章展示区域 -->
  <div class="articles">
    <div class="articles-header">
      <b class="articles-title">您的全部文章</b>
      以
      <select v-model="selectedOption" class="dropdown-select">
        <option value="byLike">最受欢迎</option>
        <option value="byData">发布日期</option>
      </select>
      排序
      <button class="confirm-button" @click="handleConfirm">确认</button>
    </div>
    <div class="article">
      <!-- 文章内容 -->
      <div v-for="(p, index) in postOverviewList" :key="p.post_id">
        <Article 
          :post_id="p.post_id" 
          :user_id="p.user_id" 
          :username="p.username" 
          :title="p.title" 
          :updated_at="p.updated_at" 
          :Likes="p.Likes" 
          :showButtons="true" 
          @destroy="handleDestroy(index)"
        />
      </div>
    </div>
    <!-- 更多文章可以继续添加 -->
  </div>

  <div>
    <el-dialog v-model="showEditDialog" title="修改信息">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            :type="passwordType"
            placeholder="请输入新密码"
          >
            <template #suffix>
              <i
                class="el-input__icon el-icon-view"
                @click="togglePasswordVisibility"
              ></i>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 注销确认模态框 -->
    <el-dialog v-model="isConfirmationModalVisible" title="确认注销">
      <p>此账号注销后无法找回，请谨慎操作。</p>
      <el-input v-model="confirmationText" placeholder="请输入“我确认要注销此账号”"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeConfirmationModal">取消</el-button>
          <el-button type="primary" @click="handleConfirmLogout">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import Article from '@/components/utils/Article.vue';
import { useLoginStore } from '@/stores/Login';
import { useRouter } from 'vue-router';
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useToast } from 'vue-toastification';

const toast = useToast();
const router = useRouter();
const loginStore = useLoginStore();

// 文章列表
interface postOverview {
  post_id: number;
  user_id: number;
  Likes: number;
  username: string;
  title: string;
  updated_at: string;
}
let postOverviewList = reactive<postOverview[]>([]);

const showEditDialog = ref(false);
const passwordType = ref('password');
const confirmationText = ref('');

// 下拉选择框的选项值
const selectedOption = ref('byData'); // 默认值为选项1

// 定义并初始化 articles 变量
const articles = ref<postOverview[]>([]);
const form = reactive({
  username: loginStore.userInfo.username,
  password: '',
});

const togglePasswordVisibility = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password';
};

function handleDestroy(index: number) {
  articles.value.splice(index, 1); // 移除指定索引的文章
  postOverviewList.splice(index, 1);
}

function getAll(by: string) {
  axios.get('http://localhost:8080/post/overview', {
    params: { by: by },
    headers: { token: loginStore.userInfo.token }
  })
  .then(res => {
    // 使用扩展运算符来保持响应性
    postOverviewList.splice(0, postOverviewList.length);
    postOverviewList.push(...res.data.data);
    console.log("获取文章概览数据成功", res.data.data);
  })
  .catch(error => console.error('There was an error fetching the data!', error));
}

const handleSubmit = () => {
  // 处理表单提交逻辑
  console.log(form);
  showEditDialog.value = false;
  // axios向后端发起请求
  axios.put('http://localhost:8080/user/revise', {
    username: form.username,
    password: form.password,
    token: loginStore.userInfo.token
  })
  .then(response => {
    // 处理成功响应
    console.log('Response:', response.data);
    toast.success("修改成功，请重新登陆");
    // 调用登出，然后重新登陆
    logout();
  })
  .catch(error => {
    // 处理错误
    console.error('Error:', error);
  });

  toast.success("信息修改成功");
};

const logout = () => {
  // 清除 useLoginStore 中的所有内容
  loginStore.userInfo = {
    id: '',
    avatarurl: '../../assets/img/deLogin.png',
    username: '',
    token: ''
  };
  toast.success("成功");
  // 跳转到主页
  router.push('/');
};

const handleConfirm = () => {
  console.log('选择的选项是:', selectedOption.value);
  getAll(selectedOption.value);
};

// 注销相关逻辑
const isConfirmationModalVisible = ref(false);

const openConfirmationModal = () => {
  isConfirmationModalVisible.value = true;
};

const closeConfirmationModal = () => {
  isConfirmationModalVisible.value = false;
  confirmationText.value = '';
};

const handleConfirmLogout = () => {
  if (confirmationText.value === "确认") {
    // 调用注销函数
    logoutAccount();
  } else {
    alert("输入不正确，请重新输入。");
  }
};

const logoutAccount = () => {
  // 实现注销逻辑
  console.log("账号已注销");
  // 例如，清除用户信息并重定向到登录页面
  axios.delete('http://localhost:8080/user/logout', {
    data: { token: loginStore.userInfo.token }
  })
  .then(response => {
    // 处理成功响应
    console.log('Response:', response.data);
    toast.success("注销成功");
    // 调用登出，然后重新登陆
    logout();
  })
  .catch(error => {
})
  loginStore.userInfo = {
    id: '',
    avatarurl: '../../assets/img/deLogin.png',
    username: '',
    token: ''
  };

  logout();
};

onMounted(() => {
  // 在组件挂载后调用 getAll 函数
  getAll(selectedOption.value);
});
</script>

<style scoped>
.user-profile {
  text-align: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  margin: 0 auto;
}

.profile-info {
  margin-bottom: 20px;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 20px;
}

button {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
  margin-right: 10px; /* 添加间距 */
}

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

.logout-button {
  background-color: #ff4d4d;
}

.logout-button:hover {
  background-color: #ff1a1a;
}

.articles {
  flex: 1; /* 占据剩余空间 */
  padding: 20px;
  overflow-y: auto; /* 滚动条 */
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直方向从顶部开始 */
}

/* 单篇文章样式 */
.article {
  margin-bottom: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  width: 100%;
}

/* 文章标题样式 */
.articles-title {
  font-size: 24px;
  color: #333; 
  font-weight: bold;
  margin-bottom: 10px;
}

/* 下拉选择框样式 */
.dropdown-select {
  margin-left: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>