const { birthInfoToBazi, analyzeElementBalance } = require('../../utils/core/index.js');

Page({
  data: {
    gender: 'male',
    birthDate: '1990-01-01',
    birthTime: '12:00',
    ziSect: 'lateZiNextDay',
    bazi: null,
    pillars: [],
    elements: [],
    elementAnalysis: {}
  },

  onLoad() {
    // 尝试从本地存储恢复
    const saved = wx.getStorageSync('lunar-bazi-input');
    if (saved) {
      this.setData(saved);
    }
  },

  setGender(e) {
    this.setData({ gender: e.currentTarget.dataset.g });
  },

  setZiSect(e) {
    this.setData({ ziSect: e.currentTarget.dataset.s });
  },

  onDateChange(e) {
    this.setData({ birthDate: e.detail.value });
  },

  onTimeChange(e) {
    this.setData({ birthTime: e.detail.value });
  },

  calculate() {
    const { gender, birthDate, birthTime, ziSect } = this.data;
    const [year, month, day] = birthDate.split('-').map(Number);
    const [hour, minute] = birthTime.split(':').map(Number);

    const bazi = birthInfoToBazi({ year, month, day, hour, minute, gender, ziSect });
    const elementAnalysis = analyzeElementBalance(bazi.eightChar);

    const pillars = [
      { label: '年柱', ...bazi.eightChar.yearPillar },
      { label: '月柱', ...bazi.eightChar.monthPillar },
      { label: '日柱', ...bazi.eightChar.dayPillar },
      { label: '时柱', ...bazi.eightChar.hourPillar }
    ];

    const total = elementAnalysis.total || 1;
    const elements = [
      { name: '木', count: elementAnalysis.wood, percent: Math.round(elementAnalysis.wood / total * 100) },
      { name: '火', count: elementAnalysis.fire, percent: Math.round(elementAnalysis.fire / total * 100) },
      { name: '土', count: elementAnalysis.earth, percent: Math.round(elementAnalysis.earth / total * 100) },
      { name: '金', count: elementAnalysis.metal, percent: Math.round(elementAnalysis.metal / total * 100) },
      { name: '水', count: elementAnalysis.water, percent: Math.round(elementAnalysis.water / total * 100) }
    ];

    this.setData({ bazi, pillars, elements, elementAnalysis });

    // 保存输入
    wx.setStorageSync('lunar-bazi-input', { gender, birthDate, birthTime, ziSect });
    // 保存八字供运势页使用
    wx.setStorageSync('lunar-user-bazi', bazi);
  },

  reset() {
    this.setData({ bazi: null });
  },

  goFortune() {
    wx.switchTab({ url: '/pages/fortune/fortune' });
  }
});
