<template>
  <view class="page">
    <view class="list">
      <view class="row" @click="chooseAvatar">
        <text class="row-label">头像</text>
        <view class="row-value">
          <image
            v-if="avatarDisplaySrc && !avatarLoadFailed"
            class="row-avatar-img"
            :src="avatarDisplaySrc"
            mode="aspectFill"
            @error="onAvatarImageError"
          />
          <view v-else class="row-avatar-ph">
            <text class="row-avatar-letter">{{
              profileAvatarLetter(form.nickname)
            }}</text>
          </view>
        </view>
        <text class="row-chev">›</text>
      </view>

      <view class="row-divider" />

      <view class="row" @click="openNameEditor">
        <text class="row-label">名字</text>
        <text
          class="row-value-text"
          :class="{ 'row-value-text--muted': !form.nickname.trim() }"
          >{{ form.nickname.trim() || "未填写" }}</text>
        <text class="row-chev">›</text>
      </view>

      <view class="row-divider" />

      <view class="row row--static">
        <text class="row-label">手机号码</text>
        <text class="row-value-text row-value-text--muted row--static-value">{{
          phoneDisplay
        }}</text>
      </view>

      <view class="row-divider" />

      <view class="row" @click="openBioEditor">
        <text class="row-label">简介</text>
        <text class="row-value-text row-value-text--muted">{{
          bioDisplay
        }}</text>
        <text class="row-chev">›</text>
      </view>

      <view class="row-divider" />

      <view class="row" @click="openGenderEditor">
        <text class="row-label">性别</text>
        <text class="row-value-text row-value-text--muted">{{
          genderLabels[genderIndex]
        }}</text>
        <text class="row-chev">›</text>
      </view>
    </view>

    <view class="foot">
      <view class="btn-save" @click="saveAndBack">
        <text>保存</text>
      </view>
    </view>

    <!-- 编辑名字 · 居中弹框 -->
    <view
      v-if="nameEditorOpen"
      class="modal-mask"
      @click="nameEditorOpen = false"
    >
      <view class="modal-dialog" @click.stop>
        <text class="modal-title">修改名字</text>
        <input
          v-model="draftName"
          class="modal-input"
          type="nickname"
          maxlength="16"
          placeholder="填写名字"
        />
        <view class="modal-actions">
          <view class="modal-btn modal-btn--ghost" @click="nameEditorOpen = false">
            <text>取消</text>
          </view>
          <view class="modal-btn modal-btn--primary" @click="confirmName">
            <text>确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 编辑简介 · 居中弹框 -->
    <view
      v-if="bioEditorOpen"
      class="modal-mask"
      @click="bioEditorOpen = false"
    >
      <view class="modal-dialog modal-dialog--bio" @click.stop>
        <text class="modal-title">个人简介</text>
        <textarea
          v-model="draftBio"
          class="modal-textarea"
          maxlength="120"
          placeholder="一句话介绍自己"
          :auto-height="true"
        />
        <view class="modal-actions">
          <view class="modal-btn modal-btn--ghost" @click="bioEditorOpen = false">
            <text>取消</text>
          </view>
          <view class="modal-btn modal-btn--primary" @click="confirmBio">
            <text>确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 选择性别 · 居中弹框 -->
    <view
      v-if="genderEditorOpen"
      class="modal-mask"
      @click="genderEditorOpen = false"
    >
      <view class="modal-dialog modal-dialog--gender" @click.stop>
        <text class="modal-title">选择性别</text>
        <view
          v-for="(label, idx) in genderLabels"
          :key="idx"
          class="gender-row"
          :class="{ 'gender-row--on': genderIndex === idx }"
          @click="selectGender(idx)"
        >
          <text class="gender-row-txt">{{ label }}</text>
          <text v-if="genderIndex === idx" class="gender-row-check">✓</text>
        </view>
        <view class="modal-btn-block modal-btn-block--ghost" @click="genderEditorOpen = false">
          <text>取消</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { resolveMediaUrl } from "@/utils/mediaUrl";
import { onLoad, onShow } from "@dcloudio/uni-app";
import type { UserProfile } from "@/utils/userProfileStorage";
import {
  loadUserProfile,
  profileAvatarLetter,
  saveUserProfile,
} from "@/utils/userProfileStorage";
import { apiEnabled } from "@/config/api";
import { apiFailureMessage, get, isMpSessionExpiredError, post, uploadImage } from "@/utils/api/http";
import { ensureMpSession } from "@/utils/api/mpSession";
import { isAlreadyPersistedAvatarUrl } from "@/utils/avatarUpload";

const form = reactive<UserProfile>(loadUserProfile());

const avatarDisplaySrc = computed(() =>
  resolveMediaUrl(form.avatarUrl.trim())
);
const avatarLoadFailed = ref(false);
watch(avatarDisplaySrc, () => {
  avatarLoadFailed.value = false;
});
function onAvatarImageError() {
  avatarLoadFailed.value = true;
}

const genderOptions: UserProfile["gender"][] = ["secret", "male", "female"];
const genderLabels = ["保密", "男", "女"];

const nameEditorOpen = ref(false);
const bioEditorOpen = ref(false);
const genderEditorOpen = ref(false);
const draftName = ref("");
const draftBio = ref("");

const genderIndex = computed(() => {
  const i = genderOptions.indexOf(form.gender);
  return i >= 0 ? i : 0;
});

const bioDisplay = computed(() => {
  const t = form.bio.trim();
  if (!t) return "未填写";
  return t.length > 18 ? `${t.slice(0, 18)}…` : t;
});

function formatPhoneDisplay(p: string): string {
  const t = (p || "").trim();
  if (!t) {
    return "未绑定";
  }
  if (/^1\d{10}$/.test(t)) {
    return `${t.slice(0, 3)} ${t.slice(3, 7)} ${t.slice(7)}`;
  }
  return t;
}

const phoneDisplay = computed(() => formatPhoneDisplay(form.phone));

async function hydrateFromApi() {
  if (!apiEnabled()) {
    return;
  }
  try {
    await ensureMpSession();
    const prof = await get<{
      nickname: string;
      avatarUrl: string;
      bio: string;
      gender: number;
      phone?: string;
    }>("/api/v1/me/profile");
    const d = prof.data;
    if (typeof d.nickname === "string" && d.nickname.trim()) {
      form.nickname = d.nickname.trim();
    }
    const av = typeof d.avatarUrl === "string" ? d.avatarUrl.trim() : "";
    if (av) {
      form.avatarUrl = av;
    }
    if (typeof d.bio === "string") {
      form.bio = d.bio;
    }
    form.gender =
      d.gender === 1 ? "male" : d.gender === 2 ? "female" : "secret";
    form.phone = typeof d.phone === "string" ? d.phone.trim() : "";
    persistProfile();
  } catch (e) {
    if (isMpSessionExpiredError(e)) {
      return;
    }
    /* 保持本地 */
  }
}

onLoad(() => {
  Object.assign(form, loadUserProfile());
  void hydrateFromApi();
});

onShow(() => {
  Object.assign(form, loadUserProfile());
  void hydrateFromApi();
});

function persistProfile() {
  saveUserProfile({ ...form });
}

function genderToApi(g: UserProfile["gender"]): number {
  if (g === "male") {
    return 1;
  }
  if (g === "female") {
    return 2;
  }
  return 0;
}

async function saveAndBack() {
  const nick = form.nickname.trim();
  if (!nick) {
    uni.showToast({ title: "请填写名字", icon: "none" });
    return;
  }
  form.nickname = nick;
  form.bio = form.bio.trim();
  persistProfile();
  if (apiEnabled()) {
    try {
      await ensureMpSession();
      let avatarUrl = form.avatarUrl.trim();
      if (avatarUrl && !isAlreadyPersistedAvatarUrl(avatarUrl)) {
        try {
          avatarUrl = await uploadImage(avatarUrl);
          form.avatarUrl = avatarUrl;
          persistProfile();
        } catch (e) {
          if (isMpSessionExpiredError(e)) {
            return;
          }
          uni.showToast({ title: "头像上传失败，请重试", icon: "none" });
          return;
        }
      }
      await post("/api/v1/me/profile", {
        nickname: form.nickname,
        avatarUrl,
        bio: form.bio,
        gender: genderToApi(form.gender),
      });
    } catch (e) {
      if (isMpSessionExpiredError(e)) {
        return;
      }
      /* 本地已保存 */
    }
  }
  uni.showToast({ title: "已保存", icon: "success" });
  setTimeout(() => uni.navigateBack(), 450);
}

function openGenderEditor() {
  genderEditorOpen.value = true;
}

function selectGender(idx: number) {
  if (idx < 0 || idx >= genderOptions.length) return;
  form.gender = genderOptions[idx];
  persistProfile();
  genderEditorOpen.value = false;
  uni.showToast({ title: "已保存", icon: "success" });
}

function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      const path = res.tempFilePaths[0];
      if (path) {
        form.avatarUrl = path;
        persistProfile();
        if (!apiEnabled()) {
          uni.showToast({ title: "已保存", icon: "success" });
          return;
        }
        void (async () => {
          try {
            await ensureMpSession();
            const serverUrl = await uploadImage(path);
            form.avatarUrl = serverUrl;
            persistProfile();
            await post("/api/v1/me/profile", {
              avatarUrl: serverUrl,
            });
            uni.showToast({ title: "头像已更新", icon: "success" });
          } catch (e) {
            if (isMpSessionExpiredError(e)) {
              return;
            }
            uni.showToast({
              title: apiFailureMessage(e, "头像上传失败"),
              icon: "none",
            });
          }
        })();
      }
    },
  });
}

function openNameEditor() {
  draftName.value = form.nickname;
  nameEditorOpen.value = true;
}

function confirmName() {
  const nick = draftName.value.trim();
  if (!nick) {
    uni.showToast({ title: "请填写名字", icon: "none" });
    return;
  }
  form.nickname = nick;
  persistProfile();
  nameEditorOpen.value = false;
  uni.showToast({ title: "已保存", icon: "success" });
}

function openBioEditor() {
  draftBio.value = form.bio;
  bioEditorOpen.value = true;
}

function confirmBio() {
  form.bio = draftBio.value.trim();
  persistProfile();
  bioEditorOpen.value = false;
  uni.showToast({ title: "已保存", icon: "success" });
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  padding-bottom: calc(32rpx + 120rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  background: #fff;
}

.foot {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  background: linear-gradient(180deg, rgba(255, 255, 255, 0), #fff 36%);
}

.btn-save {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 26rpx;
  border-radius: 16rpx;
  background: linear-gradient(90deg, #4a90e2, #50c8d8);
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.3);
}

.btn-save text {
  font-size: 30rpx;
  font-weight: 600;
  color: #fff;
}

.list {
  padding-top: 8rpx;
}

.row {
  display: flex;
  align-items: center;
  min-height: 112rpx;
  padding: 24rpx 32rpx;
  box-sizing: border-box;
}

.row-label {
  flex-shrink: 0;
  width: 160rpx;
  font-size: 30rpx;
  color: #111827;
}

.row-value {
  display: flex;
  flex: 1;
  justify-content: flex-end;
  min-width: 0;
}

.row-avatar-img {
  width: 96rpx;
  height: 96rpx;
  border-radius: 16rpx;
  background: #f3f4f6;
}

.row-avatar-ph {
  display: flex;
  width: 96rpx;
  height: 96rpx;
  align-items: center;
  justify-content: center;
  border-radius: 16rpx;
  background: linear-gradient(145deg, #7fb069, #4a90e2);
}

.row-avatar-letter {
  font-size: 36rpx;
  font-weight: 600;
  color: #fff;
}

.row-value-text {
  flex: 1;
  padding-right: 8rpx;
  font-size: 30rpx;
  color: #111827;
  text-align: right;
}

.row-value-text--muted {
  color: #6b7280;
}

.row-chev {
  flex-shrink: 0;
  margin-left: 8rpx;
  font-size: 32rpx;
  color: #d1d5db;
  font-weight: 300;
}

.row--static {
  pointer-events: none;
}

.row--static-value {
  flex: 1;
  padding-right: 32rpx;
  text-align: right;
}

.row-divider {
  height: 1rpx;
  margin-left: 32rpx;
  background: #f0f0f0;
}

.modal-mask {
  position: fixed;
  inset: 0;
  z-index: 400;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48rpx 40rpx;
  box-sizing: border-box;
  background: rgba(0, 0, 0, 0.45);
}

.modal-dialog {
  width: 100%;
  max-width: 620rpx;
  padding: 36rpx 32rpx 28rpx;
  border-radius: 24rpx;
  background: #fff;
  box-sizing: border-box;
  box-shadow: 0 24rpx 80rpx rgba(0, 0, 0, 0.18);
}

.modal-dialog--bio {
  max-height: min(72vh, 900rpx);
  overflow-y: auto;
}

.modal-dialog--gender {
  padding-bottom: 20rpx;
}

.modal-title {
  display: block;
  margin-bottom: 28rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  text-align: center;
}

.modal-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  margin-bottom: 32rpx;
  font-size: 30rpx;
  border: 1rpx solid #e5e7eb;
  border-radius: 16rpx;
  background: #f9fafb;
  box-sizing: border-box;
}

.modal-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx 24rpx;
  margin-bottom: 32rpx;
  font-size: 30rpx;
  line-height: 1.5;
  border: 1rpx solid #e5e7eb;
  border-radius: 16rpx;
  background: #f9fafb;
  box-sizing: border-box;
}

.modal-actions {
  display: flex;
  gap: 24rpx;
}

.modal-btn {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
  border-radius: 16rpx;
  box-sizing: border-box;
}

/* 与底部「保存」同主色；取消为同系描边 */
.modal-btn--ghost {
  border: 2rpx solid #4a90e2;
  background: #fff;
}

.modal-btn--ghost text {
  font-size: 30rpx;
  font-weight: 500;
  color: #4a90e2;
}

.modal-btn--primary {
  background: linear-gradient(90deg, #4a90e2, #50c8d8);
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.3);
}

.modal-btn--primary text {
  font-size: 30rpx;
  font-weight: 600;
  color: #fff;
}

.gender-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 24rpx;
  margin-bottom: 12rpx;
  border-radius: 16rpx;
  background: #f9fafb;
}

.gender-row--on {
  background: rgba(74, 144, 226, 0.1);
}

.gender-row-txt {
  font-size: 30rpx;
  color: #111827;
}

.gender-row-check {
  font-size: 32rpx;
  font-weight: 600;
  color: #4a90e2;
}

.modal-btn-block {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 16rpx;
  padding: 24rpx;
  border-radius: 16rpx;
  box-sizing: border-box;
}

.modal-btn-block--ghost {
  border: 2rpx solid #4a90e2;
  background: #fff;
}

.modal-btn-block--ghost text {
  font-size: 30rpx;
  font-weight: 500;
  color: #4a90e2;
}
</style>
