<template>
  <view class="container">
    <!-- 个人信息设置 -->
    <view class="profile-section">
      <!-- 头像 -->
      <view class="profile-item" @click="changeAvatar">
        <view class="item-label">头像</view>
        <view class="item-content">
          <image
            class="avatar"
            :src="userInfo.avatar"
            mode="aspectFill"
          ></image>
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>

      <!-- 用户名 -->
      <view class="profile-item" @click="editUsername">
        <view class="item-label">用户名</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.username }}</text>
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>

      <!-- 电话 -->
      <view class="profile-item" @click="editPhone">
        <view class="item-label">电话</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.phone }}</text>
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>

      <!-- 邮箱 -->
      <view class="profile-item" @click="editEmail">
        <view class="item-label">邮箱</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.email }}</text>
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
    </view>

    <!-- 应用设置 -->
    <view class="app-section">
      <!-- 缓存 -->
      <!-- 			<view class="profile-item" @click="clearCache">
				<view class="item-label">缓存</view>
				<view class="item-content">
					<text class="item-value">{{ cacheSize }}</text>
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view> -->

      <!-- 用户协议 -->
      <view class="profile-item" @click="viewUserAgreement">
        <view class="item-label">用户协议</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>

      <!-- 关于我们 -->
      <view class="profile-item" @click="viewAbout">
        <view class="item-label">关于我们</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section">
      <uv-button
        type="primary"
        size="large"
        @click="logout"
        :loading="logoutLoading"
      >
        退出登录
      </uv-button>
    </view>

    <!-- 编辑弹窗 -->
    <uv-popup ref="editPopup" mode="center" @close="closeEditModal" :round="10">
      <view class="edit-modal">
        <view class="modal-title">
          编辑{{
            editType === "username"
              ? "用户名"
              : editType === "phone"
              ? "电话"
              : editType === "email"
              ? "邮箱"
              : ""
          }}
        </view>
        <uv-input
          v-model="editValue"
          :placeholder="getPlaceholder()"
          :type="
            editType === 'phone'
              ? 'number'
              : editType === 'email'
              ? 'email'
              : 'text'
          "
          border="bottom"
          clearable
        ></uv-input>
        <view class="modal-actions">
          <uv-button type="default" @click="closeEditModal">取消</uv-button>
          <uv-button type="primary" @click="saveEdit">保存</uv-button>
        </view>
      </view>
    </uv-popup>

    <!-- 头像选择弹窗 -->
    <uv-popup
      ref="avatarSheet"
      mode="bottom"
      @close="closeAvatarSheet"
      :round="10"
    >
      <view class="avatar-sheet">
        <view class="sheet-header">
          <view class="sheet-title">选择头像</view>
        </view>
        <view class="sheet-actions">
          <view class="action-item" @click="selectAvatarSource('camera')">
            <uv-icon name="camera-fill" size="24" color="#4285f4"></uv-icon>
            <text class="action-text">拍照</text>
          </view>
          <view class="action-item" @click="selectAvatarSource('album')">
            <uv-icon name="photo-fill" size="24" color="#4285f4"></uv-icon>
            <text class="action-text">从相册选择</text>
          </view>
        </view>
        <view class="sheet-cancel">
          <uv-button type="default" size="large" @click="closeAvatarSheet">
            取消
          </uv-button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useAuthStore, useUserStore } from "@/store";

const authStore = useAuthStore();
const userStore = useUserStore();

// 响应式数据
const userInfo = ref({
  avatar: "/static/imgs/avatar.png",
  username: "张三",
  phone: "15825556676",
  email: "235382903@qq.com",
});

const cacheSize = ref("36MB");
const logoutLoading = ref(false);
const editType = ref("");
const editValue = ref("");
const editPopup = ref(null);
const avatarSheet = ref(null);

// 更换头像
const changeAvatar = () => {
  console.log("点击更换头像");
  avatarSheet.value.open();
};

// 关闭头像选择弹窗
const closeAvatarSheet = () => {
  avatarSheet.value.close();
};

// 选择头像来源
const selectAvatarSource = (source) => {
  console.log("选择头像方式:", source);
  avatarSheet.value.close();

  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: source === "camera" ? ["camera"] : ["album"],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      console.log("选择图片成功:", tempFilePath);

      // 这里应该上传图片到服务器
      // uploadAvatar(tempFilePath)

      // 临时更新头像显示
      userInfo.value.avatar = tempFilePath;

      uni.showToast({
        title: "头像更新成功",
        icon: "success",
      });
    },
    fail: (err) => {
      console.error("选择图片失败:", err);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    },
  });
};

// 编辑用户名
const editUsername = () => {
  editType.value = "username";
  editValue.value = userInfo.value.username;
  editPopup.value.open();
};

// 编辑电话
const editPhone = () => {
  editType.value = "phone";
  editValue.value = userInfo.value.phone;
  editPopup.value.open();
};

// 编辑邮箱
const editEmail = () => {
  editType.value = "email";
  editValue.value = userInfo.value.email;
  editPopup.value.open();
};

// 获取输入框占位符
const getPlaceholder = () => {
  switch (editType.value) {
    case "username":
      return "请输入用户名";
    case "phone":
      return "请输入手机号";
    case "email":
      return "请输入邮箱地址";
    default:
      return "请输入";
  }
};

// 关闭编辑弹窗
const closeEditModal = () => {
  editPopup.value.close();
  editType.value = "";
  editValue.value = "";
};

// 保存编辑
const saveEdit = async () => {
  if (!editValue.value.trim()) {
    uni.showToast({
      title: "请输入内容",
      icon: "none",
    });
    return;
  }

  // 验证格式
  if (editType.value === "phone" && !/^1[3-9]\d{9}$/.test(editValue.value)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return;
  }

  if (
    editType.value === "email" &&
    !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(editValue.value)
  ) {
    uni.showToast({
      title: "请输入正确的邮箱地址",
      icon: "none",
    });
    return;
  }

  try {
    // 调用更新用户信息API
    // await RPC.post('/api/user/update', {
    //   [editType.value]: editValue.value
    // })

    // 更新本地数据
    userInfo.value[editType.value] = editValue.value;

    uni.showToast({
      title: "保存成功",
      icon: "success",
    });

    closeEditModal();
  } catch (error) {
    console.error("保存失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
  }
};

// 清除缓存
const clearCache = () => {
  uni.showModal({
    title: "清除缓存",
    content: "确定要清除应用缓存吗？",
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: "清除中...",
        });

        // 模拟清除缓存
        setTimeout(() => {
          uni.hideLoading();
          cacheSize.value = "0MB";
          uni.showToast({
            title: "缓存清除成功",
            icon: "success",
          });
        }, 1500);
      }
    },
  });
};

// 查看用户协议
const viewUserAgreement = () => {
  uni.navigateTo({
    url: "/pagesA/user-agreement/user-agreement",
  });
};

// 查看关于我们
const viewAbout = () => {
  //   uni.navigateTo({
  //     url: "/pagesA/about/about",
  //   });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: "退出登录",
    content: "确定要退出登录吗？",
    success: (res) => {
      if (res.confirm) {
        logoutLoading.value = true;

        // 模拟退出登录
        setTimeout(() => {
          authStore.signOut();
          logoutLoading.value = false;

          // 清除用户信息和token
          // authStore.logout()

          uni.showToast({
            title: "已退出登录",
            icon: "success",
          });

          // 跳转到登录页
          uni.reLaunch({
            url: "/pages/login/login",
          });
        }, 1000);
      }
    },
  });
};

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 调用获取用户信息API
    // const result = await RPC.get('/api/user/info')
    // userInfo.value = result.data
  } catch (error) {
    console.error("加载用户信息失败:", error);
  }
};

// 计算缓存大小
const calculateCacheSize = () => {
  // 实际项目中应该计算真实的缓存大小
  // const size = await getCacheSize()
  // cacheSize.value = formatSize(size)
};

onMounted(() => {
  loadUserInfo();
  calculateCacheSize();
});

onShow(() => {
  // 页面显示时刷新用户信息
  loadUserInfo();
});
</script>

<style lang="scss" scoped>
.container {
  font-size: 14px;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 16px;
}

.profile-section,
.app-section {
  background: white;
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;

  .profile-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

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

    .item-label {
      font-size: 16px;
      color: #333;
      font-weight: 500;
    }

    .item-content {
      display: flex;
      align-items: center;
      gap: 8px;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }

      .item-value {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.logout-section {
  margin-top: 32px;
}

.edit-modal {
  width: 300px;
  padding: 24px;

  .modal-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 20px;
  }

  .modal-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;

    .uv-button {
      flex: 1;
    }
  }
}

.avatar-sheet {
  padding: 20px;

  .sheet-header {
    text-align: center;
    margin-bottom: 20px;

    .sheet-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }

  .sheet-actions {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      padding: 20px;
      border-radius: 8px;
      background: #f8f9fa;
      min-width: 100px;
      transition: all 0.3s;

      &:active {
        background: #e9ecef;
        transform: scale(0.95);
      }

      .action-text {
        font-size: 14px;
        color: #333;
      }
    }
  }

  .sheet-cancel {
    margin-top: 10px;
  }
}
</style>