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

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

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

class Ips extends React.Component{

	constructor(props){
		super(props);
		this.range = [moment().subtract(6,'days').format('YYYYMMDD'), moment().format('YYYYMMDD')];
		this.state= { currentDate:null,qds:[],ips :[],status:'pending',pagination:{current:1,pageSize:100,total:1},sort:'updatedAt',currentQd:'all' };
	}
	componentDidMount(){
		if(document.cookie.match('username=[a-zA-Z0-9]+')[0] && document.cookie.match('username=[a-zA-Z0-9]+')[0].split('=')[1]){
			this.setState({username:document.cookie.match('username=[a-zA-Z0-9]+')[0].split('=')[1]});
		}
		let pagination = this.state.pagination;
		api('GET', 'qds?skip=0&limit=1000').then((res) => {
			this.setState({qds:res.result});
        });
		//let data = { start:moment().add(-6,'days').format('YYYYMMDD'),end:moment().format('YYYYMMDD')};
		api('GET', 'ips?'+'skip=0&limit=' + pagination.pageSize+'&qd=all').then((res) => {
			this.setState({ips:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total}})
        });
	}

	getips(pagination,value,date){
		api('GET', 'qds?skip=0&limit=1000').then((res) => {
			this.setState({qds:res.result});
        });
		this.setState({status:'pending'});
		var url = 'ips?'+'skip='+ (pagination.current-1) + '&limit=' + pagination.pageSize;
		if(value)
			url += ('&qd='+ value);
		if(date)
			url += ('&date='+ date);
		api('GET', url).then((res) => {
			this.setState({ips:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total}})
        });
	}

	onChange(pagination) {
  		//let data = { start:dateString[0],end:dateString[1]};
  		this.getips(pagination,this.state.currentQd,this.state.currentDate);
  		//this.props.dispatch(actions.getMainData(data));
	}
	onChangeDate(date, dateString){
		this.setState({currentDate:dateString});
		this.getips({current:1,pageSize:this.state.pagination.pageSize},this.state.currentQd,dateString);
	}

	exportData(){

		//json2xlsx(data,{sheetName:"基础数据", filename : '基础数据'+moment().format('YYYYMMDD')+'.xlsx'});
	}
	handleSort(e){
		this.setState({sort:e.target.value});
		this.getips({current:1,pageSize:this.state.pagination.pageSize},e.target.value);

	}
	handleChange(value) {
		this.setState({currentQd:value});
		this.getips({pageSize:this.state.pagination.pageSize,current:1},value,this.state.currentDate)
	  //console.log(`selected ${value}`);
	}


	render(){
		console.dir(this.state.pagination);
		let children = [<Option key='all'>全部</Option>];
			for (var  i = 0; i < this.state.qds.length; i++) {
				let item = this.state.qds[i];
			  children.push(<Option key={item._id}>{ item.user }</Option>);
		}
		const columns = [
			{
			  title: '日期',
			  dataIndex: 'date',
			  key: 'date',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: 'ip',
			  dataIndex: 'ip',
			  key: 'ip',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},{
			  title: '次数',
			  dataIndex: 'times',
			  key: 'times',
			  width: 100,
			   render: text => <span href="#">{text}</span>,
			},
			{
			  title: '渠道',
			  dataIndex: 'qd',
			  key: 'qd',
			  width: 100,
			  // sorter: (a, b) => { a.qd - b.qd},
			  render: text => <span href="#">{text}</span>,
			}
			];
			let data = [];
			let count = 0;
			let ips = this.state.ips;
			for(let i = 0;i<ips.length;i++){
				data.push({
					key:i,
					ip:ips[i].ip,
					date:ips[i].date,
					times:ips[i].times,
					qd:(ips[i]['qd'] && ips[i]['qd']['user']) || '--'
				});
			}
		
		return (
			this.state.username == 'admin' ? <div>
			    <DatePicker onChange={ this.onChangeDate.bind(this) }  format={'YYYYMMDD'}  style={{ width:200,margin:'10px'}}/>
		       	<Select
				    style={{ width:200,margin:'10px 0px'}}
				    placeholder="输入渠道名称"
				    defaultValue="all"
				    onChange={this.handleChange.bind(this)}
				  >
				    {children}
				  </Select>
			    <Spin spinning= { this.state.status == 'pending' }>
			    	<Table columns={columns} dataSource = { data }  size="middle" pagination={ this.state.pagination } onChange = { this.onChange.bind(this)} bordered/>
			    </Spin>
			</div>: <Alert
			      message="抱歉"
			      description="您没有权限"
			      type="warning"
			    />
			)
	}
}

/*
function mapStateToProps (state) {
	return state;
}

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

module.exports = Ips;



