const apiClient = require('../../utils/api-client.js');


const occupationOptions = [
  "初中生", "高中生", "大学生", "研究生", "留学生", "科研", "警察", "医生", "护士",
  "程序员", "老师", "化妆师", "摄影师", "音乐", "美术", "金融", "厨师", "工程师",
  "公务员", "互联网", "产品经理", "模特", "演员", "导演", "律师", "创业者", "其他"
];
const educationOptions = ["博士", "硕士", "本科", "专科", "中专", "高中", "初中", "小学", "其他"];
const genderOptions = ["未知", "男", "女", "其他"];
const genderMap = {
  "未知": 0,
  "男": 1,
  "女": 2,
  "其他": 3
}
const constellationOptions = ["双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座", "水瓶座"];
const personalityOptions = ["INTJ", "INTP", "ENTJ", "INFP", "ENTP", "INFJ", "ENFP", "ENFJ", "ISTJ", "ISFJ", "ISTP", "ISFP", "ESTJ", "ESFJ", "ESTP", "ESFP"];
const sleepOptions = ["早起鸟儿", "夜猫子", "规律型", "深度睡眠追求者", "碎片化睡眠者", "失眠困扰者", "咖啡因敏感型", "数字戒断者", "运动调节型", "挑战打卡型", "鼾声监测者", "生物钟调节者", "社区分享型"];
const socialOptions = ["内容创作者", "观察者", "吃瓜者", "潜水者", "机器人", "社群型用户", "KOL", "KOC", "普通用户", "算法依赖型用户", "事件驱动型用户", "季节性活跃用户", "社交维系型用户", "兴趣社群型用户", "职业网络型用户", "娱乐消遣型用户", "购物种草型用户", "互动型用户"];
const heightOptions = Array.from({ length: 71 }, (_, i) => (140 + i) + "cm");

Page({
  data: {
    occupationOptions,
    educationOptions,
    genderOptions,
    constellationOptions,
    personalityOptions,
    sleepOptions,
    socialOptions,
    heightOptions,

    user: {
      avatar: "/images/default-avatar.png",
      customId: "10000123",
      nickname: "realrain",
      bio: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate libero et velit interdum, ac aliquet odio mattis.",
      occupation: "程序员",
      education: "本科",
      gender: "男",
      birthday: "1999-04-25",
      hometown: [],
      constellation: "金牛座",
      height: "175cm",
      personality: "INTJ",
      sleep: "夜猫子",
      social: "普通用户"
    },

    // 编辑态
    isEditing: false,
    editingIntro: false,
    tempIntro: "",
    tempNickname: "",

    // sheet 控制
    showSheet: false,
    sheetOptions: [],
    sheetTitle: "",
    sheetKey: "",
    selectedValue: ""
  },

  getKeyByValue(obj, value) {
    return Object.keys(obj).find(key => obj[key] === value);
  },

  async onLoad() {
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1];    // 当前页面实例
    const profile = pages[pages.length - 2];    // 上一个页面实例（profile）
    if (profile && profile.initSystemInfo) {
      profile.initSystemInfo();
    }
    if (profile && profile.loadUserData) {
      profile.loadUserData();
    }
    const clearData = this.clearObjectValues(this.data.user);
    // const appData = app.globalData.userInfo?.user;
    const appData = await apiClient.getUserInfo();
    if (appData?.code === 0) {
      appData.data.gender = this.getKeyByValue(genderMap, appData['data']['gender'])
    }
    this.setData({ user: appData.data ?? clearData });
  },

  onUnload() {
    console.log('页面被物理返回键关闭');
    // 更新用户信息
    const user = this.data.user;
    user['gender'] = genderMap[user.gender];
    apiClient.updateUserProfile(user)
      .then(res => {
        console.log('更新用户信息成功', res);
        wx.showToast({ title: '更新用户信息成功', icon: 'success' });
      })
      .catch(err => {
        console.error('更新用户信息失败', err);
        wx.showToast({ title: '更新用户信息失败', icon: 'none' });
      });
  },

  clearObjectValues(obj) {
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      if (Array.isArray(value)) {
        // 清空为新数组
        obj[key] = [];
      } else {
        const map = {
          'object': {},
          'string': '',
          'number': 0,
          'boolean': false,
        }
        const type = typeof value;
        obj[key] = map[type] ?? null;
      }
    });
    return obj
  },

  /* ---------- 头像 -------------- */
  chooseAvatar() {
    const pages = getCurrentPages();
    const profile = pages[pages.length - 2];    // 上一个页面实例（profile）
    if (profile && profile.changeAvatar) {
      console.log('执行更换头像方法=======>', profile.changeAvatar());
      profile.changeAvatar();
    }
  },

  // chooseImage(useCamera) {
  //   const self = this;
  //   wx.chooseImage({
  //     count: 1,
  //     sizeType: ['compressed'],
  //     sourceType: useCamera ? ['camera'] : ['album'],
  //     success(res) {
  //       const tempPath = res.tempFilePaths[0];
  //       const user = Object.assign({}, self.data.user, { avatar: tempPath });
  //       self.setData({ user });
  //       wx.setStorageSync('user_profile_v1', user);
  //     }
  //   });
  // },

  startEdit() {
    this.setData({
      isEditing: true,
      tempNickname: this.data.user.nickname
    });
  },
  onInput(e) {
    this.setData({
      tempNickname: e.detail.value
    });
  },
  confirmEdit() {
    if (!this.data.tempNickname) return;
    const user = Object.assign({}, this.data.user, { nickname: this.data.tempNickname });
    this.setData({ user });
    this.setData({
      isEditing: false
    });
  },
  onBlur() {
    this.setData({
      isEditing: false
    });
  },
  /* ---------- 昵称 ---------- */
  onEditNickname() {
    this.setData({
      editingNickname: !this.data.editingNickname,
      tempNickname: this.data.user.nickname || ""
    });
  },

  /* ---------- 个人简介 ---------- */
  toggleIntroEdit() {
    this.setData({
      editingIntro: !this.data.editingIntro,
      tempIntro: this.data.user.bio || ""
    });
  },

  onIntroInput(e) {
    this.setData({ tempIntro: e.detail.value });
  },

  cancelIntro() {
    this.setData({ editingIntro: false, tempIntro: "" });
  },

  saveIntro() {
    const user = Object.assign({}, this.data.user, { bio: this.data.tempIntro });
    this.setData({ user, editingIntro: false, tempIntro: "" });
    // 更新用户信息
    // apiClient.updateUserProfile(user)
    //   .then(res => {
    //     console.log('更新用户信息成功', res);
    //     wx.showToast({ title: '更新用户信息成功', icon: 'success' });
    //     this.setData({ user, editingIntro: false, tempIntro: "" });
    //   })
    //   .catch(err => {
    //     console.error('更新用户信息失败', err);
    //     wx.showToast({ title: '更新用户信息失败', icon: 'none' });
    //   });
  },

  /* ---------- bottom sheet 通用打开 ---------- */
  openSheet(e) {
    // data-options 会以字符串形式传入，如果直接传对象需要自定义组件
    // 这里我们支持两种写法：如果元素上有 data-options 属性且为 JSON 字符串，则尝试解析（注意：wxml 中直接传数组会被字符串化）
    const dataset = e.currentTarget.dataset || {};
    const key = dataset.key;
    const title = dataset.title || '请选择';
    let options = dataset.options;

    // dataset.options 在 wxml 传递数组时通常会变成字符串 "[object Object]" —— 我们优先根据 key 在定义好的数组中取
    if (!options || typeof options === 'string') {
      // if (key === 'occupation') options = occupationOptions;
      // else if (key === 'education') options = educationOptions;
      // else if (key === 'gender') options = genderOptions;
      // else if (key === 'constellation') options = constellationOptions;
      // else if (key === 'personality') options = personalityOptions;
      // else if (key === 'sleep') options = sleepOptions;
      // else if (key === 'social') options = socialOptions;
      // else if (key === 'height') options = heightOptions;
      // else options = [];
      const map = {
        occupation: occupationOptions,
        education: educationOptions,
        gender: genderOptions,
        // constellation: constellationOptions,
        personality: personalityOptions,
        sleep: sleepOptions,
        social: socialOptions,
        height: heightOptions,
      }
      options = map[key] || [];
    }
    const selectedValue = this.data.user[key] || "";

    this.setData({
      showSheet: true,
      sheetOptions: options,
      sheetTitle: title,
      sheetKey: key,
      selectedValue
    });
  },

  closeSheet() {
    this.setData({ showSheet: false, sheetOptions: [], sheetTitle: "", sheetKey: "", selectedValue: "" });
  },

  onSheetSelect(e) {
    const idx = e.currentTarget.dataset.index;
    const val = this.data.sheetOptions[idx];
    const key = this.data.sheetKey;
    if (!key) return this.closeSheet();

    const user = Object.assign({}, this.data.user);
    user[key] = val;
    this.setData({ user, selectedValue: val }, () => {
      this.closeSheet();
    });
    // 更新用户信息
    // apiClient.updateUserProfile(user)
    //   .then(res => {
    //     console.log('更新用户信息成功', res);
    //     wx.showToast({ title: '更新用户信息成功', icon: 'success' });
    //     this.setData({ user, selectedValue: val }, () => {
    //       this.closeSheet();
    //     });
    //   })
    //   .catch(err => {
    //     console.error('更新用户信息失败', err);
    //     wx.showToast({ title: '更新用户信息失败', icon: 'none' });
    //   });
  },

  /* ---------- 生日 ---------- */
  onBirthdayChange(e) {
    const val = e.detail.value;
    const user = Object.assign({}, this.data.user, { birthday: val });
    // 更新星座
    const [y, m, d] = val.split('-').map(x => parseInt(x, 10));
    user.constellation = this.estimateConstellation(m, d);
    this.setData({ user });
    // 更新用户信息
    // apiClient.updateUserProfile(user)
    //   .then(res => {
    //     console.log('更新用户信息成功', res);
    //     wx.showToast({ title: '更新用户信息成功', icon: 'success' });
    //     this.setData({ user });
    //   })
    //   .catch(err => {
    //     console.error('更新用户信息失败', err);
    //     wx.showToast({ title: '更新用户信息失败', icon: 'none' });
    //   });
  },

  estimateConstellation(m, d) {
    if ((m === 3 && d >= 21) || (m === 4 && d <= 19)) return "白羊座";
    if ((m === 4 && d >= 20) || (m === 5 && d <= 20)) return "金牛座";
    if ((m === 5 && d >= 21) || (m === 6 && d <= 21)) return "双子座";
    if ((m === 6 && d >= 22) || (m === 7 && d <= 22)) return "巨蟹座";
    if ((m === 7 && d >= 23) || (m === 8 && d <= 22)) return "狮子座";
    if ((m === 8 && d >= 23) || (m === 9 && d <= 22)) return "处女座";
    if ((m === 9 && d >= 23) || (m === 10 && d <= 23)) return "天秤座";
    if ((m === 10 && d >= 24) || (m === 11 && d <= 22)) return "天蝎座";
    if ((m === 11 && d >= 23) || (m === 12 && d <= 21)) return "射手座";
    if ((m === 12 && d >= 22) || (m === 1 && d <= 19)) return "摩羯座";
    if ((m === 1 && d >= 20) || (m === 2 && d <= 18)) return "水瓶座";
    return "双鱼座";
  },

  /* ---------- 家乡 ---------- */
  onHometownChange(e) {
    const nick = e.detail?.value ?? this.data.user.hometown;
    const user = Object.assign({}, this.data.user, { hometown: nick });
    this.setData({ user });
    // 更新用户信息
    // apiClient.updateUserProfile(user)
    //   .then(res => {
    //     console.log('更新用户信息成功', res);
    //     wx.showToast({ title: '更新用户信息成功', icon: 'success' });
    //     this.setData({ user });
    //   })
    //   .catch(err => {
    //     console.error('更新用户信息失败', err);
    //     wx.showToast({ title: '更新用户信息失败', icon: 'none' });
    //   });
  }
});