const MEMBER_KEY = 'family_member';

Page({
  data: {
    avatars: ['👤', '👨', '👩', '👴', '👵', '👶', '🧒', '👦', '👧'],
    relations: ['本人', '配偶', '父亲', '母亲', '儿子', '女儿', '爷爷', '奶奶', '外公', '外婆', '其他'],
    bloodTypes: ['A', 'B', 'AB', 'O', '未知'],
    relationIdx: -1,
    today: '',
    form: {
      avatar: '👤',
      name: '',
      gender: '',
      birthday: '',
      relation: '',
      bloodType: '',
      allergies: '',
      chronicDiseases: '',
      longTermMeds: '',
      notes: '',
    },
  },

  onLoad() {
    const today = new Date();
    this.setData({
      today: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`,
    });

    const member = wx.getStorageSync(MEMBER_KEY);
    if (member && member.name) {
      this.setData({
        form: { ...this.data.form, ...member },
        relationIdx: this.data.relations.indexOf(member.relation),
      });
    }
  },

  pickAvatar(e: WechatMiniprogram.TouchEvent) {
    this.setData({ 'form.avatar': e.currentTarget.dataset.avatar });
  },

  onField(e: WechatMiniprogram.Input) {
    this.setData({ [`form.${e.currentTarget.dataset.field}`]: e.detail.value });
  },

  onRelationChange(e: WechatMiniprogram.PickerChange) {
    const idx = Number(e.detail.value);
    this.setData({ relationIdx: idx, 'form.relation': this.data.relations[idx] });
  },

  onBirthdayChange(e: WechatMiniprogram.PickerChange) {
    this.setData({ 'form.birthday': e.detail.value });
  },

  pickGender(e: WechatMiniprogram.TouchEvent) {
    this.setData({ 'form.gender': e.currentTarget.dataset.gender });
  },

  pickBlood(e: WechatMiniprogram.TouchEvent) {
    this.setData({ 'form.bloodType': e.currentTarget.dataset.bt });
  },

  save() {
    if (!this.data.form.name.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    wx.setStorageSync(MEMBER_KEY, this.data.form);
    wx.showToast({ title: '已保存', icon: 'success' });
    setTimeout(() => wx.navigateBack(), 800);
  },
});
