<script setup lang="ts">
/**
 * 个人中心 - 基本资料
 * 可编辑：头像（复用表单 Avatar 上传组件）、昵称（与后端 update-my-profile 白名单一致）
 * 只读展示：登录账号/手机号/角色/所属门店/最后登录时间等（账号身份信息不允许自助修改）
 * 保存成功后重拉 my-info 刷新全局登录态，顶栏/工作台头像昵称立即生效
 */
import { computed, ref, watch } from 'vue';

import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useAuthStore } from '#/store/auth';

import { updateMyProfile } from './api';

const props = defineProps({
  profile: {
    type: Object,
    default: () => ({}),
  },
});
const emits = defineEmits(['saved']);

const authStore = useAuthStore();

/** 可编辑字段表单：仅头像 + 昵称，其余字段一律只读展示 */
const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    labelWidth: 80,
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Avatar',
      fieldName: 'avatar',
      label: '头像',
    },
    {
      component: 'VbenInput',
      fieldName: 'nick_name',
      label: '昵称',
      rules: 'required',
      componentProps: {
        placeholder: '请输入昵称',
        maxlength: 20,
      },
    },
  ],
  showDefaultActions: false,
});

// 父组件拉取到实时资料后回填表单（保存成功刷新后同样走这里）
watch(
  () => props.profile,
  (val: any) => {
    if (val && val.id) {
      formApi.setValues({
        avatar: val.avatar,
        nick_name: val.nick_name,
      });
    }
  },
  { deep: true, immediate: true },
);

/** 只读信息行：为空的可选字段（门店/工号/邮箱）不展示，避免一排「-」 */
const readonlyRows = computed(() => {
  const p: any = props.profile || {};
  const rows: { label: string; value: string }[] = [
    { label: '登录账号', value: p.login_account },
    { label: '手机号', value: p.phone },
    { label: '角色', value: p.role_name },
  ];
  if (p.store_name) {
    rows.push({ label: '所属门店', value: p.store_name });
  }
  if (p.job_number) {
    rows.push({ label: '工号', value: p.job_number });
  }
  if (p.email) {
    rows.push({ label: '邮箱', value: p.email });
  }
  rows.push({ label: '最后登录', value: p.last_login_time });
  rows.push({ label: '创建时间', value: p.created_at });
  return rows.map((row) => ({ ...row, value: row.value || '-' }));
});

const saving = ref(false);

/**
 * 保存资料：校验 → 提交白名单字段 → 重拉全局登录态 → 通知父组件刷新
 * 为什么要 fetchUserInfo：后端已刷新 Redis 会话，前端重拉 my-info 才能让顶栏/工作台立即显示新头像昵称
 */
function handleSave() {
  formApi.validate().then(async (e: any) => {
    if (!e.valid) return;
    const values = await formApi.getValues();
    saving.value = true;
    try {
      await updateMyProfile({
        nick_name: values.nick_name,
        avatar: values.avatar || '',
      });
      message.success('保存成功');
      await authStore.fetchUserInfo();
      emits('saved');
    } finally {
      saving.value = false;
    }
  });
}
</script>
<template>
  <div class="profile-base w-full lg:w-2/3">
    <Form />
    <Button type="primary" :loading="saving" @click="handleSave">
      保存资料
    </Button>
    <div class="profile-base__section-title">账号信息</div>
    <div class="profile-base__grid">
      <div
        v-for="row in readonlyRows"
        :key="row.label"
        class="profile-base__row"
      >
        <span class="profile-base__label">{{ row.label }}</span>
        <span class="profile-base__value">{{ row.value }}</span>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* 只读信息区：全部走主题变量，暗色模式自动适配 */
.profile-base__section-title {
  padding-bottom: 10px;
  margin-top: 28px;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 600;
  color: hsl(var(--foreground));
  border-bottom: 1px solid hsl(var(--border));
}

.profile-base__grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 0 24px;
}

.profile-base__row {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed hsl(var(--border) / 0.6);
}

.profile-base__label {
  flex-shrink: 0;
  width: 72px;
  font-size: 13px;
  color: hsl(var(--muted-foreground));
}

.profile-base__value {
  overflow: hidden;
  font-size: 13px;
  color: hsl(var(--foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .profile-base__grid {
    grid-template-columns: 1fr;
  }
}
</style>
