const React = require('react');
const connect = require('react-redux').connect;
const actions = require('../../js/actions');
const types = require('../../js/actions/actionTypes');
const moment = require('moment');

import { Table, Spin}  from 'antd';

class Detail extends React.Component{
	constructor(props){
		super(props);
		// this.state= { pagination : { current: 0,total: 0} };
	}

	componentDidMount (){
		let limit = 30;
		let skip = 0;
		// await this.props.dispatch({status:'pending',type:types.DETAILDATA});
		this.props.dispatch(actions.getDetailData({limit,skip}));
	}

	handleTableChange (pagination, filters, sorter) {
	    const pager = this.props.data.detail.pagination;
	    pager.current = pagination.current;
	    // this.props.dispatch({
	    //   pagination: pager,
	    //   type:types.DETAILDATA
	    // })
	    this.props.dispatch(actions.getDetailData({limit: 30,skip: parseInt(pager.current)-1 }));
  	}

	render(){
		let columns = [ 
		 {
		  	title: '用户',
		  	dataIndex: 'name',
		  	key: 'name',
		  	width: 100,
		  	render: text => <a href="#">{text}</a>,
		  },
		  {
		  	title: '电话',
		  	dataIndex: 'phone',
		  	key: 'phone',
		  	width: 100,
		  	render: text => <a href="#">{text}</a>,
		  },
		  {
		  	title: '账户数量',
		  	dataIndex: 'ups',
		  	key: 'ups',
		  	width: 100,
		  	render: text => <a href="#">{text}</a>,
		  },
		  {
		  	title: '注册时间',
		  	dataIndex: 'date',
		  	key: 'date',
		  	width: 100,
		  	render: text => <a href="#">{text}</a>,
		  },
		];
		
		let users = this.props.data.detail ? this.props.data.detail.users : [];
		let upstreams = this.props.data.detail ? this.props.data.detail.upstreams : [];
		let upMap = {};
		let data = [];
		for(let i = 0;i < upstreams.length; i++){
			let id = upstreams[i]['_id']['creater'];
			upMap[id] = upstreams[i]['count'];
		}
		for(let i = 0;i < users.length; i++){
			let item = users[i];
			data.push({
				key : i,
				name : item['username'] || '-',
				phone : item['phone'] || '-',
				ups : upMap[ item['_id'] ] || 0,
				date : moment(item['createdAt']).format('YYYY/MM/DD hh:mm:ss')
			})
		}

		return (
				<Table columns={columns} dataSource = { data }  pagination={ this.props.data.detail.pagination }  size="middle" onChange = { this.handleTableChange.bind(this) }/>
			)
	}
}

function mapStateToProps (state) {
	return state;
}
module.exports = connect(mapStateToProps)(Detail);