import { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux'
import {View, Image} from '@tarojs/components'

import {set} from '../../actions/counter'
import { login,getUserOrderList,setDecryptData } from '../../utils/servers/servers'

import NavBar from "../../components/NavBar";
import ListBottomStart from "../../components/common/listBottomStart";
import PhoneWarrantMore from "../../components/common/phoneWarrantMore";

import './index.less'

import userIcon from '../../custom-tab-bar/image/user.png';
import background from "../../assets/images/background.png";

@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  set (value) {
    dispatch(set(value))
  }
}))
class Index extends Component {

  inst = Taro.getCurrentInstance()

  constructor(props) {
    super(props);
    this.state={
      list: [],
      pageNo: 0,
      listState: 'LOADING',
      userInfor:Taro.getStorageSync('userInfor') || '',
      token: Taro.getStorageSync('token') || '',
      visible: false,
    }
  }

  async componentDidShow() {
    this.props.set(1);
    this.setState({
      userInfor:Taro.getStorageSync('userInfor') || '',
      token: Taro.getStorageSync('token') || '',
    })
  }

  async componentDidMount() {
    await this.getUserOrderList();
  }

  onPullDownRefresh(){
    this.getUserOrderList();
  }

  onReachBottom(){
    this.getUserOrderList(this.state.pageNo+1);
  }

  login(){
    Taro.getUserProfile({
      desc: '用于用户登录',
      success: (userInfor)=> {
        login(userInfor).then((mobile)=>{
          if(!mobile){
            this.setState({
              visible: true
            })
          }
          this.setState({
            userInfor:Taro.getStorageSync('userInfor') || '',
            token: Taro.getStorageSync('token') || '',
          })
          this.getUserOrderList();
        })
      },
      fail: ()=>{
        Taro.showToast({title:'请同意授权获取用户信息',icon:'none'});
      }
    })
  }

  async getUserOrderList (pageNo = 1){
    this.setState({
      listState: 'LOADING'
    })
    let msg = await getUserOrderList({
      pageNo: pageNo,
      pageSize: 5,
      payStatus: 1,
    });
    if(msg.error.length === 0){
      if(msg.data.totalCount === 0){
        this.setState({
          listState: 'NO_DATA'
        })
      }else if(msg.data.totalCount === this.state.list.length && pageNo !== 1){
        Taro.showToast({title:'没有更多数据了',icon:'none'});
        this.setState({
          listState: 'NO_MORE_DATA'
        })
      }else{
        this.setState({
          list:pageNo === 1 ? msg.data.list : this.state.list.concat(msg.data.list),
          pageNo: msg.data.pageNo
        },()=>{
          if(msg.data.totalCount === this.state.list.length){
            this.setState({
              listState: 'NO_MORE_DATA'
            })
          }
        })
      }
    }else{
      Taro.showToast({title:msg.error[0].message,icon:'none'});
      if(msg.error[0].field === '403'){
        this.setState({
          token: ''
        })
      }
      this.setState({
        listState: msg.error[0].field === '403' ? 'NO_DATA' : 'RELOAD'
      })
    }
    Taro.stopPullDownRefresh();
  }

  async setDecryptData(data){
    let msg = await setDecryptData({
      encryptedData : data.encryptedData,
      iv : data.iv
    });
    if(msg.error && msg.error.length !== 0){
      if(msg.error[0].field === '403'){
        this.setState({
          token: ''
        })
      }
      Taro.showToast({title:msg.error[0].message,icon:'none'});
      return;
    }
    if(msg.phoneNumber){
      let userInfor = Taro.getStorageSync('userInfor');
      userInfor.mobile = msg.phoneNumber;
      Taro.setStorageSync('userInfor', userInfor);
      this.setState({
        userInfor: userInfor
      })
      Taro.showToast({
        title:'绑定成功',
        icon:'success'
      });
    }else{
      Taro.showToast({
        title:'绑定失败',
        icon:'error'
      });
    }
  }

  render () {
    return (
      <View className='userPage'>
        <NavBar
          extClass='NavBar'
          title='我的'
          background='#7ac7ff'
          onHome={()=>{}}
        />
        <Image src={background} className='background'/>
        <View className='userInfor' onClick={()=>{
          if(Taro.getStorageSync('token')){
            return;
          }
          this.login()
        }}>
          <View className='avatar'>
            {
              this.state.token ?
                <Image src={this.state.userInfor.avatarUrl} className='login'/> :
                <Image className='noLogin' src={userIcon}/>
            }

          </View>
          <View className='nickName'>
            {
              this.state.token ?
                this.state.userInfor.nickName :
                '点击登录'
            }
          </View>
          {this.state.token && this.state.userInfor && !this.state.userInfor.mobile ? <View className='bindPhone' onClick={(e)=>{
            e.stopPropagation();
            this.setState({
              visible:true
            })
          }}>绑定手机</View> : null}
        </View>
        <View className='list'>
          {this.state.list.map((v,k)=>(
            <View className='item' key={k} onClick={()=>{
              Taro.navigateTo({
                url:'/pages/details/index?id='+v.projectId
              })
            }}>
              <View className='block'>
                <View className='top'/>
                <View className='bottom'>
                  <View className='left'/>
                  <View className='right'/>
                </View>
              </View>
              <View className='infor'>
                <View className='title'>{v.projectName}</View>
                <View className='content'>{v.projectTypeName}</View>
              </View>
              <View className='moneyInfor'>
                <View className='money'>¥{parseFloat(v.projectAmount)}</View>
                <View className='time'>{v.createTimes}</View>
              </View>
            </View>
          ))}
          <ListBottomStart
            state={this.state.listState}
            reload={()=>{
              this.getUserOrderList(this.state.pageNo+1);
            }}/>
        </View>
        <PhoneWarrantMore
          visible={this.state.visible}
          onClose={()=>{
            this.setState({
              userInfor: Taro.getStorageSync('userInfor')
            })
            this.setState({
              visible:false
            })
          }}
        />
      </View>
    )
  }
}

export default Index

