<template>
<view id="bindingphone">
    <view class="tips" :hidden="!message">{{message}}</view>
    <view class="phone__warning">
        <view class="phone__num">
            <input type="text" placeholder="手机号码" @input="changeCode"></input>
        </view>
        <view class="phone__code">
            <view class="input">
                <input type="text" placeholder="验证码" @input="changeIdentifyCode"></input>
            </view>
            <view class="code__get code-send" :style="'background: ' + config.mainColor" @tap="getCode">
                {{code.codeText}}
            </view>
        </view>
    </view>

    <view class="phone__box">
        <view class="phone__btn phone-confirm phone-binding" :style="'background: ' + config.mainColor" @tap="submit">
            确定绑定
        </view>
        <view class="phone__btn phone-cancel" @tap="back">
            取消
        </view>
    </view>

</view>
</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

export default {
  data() {
    return {
      code: {
        total: 60,
        access_token: null,
        codeText: "获取验证码"
      },
      sending: false,
      tellphone: '',
      identifyingcode: '',
      url: '',
      config: '',
	  message:''
    };
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var bgConfig = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: bgConfig
    });

    if (e.url) {
      this.setData({
        url: e.url
      });
    }
  },
  methods: {
    getCode() {
      if (this.sending) return;
      var randoms = this.random();
      this.setData({
        sending: true,
        'code.codeText': "短信发送中",
        'code.access_token': randoms
      });
      var fn;
      fn = this.getLoginCode;
      fn(() => {
        var total = this.code.total;
        this.setData({
          'code.codeText': total + "秒后再发送"
        });
        var timer = setInterval(() => {
          total--;
          this.setData({
            'code.codeText': total + "秒后再发送"
          });

          if (total < 1) {
            this.setData({
              sending: false,
              'code.codeText': "获取验证码"
            });
            clearInterval(timer);
          }
        }, 1000);
      }, () => {
        // this.setData({
        //   sending: false,
        //   'code.codeText': "获取验证码"
        // });
		this.sending=false;
		this.code.codeText="获取验证码";
      });
    },

    changeCode(e) {
      this.setData({
        tellphone: e.detail.value
      });
    },

    changeIdentifyCode(e) {
      this.setData({
        identifyingcode: e.detail.value
      });
    },

    random() {
      return Math.random().toString(36).substr(2, 24);
    },

    getLoginCode(resolve, reject) {
      var message = null;

      if (!is.has(this.tellphone)) {
        message = "请输入您的手机号";
      } else if (!is.mobile(this.tellphone)) {
        message = '手机号格式不正确，请重新输入';
      }

      if (message) {
        this.message=message;
        reject();
        setTimeout(() => {
          this.message='';
        }, 3000);
        return;
      }

      this.$http.post({
        api: "api/sms/verify-code",
        data: {
          mobile: this.tellphone,
          access_token: this.code.access_token
        }
      }).then(res => {
        if (res.data.success) {
          resolve();
        } else {
          reject();
        }
      }); // resolve();
    },


    submit() {
      var message = null;

      if (!is.has(this.tellphone)) {
        message = "请输入您的手机号";
      } else if (!is.mobile(this.tellphone)) {
        message = '手机号格式不正确，请重新输入';
      } else if (!is.has(this.identifyingcode)) {
        message = "请填写验证码";
      }

      if (message) {
      
		this.message=message;
		
        setTimeout(() => {
			
         this.message='';
		 
        }, 3000);
        return;
      }

	  this.showLoading=true;
	  
      this.bindUserMobile();
    },

    bindUserMobile() {
      this.$http.post({
        api: 'api/users/update/mobile',
        data: {
          mobile: this.tellphone,
          code: this.identifyingcode,
          access_token: this.code.access_token
        },
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        wx.hideLoading();

        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            wx.showModal({
              content: '绑定成功',
              showCancel: false,
              success: res => {
                if (res.confirm || !res.cancel && !res.confirm) {
                  if (this.url) {
                    wx.redirectTo({
                      url: '/' + decodeURIComponent(this.url)
                    });
                  } else {
                    wx.switchTab({
                      url: '/pages/user/personal/personal'
                    });
                  }
                }
              }
            });
          } else {
            wx.showModal({
              content: res.message || '绑定失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败，请重试',
            showCancel: false
          });
        }
      }).catch(rej => {
        res = res.data;
        wx.showModal({
          content: '请求失败，请重试',
          showCancel: false
        });
      });
    },

    back() {
      if (this.url) {
        wx.redirectTo({
          url: '/' + decodeURIComponent(this.url)
        });
      } else {
        wx.navigateBack();
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "bindingphone";
</style>
