const versionInfo = require('../../utils/version.js');
const { request } = require('../../utils/request.js');
const birthProfile = require('../../utils/birth-profile.js');

Page({
  data: {
    userInfo: null,
    loggedIn: false,
    logging: false,
    weekStartDay: 0,
    ziHourSect: 'lateZiNextDay',
    solarTime: true,
    showBuddhist: false,
    highlightLunar: true,
    bookmarks: [],
    // 生辰档案
    profiles: [],
    activeProfileId: '',
    maxFree: birthProfile.MAX_PROFILES,
    canAdd: true,
    showAddForm: false,
    formName: '',
    formGender: 'male',
    formDate: '1990-01-01',
    formTime: '12:00',
    version: versionInfo.version,
    buildNumber: versionInfo.buildNumber,
    buildTime: versionInfo.buildTime,
    commitSha: versionInfo.commitSha
  },

  onLoad() {
    this.loadSettings();
    this.loadBookmarks();
  },

  onShow() {
    this.loadBookmarks();
    this.loadProfiles();
  },

  loadSettings() {
    const settings = wx.getStorageSync('lunar-settings') || {};
    this.setData({
      weekStartDay: settings.weekStartDay || 0,
      ziHourSect: settings.ziHourSect || 'lateZiNextDay',
      solarTime: settings.solarTime !== false,
      showBuddhist: settings.showBuddhist === true,
      highlightLunar: settings.highlightLunar !== false
    });
  },

  saveSettings() {
    const { weekStartDay, ziHourSect, solarTime, showBuddhist, highlightLunar } = this.data;
    wx.setStorageSync('lunar-settings', { weekStartDay, ziHourSect, solarTime, showBuddhist, highlightLunar });
  },

  loadBookmarks() {
    const bookmarks = wx.getStorageSync('lunar-bookmarks') || [];
    this.setData({ bookmarks });
  },

  // ==================== 生辰档案 ====================

  loadProfiles() {
    const render = () => {
      const profiles = birthProfile.getProfiles();
      const active = birthProfile.getActiveProfile();
      this.setData({
        profiles,
        activeProfileId: active ? active.id : '',
        canAdd: profiles.length < this.data.maxFree
      });
    };
    // 已登录时先从服务端同步，失败静默回退本地
    if (birthProfile.isLoggedIn()) {
      birthProfile.syncFromServer().then(render).catch(render);
    } else {
      render();
    }
  },

  toggleAddForm() {
    if (!this.data.showAddForm && !this.data.canAdd) {
      wx.showToast({ title: `最多可免费绑定 ${this.data.maxFree} 个生辰`, icon: 'none' });
      return;
    }
    this.setData({ showAddForm: !this.data.showAddForm });
  },

  onFormName(e) {
    this.setData({ formName: e.detail.value });
  },

  setFormGender(e) {
    this.setData({ formGender: e.currentTarget.dataset.g });
  },

  onFormDate(e) {
    this.setData({ formDate: e.detail.value });
  },

  onFormTime(e) {
    this.setData({ formTime: e.detail.value });
  },

  submitProfile() {
    const { formName, formGender, formDate, formTime } = this.data;
    if (!formDate || !formTime) {
      wx.showToast({ title: '请选择出生日期和时间', icon: 'none' });
      return;
    }
    const result = birthProfile.addProfile({
      name: formName.trim() || '未命名',
      gender: formGender,
      birthday: formDate,
      birthTime: formTime
    });
    if (!result.ok) {
      wx.showToast({ title: result.msg, icon: 'none' });
      return;
    }
    // 已登录时推送到服务端（静默失败，不影响本地）
    birthProfile.pushProfileToServer(result.profile);
    this.setData({ showAddForm: false, formName: '' });
    wx.showToast({ title: '绑定成功', icon: 'success' });
    this.loadProfiles();
  },

  removeProfile(e) {
    const id = e.currentTarget.dataset.id;
    const profile = this.data.profiles.find(p => p.id === id);
    if (!profile) return;
    wx.showModal({
      title: '删除生辰',
      content: `确定删除「${profile.name}」的生辰信息吗？`,
      success: (res) => {
        if (!res.confirm) return;
        birthProfile.removeProfile(id);
        birthProfile.removeProfileFromServer(profile);
        wx.showToast({ title: '已删除', icon: 'success' });
        this.loadProfiles();
      }
    });
  },

  // ==================== 登录 ====================

  login() {
    if (this.data.logging) return;
    this.setData({ logging: true });
    wx.login({
      success: (loginRes) => {
        if (!loginRes.code) {
          this.setData({ logging: false });
          wx.showToast({ title: '微信登录失败', icon: 'none' });
          return;
        }
        request({
          url: '/api/user/login',
          method: 'POST',
          data: { code: loginRes.code }
        }).then((res) => {
          if (res && res.code === 0 && res.data && res.data.token) {
            wx.setStorageSync('token', res.data.token);
            wx.setStorageSync('lunar-user-info', res.data.user);
            this.setData({ userInfo: res.data.user, loggedIn: true, logging: false });
            wx.showToast({ title: '登录成功', icon: 'success' });
            // 登录后同步服务端生辰档案
            this.loadProfiles();
          } else {
            this.setData({ logging: false });
            wx.showToast({ title: (res && res.msg) || '登录失败', icon: 'none' });
          }
        }).catch(() => {
          this.setData({ logging: false });
          wx.showToast({ title: '登录失败，请稍后重试', icon: 'none' });
        });
      },
      fail: () => {
        this.setData({ logging: false });
        wx.showToast({ title: '微信登录失败', icon: 'none' });
      }
    });
  },

  logout() {
    wx.showModal({
      title: '退出登录',
      content: '退出后生辰档案仅保存在本机，重新登录可恢复云端档案',
      success: (res) => {
        if (!res.confirm) return;
        wx.removeStorageSync('token');
        wx.removeStorageSync('lunar-user-info');
        this.setData({ userInfo: null, loggedIn: false });
        wx.showToast({ title: '已退出', icon: 'success' });
      }
    });
  },

  // ==================== 偏好设置 ====================

  setWeekStart(e) {
    this.setData({ weekStartDay: Number(e.currentTarget.dataset.v) });
    this.saveSettings();
  },

  setZiSect(e) {
    this.setData({ ziHourSect: e.currentTarget.dataset.v });
    this.saveSettings();
  },

  onSolarTimeChange(e) {
    this.setData({ solarTime: e.detail.value });
    this.saveSettings();
  },

  onBuddhistChange(e) {
    this.setData({ showBuddhist: e.detail.value });
    this.saveSettings();
  },

  onHighlightLunarChange(e) {
    this.setData({ highlightLunar: e.detail.value });
    this.saveSettings();
  },

  removeBookmark(e) {
    const date = e.currentTarget.dataset.date;
    let bookmarks = this.data.bookmarks.filter(b => b.date !== date);
    wx.setStorageSync('lunar-bookmarks', bookmarks);
    this.setData({ bookmarks });
    wx.showToast({ title: '已删除', icon: 'success' });
  },

  navTo(e) {
    const url = e.currentTarget.dataset.url;
    // tabBar 页面必须用 switchTab 打开
    const tabPages = ['/pages/home/home', '/pages/wish-tree/wish-tree', '/pages/bazi/bazi', '/pages/wiki/wiki', '/pages/settings/settings', '/pages/fortune/fortune'];
    if (tabPages.includes(url)) {
      wx.switchTab({ url });
    } else {
      wx.navigateTo({ url });
    }
  }
});
