// pages/customermanage/addcustomer.js
const app = getApp();
const phoneRegExp = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|147)\d{8}$/,
  customerCodeRegExp = /^\d{1,10}$/;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    error: '',
    formData: {
      customerId: app.$util.customerId,
      customerCode: '',
      mobile: '',
    }
  },
  formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },
  submit() {
    const {
      customerCode,
      mobile
    } = this.data.formData;
    let error = '';
    if (!phoneRegExp.test(mobile)) {
      error = '您输入的手机号有误，请重新输入';
    }
    if (!mobile) {
      error = '请输入手机号';
    }
    if (!customerCodeRegExp.test(customerCode)) {
      error = '您输入的户号有误，请重新输入';
    }
    if (!customerCode) {
      error = '请输入户号';
    }
    if (error) {
      this.setData({
        error
      })
      return;
    }
    app.$http.get('/user/codeAndPhoneQuery', this.data.formData).then(({ status, data = {}, msg }) => {
      if (status === 0) {
        const {userNumber, username, address} = data;
        if (userNumber) {
          this.popup.setData({
            extClass: 'customer-popup',
            type: 'success',
            title: '您确认绑定当前户名？',
            content: `户名：${username || '-'}`,
            content1: `地址：${address || '-'}`,
            params: data
          });
          this.popup.show();
        }
      } else {
        this.popup.setData({
          type: 'error',
          title: '',
          content: msg || `您输入的户号与手机号不匹配，请重新输入`,
          content1: ''
        });
        this.popup.show();
      }
    })
  },
  cancelEvent: function () {
    this.popup.close();
  },
  confirmEvent: function () {
    if (this.popup.data.type == 'success' && this.popup.data.params) {
      const { customerId, userNumber } = this.popup.data.params;
      app.$http.postForm('/user/bindingAccount', {
        customerId,
        userNumber
      }).then(({ status, msg, data }) => {
        if (status === 0) {
          app.globalData = {};
          app.getUserInfo(app.token);
          this.popup.close();
          wx.navigateBack({
            delta: 1
          })
        } else {
          this.popup.setData({
            type: 'error',
            content: msg,
          });
        }
      })
      return;
    }
    this.popup.close();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //获得popup组件
    this.popup = this.selectComponent("#popup");
  }
})