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

import { openPrivacyContract } from "../../../../lib/wx/open-api";

// module/user/pages/user-certification/user-certification.ts
import { createUserInfoMethod, verifyCardnoMethod } from "../../request"
import { usePhoneNumber } from "../../../../lib/use/use-phone";

Component({
  behaviors: [
    PageContainerBehavior,
    DictionariesBehavior,
    tickleBehavior,
  ],
  lifetimes: {
    attached() {
      const channel = this.getOpenerEventChannel();
      channel.on('navigateBack', (data) => { this.setData(data); })

      const { getPhoneNumber, updateStatus, updateValue } = usePhoneNumber();
      this.getPhoneNumber = <any>getPhoneNumber;
      updateStatus(status => this.setData({ 'loading': status === 'loading' }));
      updateValue(value => this.setData({ 'model.phone': value }));
    }
  },
  properties: {},
  data: {
    hide: false,
    loading: false,
    verifying: false,
    model: {} as AnyObject,
    privacyContract: { agree: false, name: '《隐私政策》', show: false },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getPhoneNumber() { /** usePhoneNumber 中实现 */ },
    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 });
    },
    async verifyCardno(event: WechatMiniprogram.InputConfirm) {
      const value = event.detail.value;
      if (value.length !== 18) { wx.showToast({ title: '请输入正确的身份证号', icon: 'none' }); }
      else {
        this.setData({ verifying: true });
        try {
          const data = await verifyCardnoMethod(value);
          this.setData({ 'model.age': data.age, 'model.sex': data.sex });
        } catch (error) {
          this.setData({ 'model.cardno': '', 'model.age': '', 'model.sex': '' });
          wx.showToast({ title: error.errMsg, icon: 'error' });
        }
        this.setData({ verifying: false });
      }
    },
    async onSubmit(event: WechatMiniprogram.FormSubmit) {
      const data = { ...this.data.model, ...event.detail.value };
      // if (!data.phone) return getTickleContext.call(this).showWarnMessage('请获取手机号码');
      data.phone = '13012344322'
      if (!data.name) return getTickleContext.call(this).showWarnMessage('请输入姓名');
      if (data.cardno?.length !== 18) return getTickleContext.call(this).showWarnMessage('请输入正确的身份证号');
      if (data.sex === '1' && !data.womenSpecialPeriod) return getTickleContext.call(this).showWarnMessage('请至少选择一项女性特殊期');
      if (!data.height) return getTickleContext.call(this).showWarnMessage('请输入身高');
      if (!data.weight) return getTickleContext.call(this).showWarnMessage('请输入体重');
      console.log(data);
      if (!this.data.privacyContract.agree) { wx.showToast({ title: `请阅读并同意${this.data.privacyContract.name}`, icon: 'none' }) }

      wx.showLoading({ title: '保存中' });
      try {
        const { patientId } = await createUserInfoMethod(<any>data);
        await wx.navigateBack();
        if (patientId) this.getOpenerEventChannel().emit('update', { patientId });
      } catch (error) {
        getTickleContext.call(this).showErrorMessage(error.errMsg);
      }
      wx.hideLoading()
    }
  },
})