import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import DictionariesBehavior from "../../../../core/behavior/dictionaries.behavior";
import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { PageLoadBehavior } from "../../../../core/behavior/page-loading.behavior";
import { getUserInfoMethod, updateUserInfoMethod } from "../../request";

// module/user/pages/user-edit/user-edit.ts
Component({
  behaviors: [
    PageContainerBehavior,
    PageLoadBehavior<App.Patient.Model>(getUserInfoMethod),
    DictionariesBehavior,
    tickleBehavior,
  ],
  lifetimes: {
    attached() { },
  },
  properties: {},
  data: {
    model: null as App.Patient.Model | null,
    name: "",
    cardno: "",
    age: "",
    sex: "",
    dirty: false,
    idCardValid: false,
  },
  observers: {
    'model.cardno'(value: string) {
      const that = this as any;
      const v = (value || '').trim();
      if (!v) return that.setData({ idCardValid: false });
      if (/^\d{17}[\dXx]$/.test(v)) {
        const { valid } = (that as any).validateIdCard18(v);
        that.setData({ idCardValid: !!valid });
      } else {
        that.setData({ idCardValid: false });
      }
    },
  },
  methods: {
    validateIdCard18(cardno: string): { valid: boolean; message?: string } {
      const code = (cardno || '').toUpperCase();
      if (!/^\d{17}[\dX]$/.test(code)) return { valid: false, message: '身份证号格式不正确' };
      const year = parseInt(code.substring(6, 10));
      const month = parseInt(code.substring(10, 12));
      const day = parseInt(code.substring(12, 14));
      const birth = new Date(year, month - 1, day);
      if (
        birth.getFullYear() !== year ||
        birth.getMonth() + 1 !== month ||
        birth.getDate() !== day
      ) return { valid: false, message: '出生日期无效' };
      const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      const Vi = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
      let sum = 0;
      for (let i = 0; i < 17; i++) sum += parseInt(code[i]) * Wi[i];
      const check = Vi[sum % 11];
      if (check !== code[17]) return { valid: false, message: '校验位错误' };
      return { valid: true };
    },
    onFormInput(event: WechatMiniprogram.Input) {
      const that = this as any;
      const field = (event.currentTarget?.dataset as any)?.field || (event.target?.dataset as any)?.field;
      if (!field) return;
      const value = (event.detail as any)?.value;
      if (field === 'cardno') {
        that.updateByCardno(value);
      } else if (field === 'age') {
        that.setData({ ['model.age']: value });
      } else if (field === 'name') {
        that.setData({ ['model.name']: value });
      }
    },
    onFormChange(event: WechatMiniprogram.CustomEvent) {
      const that = this as any;
      const { name, value } = (event.detail as any) || {};
      if (!name) return;
      that.setData({ [`model.${name}`]: value });
    },
    onSexChange(event: WechatMiniprogram.CustomEvent) {
      const that = this as any;
      const value = (event as any)?.detail; // field-radio 直接传递选中值
      that.setData({ ['model.sex']: value.sex });
    },
    updateByCardno(cardno?: string) {
      const that = this as any;
      const normalized = (cardno || '').trim();
      that.setData({ ['model.cardno']: normalized });
      if (!normalized) {
        // 清空身份证：同步清空年龄与性别
        return that.setData({ ['model.age']: '', ['model.sex']: '', idCardValid: false });
      }
      // 仅支持18位身份证解析
      if (/^\d{17}[\dXx]$/.test(normalized)) {
        const { valid, message } = (this as any).validateIdCard18(normalized);
        if (!valid) {
          that.setData({ ['model.age']: '', ['model.sex']: '', idCardValid: false });
          return getTickleContext.call(that).showWarnMessage(message || '身份证号不合法');
        }
        const year = parseInt(normalized.substring(6, 10));
        const month = parseInt(normalized.substring(10, 12));
        const day = parseInt(normalized.substring(12, 14));
        const birth = new Date(year, month - 1, day);
        const now = new Date();
        let age = now.getFullYear() - birth.getFullYear();
        const m = now.getMonth() - birth.getMonth();
        if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) age--;
        const sexCode = parseInt(normalized.substring(16, 17));
        // 字典通常 0=男 1=女 或 1=女? 需与现有校验一致：文件中 womenSpecialPeriod 用 sex==='1' 判断为女性
        const sex = sexCode % 2 === 0 ? '1' : '0';
        that.setData({ ['model.age']: age, ['model.sex']: sex, idCardValid: true });
      } else {
        // 未满18位时，实时清空由身份证推导的年龄/性别，保持可编辑
        that.setData({ ['model.age']: '', ['model.sex']: '', idCardValid: false });
      }
    },
    async onSubmit(event: WechatMiniprogram.FormSubmit) {
      console.log(event, "onSubmit");
      this.setData({ dirty: true });
      const data = { ...this.data.model, ...event?.detail?.value } as any;
      console.log(data, "穿的数据");
      // 如填写了身份证，进行18位身份证合法性校验
      if (data.cardno) {
        const { valid, message } = (this as any).validateIdCard18((data.cardno || '').toString());
        if (!valid) return this.showMessageAndDirty(message || '身份证号不合法');
      }
      // 必填：年龄、性别
      if (!data.age) return this.showMessageAndDirty("请填写年龄");
      if (data.sex === undefined || data.sex === null || data.sex === '') return this.showMessageAndDirty("请选择性别");
      if (!data.patientId) data.patientId = wx.getStorageSync("patientId");
      // 表单验证
      if (data.sex.toString() === "1" && !data.womenSpecialPeriod) return this.showMessageAndDirty("请至少选择一项女性特殊期");
      if (!data.height) return this.showMessageAndDirty("请填写身高");
      if (!data.weight) return this.showMessageAndDirty("请填写体重");
      try {
        console.log(data, "data");
        await updateUserInfoMethod(<any>data)
        wx.navigateBack();
        this.getOpenerEventChannel().emit("update2", event.detail.value);
      } catch (error) {
        const msg = (error as any)?.errMsg || '更新失败';
        this.showMessageAndDirty(msg);
      }
    },
    showMessageAndDirty(message: string) {
      if (message) getTickleContext.call(this).showWarnMessage(message);
      setTimeout(() => this.setData({ dirty: false }), 200);
    },
  },
});
