import { getHospitalizationInfo, saveAdmissionRegistration, editAdmissionRegistration } from './service';
import history from '../../utils/history';
import { checkPhone, checkIdCard } from '../edit-patient/check';
import getEncryptStr from '../../utils/getEncryptStr';
import loadOcr from '../../utils/loadOcr';
import doLogin from '../../utils/doLogin';
import { connect } from 'herculex';
Component(connect({
  mapStateToProps: {
    userInfo: ({
      $global
    }) => $global.userInfo || {}
  }
})({
  data: {
    isEdit: 'NO',
    // 是否是编辑
    inpatientId: '',
    // 住院记录id
    patientId: '',
    // 就诊人id
    form: {
      relationShip: '本人',
      // 就诊人与本人关系名称
      name: '',
      // 就诊人姓名
      sex: '',
      // 就诊人性别
      idCardType: '身份证',
      // 证件类型， 默认是身份证号 - 身份证
      idCardNo: '',
      // 证件号码
      phoneNumber: '',
      // 手机号
      inpatientNo: '' // 住院号

    },
    certTypes: ['身份证'],
    disableButton: true,
    sex: [{
      name: '男',
      value: '男'
    }, {
      name: '女',
      value: '女'
    }],
    isAuthSuccess: false,
    showOtherButton: 'false'
  },

  didMount() {
    const {
      inpatientId,
      isEdit,
      patientId,
      showOtherButton
    } = this.$page.data.query;
    this.setData({
      inpatientId,
      isEdit: isEdit || 'NO',
      patientId,
      showOtherButton
    }, () => {
      // 如果是编辑状态 - 获取住院人详情
      if (this.data.isEdit === 'YES') {
        // 获取住院人详情信息
        this.getHospitalInfoDetail();
      } else {
        this.$page.$confirm.showPopover({
          title: '本次是谁住院？',
          popupPosition: 'bottom',
          onButtonClose: () => this.popOverClose(),
          // 弹出框关闭
          onChoosePatient: item => this.choosePatientRelation(item) // 选择就诊人与本人关系

        });
        this.resetForm();
      }
    });
  },

  methods: {
    // 获取住院人详情信息
    async getHospitalInfoDetail() {
      const result = await getHospitalizationInfo({
        inpatientId: this.data.inpatientId
      }); // name 字段名称不同

      result.name = result.inpatientName;
      this.setData({
        form: result
      });
      this.onDisableButton(this.data.form);
    },

    // 编辑信息
    async editInfo(value) {
      const phoneNumber = await getEncryptStr(value);
      const result = await editAdmissionRegistration({
        patientId: this.data.patientId,
        phoneNumber
      });
      const {
        isSuccess
      } = result || {}; // 如果编辑失败，toast提示

      if (!isSuccess) {
        my.showToast({
          content: '编辑失败'
        });
        return;
      } // 如果编辑成功，toast提示


      if (isSuccess) {
        my.showToast({
          content: '编辑成功',
          duration: 2000,
          success: () => {
            // 返回上一页
            my.navigateBack();
          }
        });
      }
    },

    // 新增
    async saveInfo(_form) {
      const params = { ..._form,
        idCardNo: await getEncryptStr(_form.idCardNo),
        phoneNumber: await getEncryptStr(_form.phoneNumber)
      };
      const result = await saveAdmissionRegistration(params);
      const {
        inpatientId
      } = result; // 如果保存失败，toast提示

      if (!inpatientId) {
        my.showToast({
          content: '保存失败！'
        });
        return;
      } // 如果成功保存，跳转至‘登记结果’页


      if (inpatientId) {
        my.showToast({
          content: '添加成功',
          duration: 1000,
          success: () => {
            history.replace({
              query: {
                inpatientId,
                showOtherButton: this.data.showOtherButton
              },
              title: '登记结果',
              pageType: 'registration-result'
            });
          }
        });
      }
    },

    // 提交信息，保存/编辑
    onSubmit() {
      // 获取表单信息
      // const {
      //   detail: {
      //     value,
      //   },
      // } = e;
      const {
        idCardNo,
        phoneNumber,
        inpatientNo
      } = this.data.form;

      if (!checkIdCard(idCardNo)) {
        my.showToast({
          content: '身份证格式不正确！'
        });
        return;
      }

      if (!checkPhone(phoneNumber) || phoneNumber.indexOf('*') > -1) {
        my.showToast({
          content: '手机号格式不正确！'
        });
        return;
      }

      if (/.*[\u4e00-\u9fa5]+.*$/.test(inpatientNo)) {
        my.showToast({
          content: '住院号不能有汉字'
        });
        return;
      }

      const {
        isEdit
      } = this.data; // isEdit - 'YES'编辑，'NO'新增

      if (isEdit === 'YES') {
        this.editInfo(phoneNumber);
      } else {
        this.saveInfo(this.data.form);
      }
    },

    // 选择就诊人与本人关系
    async choosePatientRelation(item) {
      const {
        name
      } = item;
      const {
        form
      } = this.data;
      let isAuthSuccess = false;
      form.relationShip = name;
      /* 如果为本人，唤起授权 */

      if (name === '本人') {
        const {
          userInfo
        } = this.data; // 判断用户是否已经登陆

        if (userInfo.isLogin) {
          isAuthSuccess = true;
        } else {
          isAuthSuccess = await doLogin.call(this, {
            scopes: 'auth_user'
          });
        }

        if (isAuthSuccess) {
          const {
            phone,
            gender = 'm',
            idCardNo,
            fullName
          } = this.data.userInfo;
          form.name = fullName;
          form.idCardNo = idCardNo;
          form.phoneNumber = phone;

          if (gender) {
            form.sex = gender === 'm' ? '男' : '女';
          }
        }
      }

      this.setData({
        form,
        isAuthSuccess
      }); // 关闭弹窗

      this.popOverClose();
    },

    // 关闭弹窗
    popOverClose() {
      this.$page.$confirm.hidePopover();
    },

    // 选择就诊人与本人关系
    onChoosePatientRelation() {
      this.$page.$confirm.showPopover({
        title: '本次是谁住院？',
        popupPosition: 'bottom',
        onButtonClose: () => this.popOverClose(),
        // 弹出框关闭
        onChoosePatient: item => this.choosePatientRelation(item) // 选择就诊人与本人关系

      });
    },

    // 唤起手机通讯录
    onChooseType() {
      my.choosePhoneContact({
        success: res => {
          const {
            form
          } = this.data;
          form.phoneNumber = res.mobile;
          this.setData({
            form
          });
        }
      });
    },

    // 清空表单
    resetForm() {
      this.setData({
        form: {
          relationShip: '本人',
          // 就诊人与本人关系名称
          name: '',
          // 就诊人姓名
          sex: '',
          // 就诊人性别
          idCardType: '身份证',
          // 证件类型， 默认是身份证号 - 身份证
          idCardNo: '',
          // 证件号码
          phoneNumber: '',
          // 手机号
          inpatientNo: '' // 住院号

        }
      });
    },

    // 输入
    onInputAll(e) {
      this.data.form[e.target.dataset.name] = e.detail.value;
      this.setData({
        form: this.data.form
      });
      this.onDisableButton(this.data.form);
    },

    //  是否禁用按钮
    onDisableButton(form) {
      const {
        sex,
        name,
        idCardNo,
        phoneNumber,
        inpatientNo
      } = form;
      const rest = {
        sex,
        name,
        idCardNo,
        phoneNumber,
        inpatientNo
      };
      const disableButton = Object.values(rest).some(v => !v || v === '');
      this.setData({
        disableButton
      });
    },

    async onLaunchOcr() {
      const {
        readIDCard,
        IDCardTypes
      } = await loadOcr();
      readIDCard({
        bizId: 'ocr_01',
        type: IDCardTypes.FRONT
      }).then(res => {
        if (res.error) {
          return Promise.reject(res.error);
        }

        const {
          num: {
            data: idCardNo
          },
          name: {
            data: realName
          },
          sex: {
            data: userSex
          }
        } = res.data;
        this.setData({
          'form.sex': userSex,
          'form.name': realName,
          'form.idCardNo': idCardNo
        });
      }).catch(e => {
        this.showTip(e.message || '识别身份证失败');
      });
    }

  }
}));