// components/popup-user-auth/popup-user-auth.ts
import { openPrivacyContract } from "../../lib/wx/open-api";
import { login } from "../../lib/logic";
import { usePhoneNumber } from "../../lib/use/use-phone";
import { getSceneRegisterMethod, setSceneRegisterMethod } from "../../lib/request/common";
let submitting = false;
Component({
  properties: {
    visible: { type: Boolean, value: false },
    overlay: { type: Boolean, value: true },
    scene: { type: String, value: '' },
    cardno: { type: String, value: '' },
    phone: { type: String, value: '' },
  },
  data: {
    title: '完善信息',
    privacyContract: { agree: false, name: "《隐私政策》", show: false },

    loading: false,
    submitting: false,

    cardnoProps: { prefix: '', suffix: '', fill: '', length: 0 },
    phoneProps: { prefix: '', suffix: '', fill: '', length: 0 },
  },
  observers: {
    cardno(value: string) {
      if (!value) return;
      const length = 18;
      const tag = '*';
      if (!value.includes(tag)) value = value.padEnd(length, tag);
      const [_, prefix = '', fill = '', suffix = ''] = value.match(/(\d+)?(\*+)?(\d+)?/) || [];
      this.setData({ cardnoProps: { prefix, suffix, fill: '', length: fill.length === length ? 0 : fill.length } });
      if (this.data.cardnoProps.length) this.setData({ visible: true });
    },
    phone(value: string) {
      if (!value) return;
      const length = 11;
      const tag = '*';
      if (!value.includes(tag)) value = value.padEnd(length, tag);
      const [_, prefix = '', fill = '', suffix = ''] = value.match(/(\d+)?(\*+)?(\d+)?/) || [];
      this.setData({ phoneProps: { prefix, suffix, fill: '', length: fill.length === length ? 0 : fill.length } });
      if (this.data.phoneProps.length) this.setData({ visible: true });
    },
    scene(value: string) { this.init(value); }
  },
  methods: {
    async init(scene: string) {
      if (!scene) return;
      await login();
      const data = await getSceneRegisterMethod(scene);
      this.setData({ ...data });
      this.triggerEvent('loaded', { visible: this.data.visible, scene });
      if (data.patientId) this.register(data.patientId);
    },
    getPhoneNumberHandle(event: WechatMiniprogram.ButtonGetPhoneNumber) {
      this.setData({ loading: true });
      const { getPhoneNumber } = usePhoneNumber();
      getPhoneNumber(event, (value) => {
        this.setData({ "phoneProps.fill": value, loading: false })
      })
    },
    openPrivacyContract: openPrivacyContract,
    onPrivacySetting({ detail }: { detail: WechatMiniprogram.GetPrivacySettingSuccessCallbackResult; }) {
      this.setData({
        "privacyContract.name": detail.privacyContractName,
        // 'privacyContract.agree': !detail.needAuthorization,
      });
    },
    onAgreeChange(event: any) {
      const agree = event?.detail?.checked;
      if (agree) this.setData({ "privacyContract.show": true });
      else this.setData({ "privacyContract.agree": agree });
    },
    onAgree() {
      this.setData({ "privacyContract.agree": true });
    },
    onDisagree() {
      this.setData({ "privacyContract.agree": false });
    },
    register(patientId: string) {
      if (!patientId) return;
      wx.setStorageSync("patientId", patientId);
      this.setData({ 'visible': false });
      this.triggerEvent('register', { patientId });
    },
    async onSubmit(event: WechatMiniprogram.FormSubmit) {
      if (this.data.submitting || submitting) return;
      submitting = true;
      try {
        const data = { agemust: this.data.privacyContract.agree ? 'Y' : 'N', phone: '' } as any;
        if (data.agemust === "N") {
          this.setData({ "privacyContract.show": true });
          throw `请阅读并同意${this.data.privacyContract.name}`;
        }

        const phone = this.data.phoneProps;
        if (phone.length && phone.fill.length !== phone.length) throw `手机号码请补充完整`;
        else if (!phone.fill) throw `请获取手机号码`;
        else data.phone = `${phone.prefix}${phone.fill}${phone.suffix}`;

        const cardno = this.data.cardnoProps;
        if (cardno.length && cardno.fill.length !== cardno.length) throw `身份证号请补充完整`;
        else if (cardno.length) data.cardno = `${cardno.prefix}${cardno.fill}${cardno.suffix}`;

        if (this.data.scene) data.scene = decodeURIComponent(this.data.scene);

        this.setData({ "submitting": submitting });
        const { patientId } = await setSceneRegisterMethod(data);
        this.register(patientId);
      } catch (error) {
        if (typeof error === 'string') this.triggerEvent('message', { type: 'warning', content: error });
        else if (error.errMsg) {
          this.triggerEvent('message', { type: 'error', content: error.errMsg });
          if (!this.data.phoneProps.length) this.setData({ "phoneProps.fill": '', loading: false });
        }
      }
      setTimeout(() => {
        submitting = false;
        this.setData({ "submitting": submitting });
      }, 100);
    },
  }
})