import React,{Component} from "react";
import {Button, View} from '@tarojs/components'
import Taro from "@tarojs/taro";
import { AtIcon } from 'taro-ui'

import "taro-ui/dist/style/components/icon.scss";

import { setDecryptData } from '../../../utils/servers/servers';

import './index.less';

class PhoneWarrantMore extends Component{
  constructor(props) {
    super(props);
    this.setDecryptData = this.setDecryptData.bind(this);
  }

  async setDecryptData(data){
    Taro.showLoading({title:'正在努力绑定中...'})
    let msg = await setDecryptData({
      encryptedData : data.encryptedData,
      iv : data.iv
    });
    if(msg.error && msg.error.length !== 0){
      Taro.showToast({title:msg.error[0].message,icon:'none'});
      Taro.hideLoading();
      return;
    }
    if(msg.phoneNumber){
      let userInfor = Taro.getStorageSync('userInfor');
      userInfor.mobile = msg.phoneNumber;
      Taro.setStorageSync('userInfor', userInfor);
      Taro.showToast({
        title:'绑定成功',
        icon:'success'
      });
      this.props.onClose();
    }else{
      Taro.showToast({
        title:'绑定失败',
        icon:'error'
      });
    }
    Taro.hideLoading();
  }

  render() {
    return(
      <>
        {
          this.props.visible ? <View className='phoneWarrantMore' onClick={(e)=>{
            e.stopPropagation();
            this.props.onClose();
          }}>
            <View className='content' onClick={(e)=>{
              e.stopPropagation();
            }}>
              <View className='close' onClick={(e)=>{
                e.stopPropagation();
                this.props.onClose();
              }}>
                <AtIcon value='close' size='20' />
              </View>
              <View className='phone'>
                <AtIcon value='phone' size='40' color='#24f121'/>
              </View>
              <View className='title'>绑定手机号授权</View>
              <View className='introduction'>绑定手机号后,我们能更好的为您服务</View>
              <Button className='phoneButton' type='primary' openType='getPhoneNumber' onGetphonenumber={(v)=>{
                if(v.detail.encryptedData){
                  this.setDecryptData(v.detail)
                }
              }}>
                绑定手机号
              </Button>
            </View>
          </View> : <View/>
        }
      </>
    );
  }
}

export default PhoneWarrantMore;
