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

import json2xlsx from '../../js/json2xlsx';

import { Table, Icon, DatePicker, Alert, Row, Col, Spin, Button} from 'antd';
const { RangePicker } = DatePicker;

class DashBoard extends React.Component{

	constructor(props){
		super(props);
		//this.state= { main :"hello" };
	}
	componentDidMount(){
		let data = { start:moment().add(-6,'days').format('YYYYMMDD'),end:moment().format('YYYYMMDD')};
		this.props.dispatch(actions.getMainData(data));
		this.props.dispatch(actions.getCountData());
	}

	onChange(date, dateString) {
  		let data = { start:dateString[0],end:dateString[1]};
  		this.props.dispatch(actions.getMainData(data));
	}

	exportData(){
		let data = [];
		let userResult = this.props.data.users;
		let upstreamResult = this.props.data.upstreams;
		let userCount = this.props.data.userCount;
		let upCount = this.props.data.upCount;
		let map = {};

		for(let i = 0; i < userResult.length; i++){
			let item = userResult[i]['_id'];
			let _id = item ? item['year'] + (item['month'] <= 9 ? '0'+item['month'] : item['month']) + (item['day'] <= 9 ? '0'+item['day'] : item['day']) : 'unkown';
			map[_id] = map[_id] || {};
			map[_id]['user'] = userResult[i]['count']
		}
		for(let i = 0; i < upstreamResult.length; i++){
			let item = upstreamResult[i]['_id'];
			let _id = item ? item['year'] + (item['month'] <= 9 ? '0'+item['month'] : item['month']) + (item['day'] <= 9 ? '0'+item['day'] : item['day']) : 'unkown';
			map[_id] = map[_id] || {};
			map[_id]['upstream'] = upstreamResult[i]['count']
		}

		let range = this.props.data.range;
		var start = range[0];
		var end = range[1];
		let ranges = [];
		ranges.push(moment(start,'YYYYMMDD'));
		ranges.push(moment(end,'YYYYMMDD'));

		data = [];
        let leng = Math.ceil( (moment(end).endOf('day').format('x') -  moment(start).startOf('day').format('x')) / 86400000 );
        let uptonowUser = userCount;
        let uptonowUp = upCount;
		for(let i = 0;i<leng;i++){
			var temp = moment(start).add(i, 'day').startOf('day').format('YYYYMMDD');
			let useradd = (map[temp] ? map[temp]['user']||0 : 0 );
			uptonowUser += useradd;
			let upstreamadd = (map[temp] ? map[temp]['upstream']||0 : 0 );
			uptonowUp += upstreamadd;

			data.push({
				'日期':temp,
				'用户新增':useradd,
				'用户合计':uptonowUser,
				'账号新增':upstreamadd,
				'账号合计':uptonowUp
			});
		}

			json2xlsx(data,{sheetName:"基础数据", filename : '基础数据'+moment().format('YYYYMMDD')+'.xlsx'});
	}

	render(){
		const columns = [
			{
			  title: '日期',
			  dataIndex: 'date',
			  key: 'date',
			  width: 100,
			  render: text => <a href="#">{text}</a>,
			},
			{
			  title: '用户统计',
			  children:[
			  	  {
				  	title: '新增',
				  	dataIndex: 'useradd',
				  	key: 'useradd',
				  	width: 100,
				  	render: text => <a href="#">{text}</a>,
				  },
				  {
				  	title: '合计',
				  	dataIndex: 'usertotal',
				  	key: 'usertotal',
				  	width: 100,
				  	render: text => <a href="#">{text}</a>,
				  }
			  ]
			},
			{
			  title: '平台账号',
			  children:[
				  {
				  	title: '新增',
				  	dataIndex: 'upstreamadd',
				  	key: 'upstreamadd',
				  	width: 100,
				  	render: text => <a href="#">{text}</a>,
				  },
				  {
				  	title: '合计',
				  	dataIndex: 'upstreamtotal',
				  	key: 'upstreamtotal',
				  	width: 100,
				  	render: text => <a href="#">{text}</a>,
				  }]
			},{
			  title: '操作',
			  dataIndex: 'operation',
			  key: 'operation',
			  width: 100,
			  render: text => <a href="/manage/" >{ '详细' }</a>,
			}
			]
		let data = [];
		let count = 0;
		let userResult = this.props.data.users;
		let upstreamResult = this.props.data.upstreams;
		let userCount = this.props.data.userCount;
		let upCount = this.props.data.upCount;
		let map = {};

		for(let i = 0; i < userResult.length; i++){
			let item = userResult[i]['_id'];
			let _id = item ? item['year'] + (item['month'] <= 9 ? '0'+item['month'] : item['month']) + (item['day'] <= 9 ? '0'+item['day'] : item['day']) : 'unkown';
			map[_id] = map[_id] || {};
			map[_id]['user'] = userResult[i]['count']
		}
		for(let i = 0; i < upstreamResult.length; i++){
			let item = upstreamResult[i]['_id'];
			let _id = item ? item['year'] + (item['month'] <= 9 ? '0'+item['month'] : item['month']) + (item['day'] <= 9 ? '0'+item['day'] : item['day']) : 'unkown';
			map[_id] = map[_id] || {};
			map[_id]['upstream'] = upstreamResult[i]['count']
		}

		let range = this.props.data.range;
		var start = range[0];
		var end = range[1];
		let ranges = [];
		ranges.push(moment(start,'YYYYMMDD'));
		ranges.push(moment(end,'YYYYMMDD'));

		data = [];
        let leng = Math.ceil( (moment(end).endOf('day').format('x') -  moment(start).startOf('day').format('x')) / 86400000 );
        let uptonowUser = userCount;
        let uptonowUp = upCount;
		for(let i = 0;i<leng;i++){
			var temp = moment(start).add(i, 'day').startOf('day').format('YYYYMMDD');
			let useradd = (map[temp] ? map[temp]['user']||0 : 0 );
			uptonowUser += useradd;
			let upstreamadd = (map[temp] ? map[temp]['upstream']||0 : 0 );
			uptonowUp += upstreamadd;

			data.push({
				key:i,
				date:temp,
				useradd:useradd,
				usertotal:uptonowUser,
				upstreamadd:upstreamadd,
				upstreamtotal:uptonowUp
			});
		}
		data.sort(function(a,b){
			return b['key'] - a['key'];
		});
		
		return (
			<div>
			    <Row>
			      <Col span="6">
			      	<div className = "box" style={{ marginLeft:'0px'}}>
			      		<h3>用户数</h3>
			      		<span>{ this.props.data.count.user }</span>
			      	</div>
			      </Col>
			      <Col span="6">
			      	<div className = "box">
			      		<h3>账号数</h3>
			      		<span>{ this.props.data.count.upstream }</span>
			      	</div>
			      </Col>
			      <Col span="6">
			      	<div className = "box" style={{ marginRight:'0px'}}>
			      		<h3>内部用户</h3>
			      		<span>{ this.props.data.count.admin }</span>
			      	</div>
			      </Col>
			      <Col span="6">
			      	<div className = "box">
			      		<h3>外部用户</h3>
			      		<span>{ this.props.data.count.upstream - this.props.data.count.admin }</span>
			      	</div>
			      </Col>
			    </Row>
			    <RangePicker onChange={ this.onChange.bind(this) } value={ ranges } format={'YYYYMMDD'} style={{margin:'10px 0px'}}/>
			    <Button type="primary" icon="poweroff"  onClick={ this.exportData.bind(this) } style={{ float:'right',margin:'10px 0px'}}>
          			导出数据
        		</Button>
			    <Spin spinning= { this.props.data.status == 'pending' }>
			    	<Table columns={columns} dataSource = { data }  size="middle" bordered/>
			    </Spin>
			</div>
			)
	}
}


function mapStateToProps (state) {
	return state;
}

module.exports = connect(mapStateToProps)(DashBoard);