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

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

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

class Schedule extends React.Component{

	constructor(props){
		super(props);
		this.state= { currentQd:'all',qds:[],schedules :[],status:'pending',pagination:{current:1,pageSize:10,total:1},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=1000').then((res) => {
			this.setState({qds:res.result});
        });
		//let data = { start:moment().add(-6,'days').format('YYYYMMDD'),end:moment().format('YYYYMMDD')};
		api('GET', 'schedules?'+'skip=0&limit=' + pagination.pageSize).then((res) => {
			this.setState({schedules:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total},info:{quan:'',good:''}})
        });
	}

	getschedules(pagination,qd){
		console.dir(pagination);
		this.setState({status:'pending'});
		var url = 'schedules?'+'skip='+ (pagination.current-1) + '&limit=' + pagination.pageSize;
		if(qd && qd !== 'all')
			url += ('&qd='+ qd);
		api('GET', url).then((res) => {
			this.setState({schedules:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total}})
            console.dir(res.result);
        });
	}

	onChange(pagination) {
		this.getschedules(pagination,this.state.currentQd);
	}

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

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

	handleSubmit(e){
	    e.preventDefault();
	    var self = this;
	    this.props.form.validateFields((err, values) => {
	      if (!err) {
	      	if(values['final'])
	      		values['final'] = values.final.valueOf();
	        api('POST', 'schedule',values).then((res) => {
            	if(res && res.result){
            		self.setModalVisible(false);
            		self.getschedules({pageSize:this.state.pagination.pageSize,current:1});
            	}
        	});
	      }
	    });
  	}
  	checkUpdate(schedule){
  		var schedules = this.state.schedules;
  		var data = {
  			status:schedule['status'] && schedule['status']['status'] == 'use' ? 'disable' : 'use',
  			scheduleId:schedule['id']
  		}
  		var self = this;
  		api('POST', 'schedule_update',data).then((res) => {
			if(res && res.schedule){
				if(data.status == 'use')
					message.success('执行成功, 生成'+ (res.new ? res.new.length : 0 )+" 条淘口令");
				else
					message.success('执行成功, 删除'+ (res.remove_result ? res.remove_result.nModified : 0 )+" 条淘口令");
				schedules[schedule['key']]['status'] = (schedule['status'] && schedule['status']['status'] == 'use' ? 'disable' : 'use');
  				self.setState({schedules:schedules});
			}	
				//message.success('执行成功, 生成 '+(res.new ?  res.new.length : 0) +" 条,删除 "+ (res.remove_result ? res.remove_result.nModified : 0 )+" 条");
        });
  		
  	}
  	tklUpdate(schedule){
  		api('POST', 'newtkl',{id:schedule.id}).then((res) => {
			if(res && res.result =='ok')
				message.success('执行成功, 生成 '+(res.new ?  res.new.length : 0) +" 条,删除 "+ (res.remove_result ? res.remove_result.nModified : 0 )+" 条");
        });
  	}

  	autoUpdate(schedule){
  		var schedules = this.state.schedules;
  		var data = {
  			auto:schedule['status'] && schedule['status']['auto'] == 'use' ? 'disable' : 'use',
  			scheduleId:schedule['id']
  		}
  		var self = this;
  		api('POST', 'schedule_auto_update',data).then((res) => {
			if(res && res.schedule){
				schedules[schedule['key']]['auto'] = (schedule['status'] && schedule['status']['auto'] == 'use' ? 'disable' : 'use');
  				self.setState({schedules:schedules});
			}	
				//message.success('执行成功, 生成 '+(res.new ?  res.new.length : 0) +" 条,删除 "+ (res.remove_result ? res.remove_result.nModified : 0 )+" 条");
        });
  	}

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

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

	render(){
		const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
		const columns = [
			{
			  title: '计划ID',
			  dataIndex: 'id',
			  key: 'id',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '分发ID/渠道',
			  dataIndex: 'qd',
			  key: 'qd',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '推广页名称',
			  dataIndex: 'names',
			  key: 'names',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '可用淘口令',
			  dataIndex: 'tkls',
			  key: 'tkls',
			  width: 5,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '创建日期',
			  dataIndex: 'create',
			  key: 'create',
			  width: 75,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '截止日期',
			  dataIndex: 'final',
			  key: 'final',
			  width: 75,
			  render: text => <span href="#">{text}</span>,
			},{
			  title: '投放状态 / 手动替换 ／ 定时更新 ',
			  dataIndex: 'status',
			  key: 'status',
			  width: 130,
			  render: (data,schedule) => <div><Switch checked={ data.status == 'use' ? true : false } onChange={this.checkUpdate.bind(this,schedule)}  style = {{'marginRight': '10px'}}/><Button onClick = {this.tklUpdate.bind(this,schedule)} style = {{'marginRight': '10px'}}>生成淘口令</Button>
			  	<Switch checked={ data.auto  == 'use' ? true : false } onChange={this.autoUpdate.bind(this,schedule)}  style = {{'marginRight': '17px'}}/></div>,
			}
			];
			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>);
			}
			let data = [];
			let schedules = this.state.schedules;
			for(let i = 0;i<schedules.length;i++){
				let links = schedules[i].links;
				var names = "";
				links.forEach(function(link) {
					names += (" " + link['name']);
				});
				data.push({
					key:i,
					id:(schedules[i]._id && schedules[i]._id) || '--',
					final:schedules[i].final || '--',
					names:names || '--',
					status:{ status:schedules[i].status,auto:schedules[i].auto},
					qd:((schedules[i].qd && schedules[i].qd['user']) || '--') + ' /' + ((schedules[i].qd && schedules[i].qd['_id']) || '--'),
					tkls:(schedules[i].count),
					times:schedules[i].times,
					create:schedules[i].createdAt
				});
			}
		return (
			this.state.username == 'admin' ?  <div>
			    <Button type="primary" icon="plus"  onClick={ this.createSchedule.bind(this) } style={{ margin:'10px 0px'}}>
          			创建计划
        		</Button>
        		<Select
				    style={{ float:'right',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>
			    <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('names', {
			            rules: [{ required: true, message: '推广页名称不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>推广名称</span>} placeholder="例如：商品1@商品2@商品3" />
			          )}
			        </FormItem>
			        <FormItem>
			          {getFieldDecorator('user', {
			            rules: [{ required: true, message: '渠道名称不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>渠道名称</span>} placeholder="例如：qd1" />
			          )}
			        </FormItem>
			        <FormItem>
			          {getFieldDecorator('times', {
			            rules: [{ required: true, message: '推广次数不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>推广次数</span>}  placeholder="例如：1000000" />
			          )}
			        </FormItem>
			       <FormItem>
			       	  <span style={{ fontSize: 13,display:"block" }}>截止日期</span>
			          {getFieldDecorator('final',{ type: 'object', required: true, message: 'Please select time!' })(
			            <DatePicker 
			            	showTime
      						format="YYYY-MM-DD HH:mm:ss"
      						placeholder="选择"/>
			          )}
			        </FormItem>
			        <FormItem>
			          <Button type="primary" htmlType="submit" className="login-form-button">
			            一键生成
			          </Button>
			        </FormItem>
			      </Form>
		        </Modal>
			</div>: <Alert
			      message="抱歉"
			      description="您没有权限"
			      type="warning"
			    />
			)
	}
}

Schedule = Form.create()(Schedule);
module.exports = Schedule;



