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

import {set} from '../../actions/counter'
import { login,getUserOrderList } from '../../utils/servers/servers'
import ListBottomStart from "../../components/common/listBottomStart";

import './index.less'

import background from "../../assets/images/background.png";
import NavBar from "../../components/NavBar";

import userIcon from '../../custom-tab-bar/image/user.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') || ''
    }
  }

  async componentDidShow() {
    this.props.set(1);
    if(!Taro.getStorageSync('token')){
      this.setState({
        list: []
      })
    }
  }

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

  onPullDownRefresh(){
    this.getUserOrderList();
  }

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

  async login(nickname){
    let token = Taro.getStorageSync('token');
    if(!token){
      let loginMsg = await Taro.login();
      if (loginMsg.code) {
        try{
          let msg = await login({
            code:loginMsg.code,
            nickname
          });
          if(msg.error.length === 0){
            Taro.setStorageSync('token', msg.token);
            this.getUserOrderList();
          }else{
            Taro.showToast({title:msg.error[0].message,icon:'none'})
          }
        }catch (err) {
          Taro.showToast({title:'系统错误,请稍后重试',icon:'none'});
          console.log(err)
        }
      } else {
        Taro.showToast({title:loginMsg.errMsg,icon:'none'})
        console.log('登录失败！' + loginMsg.errMsg)
      }
    }
  }

  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'});
      this.setState({
        listState: msg.error[0].field === '403' ? 'NO_DATA' : 'RELOAD'
      })
    }
    Taro.stopPullDownRefresh();
  }


  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;
          }
          Taro.getUserProfile({
            desc: '用于用户登录',
            success: async (res)=> {
              let userInfo = res.userInfo
              let nickName = userInfo.nickName
              Taro.setStorageSync('userInfor', userInfo);
              await this.login(nickName);
              await this.getUserOrderList();
              getCurrentPages()[getCurrentPages().length - 1].onLoad()
            },
            fail: ()=>{
              Taro.showToast({title:'请同意授权获取用户信息',icon:'none'});
            }
          })
        }}>
          <View className='avatar'>
            {
              Taro.getStorageSync('token') ?
                <Image src={this.state.userInfor.avatarUrl} className='login'/> :
                <Image className='noLogin' src={userIcon}/>
            }

          </View>
          <View className='nickName'>
            {
              Taro.getStorageSync('token') ?
                this.state.userInfor.nickName :
                '点击登录'
            }
          </View>
        </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>
      </View>
    )
  }
}

export default Index

