const React = require('react');
const moment = require('moment');
const api = require('../../js/api');

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


import { Table, Icon, DatePicker, Alert, Row, Col, Spin, Button,Modal,Form,Input,Switch,InputNumber,message} from 'antd';
const { RangePicker } = DatePicker;
const FormItem = Form.Item;

class Qd extends React.Component{

	constructor(props){
		super(props);
		console.dir(this.props);
		this.state= { qds :[],status:'pending',pagination:{current:1,pageSize:20,total:100},modalVisible:false,username:'channel'};
	}
	componentDidMount(){
		let pagination = this.state.pagination;
		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]});
		}
		api('GET', 'qds?'+'skip=0&limit=' + pagination.pageSize).then((res) => {
			this.setState({qds:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total},info:{quan:'',good:''}})
            console.dir(res.result);
        });
	}

	getqds(pagination){
		this.setState({status:'pending'})
		api('GET', 'qds?'+'skip='+ (pagination.current-1) + '&limit=' + pagination.pageSize).then((res) => {
			this.setState({qds:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total}})
            console.dir(res.result);
        });
	}

	onChange(pagination) {
		this.getqds(pagination);
	}

	createQd(){
		this.setModalVisible(true);
	}

	handleSubmit(e){
		e.preventDefault();
	    var self = this;
	    this.props.form.validateFields((err, values) => {
	      if (!err) {
	      	console.dir(values);
	        api('POST', 'qd',values).then((res) => {
            	if(res && res.result){
            		self.setModalVisible(false);
            		self.getqds({limit:this.state.pagination.pageSize,skip:0});
            	}
        	});
	      }
	    });
	}


	ipsChange(data,value){
		console.dir(data);
		console.dir(value);
		var key = data['key'];
		var qds = this.state.qds;
		//console.dir(qds.length + '====');
		qds[key]['iplimit'] = value;
		console.dir(qds[key]['iplimit']);
		this.setState({qds:qds});
	}


	putIpData(data){
		console.dir(data);
		api('POST','put_ip',{iplimit:data['ip'],id:data['id']}).then( res => {
		 	message.success('执行成功, 影响'+ (res.result ? res.result.nModified : 0 )+" 条数据");
		});
	}

	setModalVisible(b){
		this.setState({modalVisible:b});
	}

	exportData(){
	
	}

	checkUpdate(qd){
		var qds = this.state.qds;
  		var data = {
  			ipstatus:qd['ipstatus'] && qd['ipstatus'] == 'use' ? 'disable' : 'use',
  			id:qd['id']
  		}
  		var self = this;
  		api('POST', 'qd_update',data).then((res) => {
  			if(res.result &&  res.result.nModified){
  				message.success('执行成功, 影响'+ (res.result ? res.result.nModified : 0 )+" 条数据");
  				qds[qd['key']]['ipstatus'] = (qd['ipstatus'] && qd['ipstatus'] == 'use' ? 'disable' : 'use');
				self.setState({qds:qds});	
  			}
        });
	}

	render(){
		const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
		const columns = [
			{
			  title: '渠道ID(分发ID)',
			  dataIndex: 'id',
			  key: 'id',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '用户名',
			  dataIndex: 'user',
			  key: 'user',
			  width: 40,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '备注信息',
			  dataIndex: 'info',
			  key: 'info',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '可用计划',
			  dataIndex: 'schedule',
			  key: 'schedule',
			  width: 40,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '淘口令数',
			  dataIndex: 'tkl',
			  key: 'tkl',
			  width: 40,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: 'IP控制（状态 ／ 次数）',
			  dataIndex: 'ip',
			  key: 'ip',
			  width: 100,
			  render: (text,data) => <div>
				  						<Switch checked={ data.ipstatus == 'use' ? true : false } onChange={this.checkUpdate.bind(this,data)}  style = {{'marginRight': '10px'}}/>
					  					<InputNumber min={0} max={1000000000000000}  value = { text || 0 } onChange = { this.ipsChange.bind(this,data)}/>
					  					<Button type="primary"  onClick={ this.putIpData.bind(this,data) } style = {{ marginLeft:'10px' }}>
				          					确定
				        				</Button>
			        				</div>
			}
			];
			let data = [];
			let qds = this.state.qds;
			for(let i = 0;i<qds.length;i++){
				data.push({
					key:i,
					ipstatus:(qds[i].ipstatus) || 'disable',
					id:qds[i]._id,
					user:qds[i].user,
					info:qds[i].info || '--',
					schedule:(qds[i].schedule_count) || 0,
					ip:(qds[i].iplimit) || 0,
					tkl:(qds[i].tkl_count) || 0
				});
			}
		return (
			this.state.username == 'admin' ? <div>
				<Button type="primary" icon="plus"  onClick={ this.createQd.bind(this) } style={{ margin:'10px 0px'}}>
          			创建渠道
        		</Button>
				<Spin spinning= { this.state.status == 'pending' }>
			    	<Table columns={columns} dataSource = { data }  size="middle" pagination={ this.state.pagination } onChange = { this.onChange.bind(this)} bordered/>
			    </Spin>
			    			    <Modal
		          title="渠道创建"
		          style={{ top: 30 }}
		          visible={this.state.modalVisible}
		          footer = { null }
		          onCancel = { this.setModalVisible.bind(this,false) }
		        >
			    <Form onSubmit={this.handleSubmit.bind(this)} className="login-form">
			       <FormItem>
			          {getFieldDecorator('user', {
			            rules: [{ required: true, message: '用户名不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>用户名</span>} placeholder="例如：dqd1" />
			          )}
			        </FormItem>
			        <FormItem>
			          {getFieldDecorator('info', {
			            rules: [{ required: true, message: '备注信息不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>备注信息</span>} placeholder="例如：xxx公司" />
			          )}
			        </FormItem>
			        <FormItem>
			          {getFieldDecorator('password', {
			            rules: [{ required: true, message: '密码不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>渠道密码</span>} placeholder="例如：abc123" />
			          )}
			        </FormItem>
			        <FormItem>
			          <Button type="primary" htmlType="submit" className="login-form-button">
			            创建
			          </Button>
			        </FormItem>
			    </Form>
		        </Modal>
			</div>: <Alert
			      message="抱歉"
			      description="您没有权限"
			      type="warning"
			    />
			)
	}
}
Qd = Form.create()(Qd);
module.exports = Qd;



