<template>
  <div class="main-wrapper">
    <div class="row justify-content-center">
      <div class="col-lg-8">
        <div class="card shadow-sm border-0 mt-4">
          <div class="card-header bg-gradient text-white py-4">
            <h4 class="mb-0">个人中心</h4>
            <p class="mb-0 small">管理您的账户信息与安全设置</p>
          </div>
          <div class="card-body">

            <!-- 用户头像 -->
            <div class="text-center mb-4">
              <img :src="baseUrl + user.avatar" class="rounded-circle border" width="100" height="100" />
              <div class="mt-2">
                <button class="btn btn-outline-primary btn-sm" @click="editingSection = 'avatar'">修改头像</button>
              </div>
            </div>

            <!-- 用户信息列表 -->
            <ul class="list-group list-group-flush">
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><strong>用户名：</strong>{{ user.userName }}</span>
                <button class="btn btn-link" @click="openEdit('userName')" disabled>修改</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><strong>邮箱：</strong>{{ user.email }}</span>
                <button class="btn btn-link" @click="openEdit('email')" disabled>修改</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><strong>权限：</strong>{{ (user.roles[1] ? '管理员' : '普通用户') || '无' }}</span>
                <button class="btn btn-link" @click="openEdit('bio')" disabled>修改</button>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <div class="flex-grow-1">
                  <strong>API Key：</strong>
                  <span v-if="!showApiKey">************</span>
                  <span v-else>{{ user.apiKey ? user.apiKey : '首次请重置Key' }}</span>
                </div>
                <div class="btn-group">
                  <button class="btn btn-sm btn-outline-secondary" @click="toggleApiKey">
                    {{ showApiKey ? '隐藏' : '显示' }}
                  </button>
                  <button class="btn btn-sm btn-outline-primary" @click="copyApiKey">
                    复制
                  </button>
                  <button class="btn btn-sm btn-outline-danger" @click="regenerateApiKey">
                    重置
                  </button>
                </div>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><strong>登录密码：</strong>********</span>
                <button class="btn btn-link" @click="openEdit('password')">修改</button>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 弹出框 -->
    <div v-if="editingSection" class="modal fade show d-block" tabindex="-1" style="background-color: rgba(0,0,0,0.5);">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">修改 {{ getSectionTitle(editingSection) }}</h5>
            <button type="button" class="btn-close" @click="closeEdit"></button>
          </div>
          <div class="modal-body">
            <!-- 各字段弹出表单内容 -->
            <div v-if="editingSection === 'nickname'">
              <input type="text" class="form-control" v-model="form.nickname" placeholder="请输入昵称" />
            </div>
            <div v-else-if="editingSection === 'email'">
              <input type="email" class="form-control" v-model="form.email" placeholder="请输入邮箱" />
            </div>
            <div v-else-if="editingSection === 'phone'">
              <input type="text" class="form-control" v-model="form.phone" placeholder="请输入手机号" />
            </div>
            <div v-else-if="editingSection === 'gender'">
              <select class="form-control" v-model="form.gender">
                <option value="male">男</option>
                <option value="female">女</option>
                <option value="other">其他</option>
              </select>
            </div>
            <div v-else-if="editingSection === 'bio'">
              <textarea class="form-control" rows="3" v-model="form.bio" placeholder="简单介绍一下你自己"></textarea>
            </div>
            <div v-else-if="editingSection === 'password'">
              <input type="password" class="form-control mb-2" v-model="form.newPassword" placeholder="新密码" />
              <input type="password" class="form-control" v-model="form.confirmPassword" placeholder="确认新密码" />
              <div class="invalid-feedback" style="display: block;" v-if="form.newPassword !== form.confirmPassword">
                两次密码不一致</div>
            </div>
            <div v-else-if="editingSection === 'avatar'">
              <input type="file" class="form-control" @change="onAvatarChange" accept="image/*" />
              <img :src="previewAvatar" class="mt-3 rounded-circle" width="80" v-if="previewAvatar" />
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-secondary" @click="closeEdit">取消</button>
            <button class="btn btn-primary" @click="saveEdit">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axiosInstance from '@/request/request';
import md5 from 'blueimp-md5';

export default {
  name: "UserProfilePanel",
  data() {
    return {
      showApiKey:false,
      baseUrl: '',
      user: {
        userName: '',
        email: '',
        roles: [],
        avatar: '',
        apiKey: null
      },
      editingSection: null,
      form: {},
      previewAvatar: null,
      loaded: false,
      avatarFile: null
    };
  },
  methods: {
    openEdit(section) {
      this.editingSection = section;
      this.form = { ...this.user }; // clone
    },
    closeEdit() {
      this.editingSection = null;
      this.previewAvatar = null;
    },
    async saveEdit() {
      if (this.editingSection === 'password') {
        if (this.form.newPassword !== this.form.confirmPassword) {
          return;
        }
        // 处理密码更新逻辑
        await this.updatePassword()
      } else if (this.editingSection === 'avatar') {
        if (this.previewAvatar) {
          await this.saveAvatar()
        }
      } else {
        Object.assign(this.user, this.form);
      }

      this.closeEdit();
    },
    async saveAvatar() {
      // 上传
      try {
        const formData = new FormData();
        formData.append('file', this.avatarFile);
        const res = await this.$api.uploadAvatar(formData)
        if (res.code != 1000) {
          this.$alert(res.message, 'danger')
          return
        }
        this.$alert('保存成功', 'success')
      } catch (e) {
        this.$alert('上传头像失败', 'danger')
        console.error(e)
      }
    },
    getSectionTitle(section) {
      const map = {
        userName: "用户名",
        email: "邮箱",
        password: "密码",
        avatar: "头像"
      };
      return map[section] || "信息";
    },
    onAvatarChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = (event) => {
        this.previewAvatar = event.target.result;
      };
      reader.readAsDataURL(file);
      this.avatarFile = file
    },
    async loadUserInfo() {
      try {
        const res = await this.$api.getUserInfo();
        if (res.code != 1000) {
          this.$alert(res.message, 'danger')
          return
        }
        this.user = res.data
      } catch (e) {
        this.$alert('获取用户信息失败', 'danger')
        console.error(e)
      }
    },
    async updatePassword() {
      try {
        const res = await this.$api.updateMyInfo({ password: md5(this.form.newPassword) })
        if (res.code != 1000) {
          this.$alert(res.message, 'danger')
          return
        }
        this.$alert('修改成功', 'success')
      } catch (e) {
        this.$alert('修改密码失败', 'danger')
        console.error(e)
      }

    },
    toggleApiKey(){
      if(this.showApiKey){
        this.showApiKey = false
      }else{
        this.showApiKey = true
      }
    },
    async regenerateApiKey(){
      try{
        const res = await this.$api.setApiKey()
        if(res.code != 1000){
          this.$alert(res.message,'danger')
          return
        }
        this.$alert('重置成功','success')
        this.user.apiKey = res.data
      }catch(e){
        this.$alert('生成key失败','danger')
        console.error(e)
      }
    },
    copyApiKey(){
      navigator.clipboard.writeText(this.user.apiKey).then(() => {
      this.$alert('已复制到剪贴板','success');
      })
    }
  },
  async mounted() {
    await this.loadUserInfo()
    this.baseUrl = axiosInstance.defaults.baseURL
    this.loaded = true
  }
};
</script>

<style scoped>
.bg-gradient {
  background: linear-gradient(to right, #4e73df, #1cc88a);
}

.modal {
  z-index: 1050;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.2rem;
}
</style>
