<template>
  <div class="user-profile">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <div class="profile-card">
          <div class="card-header">
            <h3 class="card-title">个人资料</h3>
          </div>
          <div class="card-content">
            <div class="avatar-section">
              <el-avatar :size="100" :src="userInfo?.avatar || ''">
                {{ userInfo?.account?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
              <el-button
                type="primary"
                link
                size="small"
                @click="handleAvatarChange"
              >
                更换头像
              </el-button>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="info-label">账号</span>
                <span class="info-value">{{ userInfo?.account || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">邮箱</span>
                <span class="info-value">{{ userInfo?.email || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">手机号</span>
                <span class="info-value">{{ userInfo?.phone || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态</span>
                <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'" size="small">
                  {{ userInfo?.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <div class="quick-actions">
          <div class="card-header">
            <h3 class="card-title">快捷操作</h3>
          </div>
          <div class="action-list">
            <div class="action-item" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <div class="detail-card">
          <div class="card-header">
            <h3 class="card-title">详细资料</h3>
            <el-button
              type="primary"
              :icon="Edit"
              size="small"
              @click="handleEditProfile"
            >
              编辑
            </el-button>
          </div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">
              {{ userInfo?.name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ getSexText(userInfo?.sex) }}
            </el-descriptions-item>
            <el-descriptions-item label="生日">
              {{ userInfo?.birth || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'" size="small">
                {{ userInfo?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间" :span="2">
              {{ formatDate(userInfo?.create_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录IP" :span="2">
              {{ userInfo?.last_login_ip || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="security-card">
          <div class="card-header">
            <h3 class="card-title">安全设置</h3>
          </div>
          <div class="security-list">
            <div class="security-item">
              <div class="security-info">
                <el-icon class="security-icon"><Lock /></el-icon>
                <div class="security-text">
                  <div class="security-title">登录密码</div>
                  <div class="security-desc">用于登录系统</div>
                </div>
              </div>
              <el-button type="primary" link @click="handleChangePassword">
                修改
              </el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon class="security-icon"><Iphone /></el-icon>
                <div class="security-text">
                  <div class="security-title">手机绑定</div>
                  <div class="security-desc">已绑定: {{ userInfo?.phone || '未绑定' }}</div>
                </div>
              </div>
              <el-button type="primary" link>
                {{ userInfo?.phone ? '更换' : '绑定' }}
              </el-button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <el-icon class="security-icon"><Message /></el-icon>
                <div class="security-text">
                  <div class="security-title">邮箱绑定</div>
                  <div class="security-desc">已绑定: {{ userInfo?.email || '未绑定' }}</div>
                </div>
              </div>
              <el-button type="primary" link>
                {{ userInfo?.email ? '更换' : '绑定' }}
              </el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑资料"
      width="500px"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.sex">
            <el-radio :value="0">保密</el-radio>
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="editForm.birth"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleSaveProfile">
          保存
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="450px"
      @close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordFormRules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="passwordLoading" @click="handleSavePassword">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Edit,
  Lock,
  SwitchButton,
  Iphone,
  Message
} from "@element-plus/icons-vue";
import { getUserInfo, updateUserInfo } from "@/api/user";
import { useAuthStore } from "@/stores/auth";

const router = useRouter();
const authStore = useAuthStore();

const userInfo = ref(null);
const editDialogVisible = ref(false);
const passwordDialogVisible = ref(false);
const editLoading = ref(false);
const passwordLoading = ref(false);

const editFormRef = ref(null);
const passwordFormRef = ref(null);

const editForm = ref({
  email: "",
  phone: "",
  name: "",
  sex: 0,
  birth: ""
});

const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const editFormRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

const passwordFormRules = {
  oldPassword: [
    { required: true, message: "请输入旧密码", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度为 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" }
  ]
};

const formatDate = (date) => {
  if (!date) return "-";
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const getSexText = (sex) => {
  const map = {
    0: "保密",
    1: "男",
    2: "女"
  };
  return map[sex] || "-";
};

const fetchUserInfo = async () => {
  try {
    const userId = authStore.user?.id;
    if (!userId) {
      ElMessage.error("用户ID不存在");
      return;
    }
    const res = await getUserInfo(userId);
    if (res.code === 200) {
      userInfo.value = res.data;
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
    ElMessage.error("获取用户信息失败");
  }
};

const handleEditProfile = () => {
  editForm.value = {
    name: userInfo.value?.name || "",
    sex: userInfo.value?.sex || 0,
    birth: userInfo.value?.birth || "",
    email: userInfo.value?.email || "",
    phone: userInfo.value?.phone || ""
  };
  editDialogVisible.value = true;
};

const handleSaveProfile = async () => {
  try {
    await editFormRef.value.validate();
    editLoading.value = true;
    const userId = authStore.user?.id;
    const res = await updateUserInfo(userId, editForm.value);
    if (res.code === 200) {
      ElMessage.success("保存成功");
      editDialogVisible.value = false;
      await fetchUserInfo();
    }
  } catch (error) {
    console.error("保存失败", error);
    if (error !== false) {
      ElMessage.error("保存失败");
    }
  } finally {
    editLoading.value = false;
  }
};

const handleEditDialogClose = () => {
  editFormRef.value?.resetFields();
};

const handleChangePassword = () => {
  passwordDialogVisible.value = true;
};

const handleSavePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    passwordLoading.value = true;
    // TODO: 调用修改密码接口
    ElMessage.success("密码修改成功");
    passwordDialogVisible.value = false;
  } catch (error) {
    console.error("修改密码失败", error);
    if (error !== false) {
      ElMessage.error("修改密码失败");
    }
  } finally {
    passwordLoading.value = false;
  }
};

const handlePasswordDialogClose = () => {
  passwordFormRef.value?.resetFields();
};

const handleAvatarChange = () => {
  ElMessage.info("头像上传功能开发中");
};

const handleLogout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await authStore.logout(authStore.user?.id);
    } catch (error) {
      console.error("退出登录接口调用失败:", error);
    }
    
    // 清除所有本地存储
    localStorage.removeItem("active_tab");
    localStorage.removeItem("1123567809876");
    localStorage.removeItem("tabs_list");
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    localStorage.removeItem("tenant");
    
    sessionStorage.removeItem("active_tab");
    sessionStorage.removeItem("456");
    sessionStorage.removeItem("tabs_list");
    sessionStorage.removeItem("token");
    sessionStorage.removeItem("user");
    sessionStorage.removeItem("tenant");
    
    // 清除所有 cookies,包括跨域和不同路径的 cookie
    const clearCookie = (name) => {
      document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
      document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=`;
      document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.${location.hostname}`;
      if (location.hostname !== "localhost") {
        document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${location.hostname}`;
      }
    };
    
    // 清除所有已知 cookie
    clearCookie("PHPSESSID");
    clearCookie("token");
    clearCookie("user");
    clearCookie("tenant");
    
    // 同时清除所有现有的 cookie
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      const eqPos = cookie.indexOf("=");
      const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
      if (name) {
        clearCookie(name);
      }
    }
    
    authStore.clearToken();
    router.push("/login");
    ElMessage.success("已退出登录");
  }).catch(() => {});
};

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

<style scoped lang="less">
.user-profile {
  padding: 0;

  .profile-card,
  .quick-actions,
  .detail-card,
  .security-card {
    background: var(--el-bg-color);
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 16px;
    border: 1px solid var(--el-border-color-lighter);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .card-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .card-content {
    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 16px;
      margin-bottom: 24px;

      .el-avatar {
        background: linear-gradient(135deg, #3973ff 0%, #4f84ff 100%);
      }
    }

    .info-list {
      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);

        &:last-child {
          border-bottom: none;
        }

        .info-label {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }

        .info-value {
          font-size: 14px;
          color: var(--el-text-color-primary);
          font-weight: 500;
        }
      }
    }
  }

  .action-list {
    .action-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 14px 16px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      .el-icon {
        font-size: 20px;
        color: var(--el-color-primary);
      }

      span {
        font-size: 14px;
        color: var(--el-text-color-primary);
      }

      &:hover {
        background: var(--el-fill-color-light);
      }
    }
  }

  .security-list {
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 12px;
      border: 1px solid var(--el-border-color-lighter);
      transition: all 0.3s;

      &:last-child {
        margin-bottom: 0;
      }

      &:hover {
        border-color: var(--el-color-primary-light-7);
        background: var(--el-fill-color-lighter);
      }

      .security-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .security-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          background: linear-gradient(135deg, rgba(57, 115, 255, 0.1) 0%, rgba(79, 132, 255, 0.1) 100%);
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--el-color-primary);
          font-size: 20px;
        }

        .security-text {
          .security-title {
            font-size: 15px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .security-desc {
            font-size: 13px;
            color: var(--el-text-color-placeholder);
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-card,
  .quick-actions,
  .detail-card,
  .security-card {
    padding: 16px;
  }
}
</style>
