import { connect } from 'herculex';
import { CREATE_CARD_TYPE } from '../../utils/common';
import { basicPageInfo, createOrBind, editCard, sendPhoneOauth } from '../../utils/service';
import { history, promisify } from '../../utils';
import { initValidator } from '../../utils/validator/card';

const MobileRegExp = require('we-validator').RULES.mobile;

const rsa = promisify(my.rsa);

const getEncryptStr = async (content, key) => {
  if (!key) {
    return content;
  }

  const [, res] = await rsa({
    action: 'encrypt',
    text: content,
    key
  });

  if (res) {
    return res.text;
  }

  return null;
};

Component(connect({
  mapStateToProps: {}
})({
  props: {
    data: {
      type: undefined,
      btnText: undefined,
      cardDetail: undefined,
      back: undefined,
      pageUuid: undefined
    }
  },
  data: {
    componentData: {},
    type: undefined,
    btnText: undefined,
    submitBtnDisabled: false,
    // 字段
    name: '',
    idCardNo: '',
    viewIdCardNo: '',
    relationShip: '',
    defaultCard: '',
    cardNum: '',
    viewCardNum: '',
    phoneNumber: '',
    idcardNoRsa: '',
    fullNameRsa: '',
    phoneRsa: ''
  },

  async didMount() {
    my.setNavigationBar({
      title: '就诊卡管理'
    });
    const {
      type,
      btnText,
      cardDetail
    } = this.props.data;
    await this.fetchComponentData();
    this.setData({
      type,
      btnText,
      validatorInstance: this.initValidator(type)
    });
    cardDetail && this.setEditField(cardDetail);
  },

  methods: {
    // 获取组件数据
    async fetchComponentData() {
      const {
        cardFormComponentData
      } = getApp().globalData;

      if (cardFormComponentData) {
        this.setData({
          componentData: cardFormComponentData
        });
      } else {
        const {
          pageUuid
        } = this.props.data;
        const [err, result] = await basicPageInfo({
          pageUuid
        });

        if (err) {
          return;
        }

        const componentType = 'hospitalCardManageComponent';
        const {
          componentData
        } = result.pages[0].components.find(item => item.componentType === componentType);
        getApp().globalData.cardFormComponentData = componentData;
        this.setData({
          componentData
        });
      }
    },

    // 鉴权设置默认值
    setDefaultValue(result) {
      const {
        userInfo
      } = getApp().globalData;
      this.setData(result ? {
        name: userInfo.fullName,
        idCardNo: userInfo.idCardNo,
        phoneNumber: userInfo.phone,
        idcardNoRsa: userInfo.idcardNoRsa,
        fullNameRsa: userInfo.fullNameRsa,
        phoneRsa: userInfo.phoneRsa
      } : {
        name: '',
        idCardNo: '',
        phoneNumber: '',
        idcardNoRsa: '',
        fullNameRsa: '',
        phoneRsa: ''
      });
    },

    // 选择关系
    onChangeRelationShip() {
      const items = ['本人', '父母', '子女', '其他'];
      my.showActionSheet({
        title: '选择关系',
        items,
        success: async res => {
          this.setData({
            relationShip: items[res.index]
          });

          if (items[res.index] === '本人') {
            const isLoginSuccess = await this.dispatchGlobal('doLogin');

            if (!isLoginSuccess) {
              return;
            }
          }

          items[res.index] && this.setDefaultValue(items[res.index] === '本人');
        }
      });
    },

    onChangeDefaultCard() {
      const items = ['是', '否'];
      my.showActionSheet({
        title: '是否默认',
        items,
        success: res => {
          this.setData({
            defaultCard: items[res.index]
          });
        }
      });
    },

    onItemInput(e) {
      this.setData({
        [e.target.dataset.field]: e.detail.value
      });
    },

    onClear(e) {
      this.setData({
        [e.target.dataset.field]: ''
      });
    },

    async onSend() {
      let msg = null;

      if (!this.data.phoneNumber) {
        msg = '请输入手机号';
        my.showToast({
          content: msg
        });
        return false;
      }

      if (!MobileRegExp.rule.test(this.data.phoneNumber)) {
        msg = '手机号格式错误';
        my.showToast({
          content: msg
        });
        return false;
      }

      const [, res] = await sendPhoneOauth({
        phoneNumber: this.data.phoneNumber
      });
      return res;
    },

    initValidator(type) {
      const {
        needPhoneOauth
      } = this.data.componentData.componentExtInfo || {};
      return initValidator(type, rules => {
        return needPhoneOauth === 'true' ? rules : rules.filter(item => item !== 'verifyCode');
      });
    },

    // 判断是否携带就诊人信息
    navigateToSuccess(res) {
      if (this.data.type === CREATE_CARD_TYPE.CREATE) {
        history.replacePage({
          pageType: 'card-created-result',
          data: {
            success: true,
            cardInfo: res
          }
        });
      } else {
        history.replacePage({
          pageType: 'card-bind-result',
          data: {
            success: true
          }
        });
      }
    },

    navigateToFail(msg) {
      if (this.data.type === CREATE_CARD_TYPE.CREATE) {
        history.replacePage({
          pageType: 'card-created-result',
          data: {
            success: false,
            msg
          }
        });
      } else {
        history.replacePage({
          pageType: 'card-bind-result',
          data: {
            success: false
          }
        });
      }
    },

    setEditField(cardDetail) {
      this.setData({
        name: cardDetail.name,
        idCardNo: cardDetail.idCardNo,
        viewIdCardNo: cardDetail.viewIdCardNo,
        relationShip: cardDetail.relationShip,
        defaultCard: cardDetail.defaultCard,
        cardNum: cardDetail.cardNum,
        viewCardNum: cardDetail.viewCardNum,
        phoneNumber: cardDetail.phoneNumber
      });
    },

    // 创建/绑定/修改 就诊卡接口
    async createCardApi() {
      const datas = {
        name: this.data.name,
        idCardNo: this.data.idCardNo,
        phoneNumber: this.data.phoneNumber,
        verifyCode: this.data.verifyCode,
        relationShip: this.data.relationShip,
        defaultCard: this.data.defaultCard
      };

      if (this.data.type !== CREATE_CARD_TYPE.CREATE) {
        datas.cardNum = this.data.cardNum;
      }

      const isValid = this.data.validatorInstance.checkData(datas);

      if (!isValid) {
        return;
      }

      const {
        type,
        cardNum,
        name,
        idCardNo,
        phoneNumber,
        verifyCode,
        relationShip,
        defaultCard,
        idcardNoRsa,
        fullNameRsa,
        phoneRsa
      } = this.data;
      this.setData({
        submitBtnDisabled: true
      });
      const app = getApp();
      const {
        appPublicKey
      } = app.globalData;
      let nameEncrypt;
      let idCardNoEncrypt;
      let phoneNumberEncrypt;

      if (relationShip === '本人') {
        if (this.data.type !== CREATE_CARD_TYPE.EDIT) {
          nameEncrypt = fullNameRsa;
          idCardNoEncrypt = idcardNoRsa;
          phoneNumberEncrypt = phoneRsa;
        } else {
          phoneNumberEncrypt = await getEncryptStr(phoneNumber, appPublicKey);
        }
      } else {
        nameEncrypt = await getEncryptStr(name, appPublicKey);
        idCardNoEncrypt = await getEncryptStr(idCardNo, appPublicKey);
        phoneNumberEncrypt = await getEncryptStr(phoneNumber, appPublicKey);
      }

      const param = {
        type,
        name: nameEncrypt,
        idCardNo: idCardNoEncrypt,
        phoneNumber: phoneNumberEncrypt,
        relationShip,
        defaultCard,
        authCode: verifyCode
      };

      if (this.data.type !== CREATE_CARD_TYPE.CREATE) {
        param.cardNum = cardNum;
      }

      if (this.data.type !== CREATE_CARD_TYPE.EDIT) {
        const [err, res] = await createOrBind(param); // 绑定与创建

        this.setData({
          submitBtnDisabled: false
        });

        if (res) {
          if (this.props.data.back) {
            getApp().globalData.refreshPage = true;
            my.navigateBack();
            return;
          }

          if (this.data.type !== CREATE_CARD_TYPE.EDIT) {
            this.navigateToSuccess(res);
          }
        } else {
          this.navigateToFail(err.msg);
        }
      } else {
        const [, res] = await editCard(param); // 编辑

        this.setData({
          submitBtnDisabled: false
        });

        if (res) {
          my.showToast({
            type: 'success',
            content: '修改就诊卡成功'
          });
          getApp().globalData.cardDetail = true;
          my.navigateBack();
        } else {
          my.showToast({
            type: 'fail',
            content: '修改就诊卡失败'
          });
        }
      }
    }

  }
}));