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,Radio,message} from 'antd';
const RadioGroup = Radio.Group;
const Search = Input.Search;
const { RangePicker } = DatePicker;
const FormItem = Form.Item;

class Agent extends React.Component{

	constructor(props){
		super(props);
		console.dir(this.props);
		this.state= { links :[],status:'pending',pagination:{current:1,pageSize:200,total:0},modalVisible:false,username:'channel',target:'target',keyword:''};
	}
	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]});
		}
		//let data = { start:moment().add(-6,'days').format('YYYYMMDD'),end:moment().format('YYYYMMDD')};
		api('GET', 'links?'+'skip=0&limit=' + pagination.pageSize).then((res) => {
			this.setState({links:res.result,status:'ready',pagination:{current:res.pagination.skip,pageSize:res.pagination.limit,total:res.pagination.total},info:{quan:'',good:''}})
            console.dir(res.result);
        });
	}

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

	onChange(pagination) {
		this.getLinks(pagination,this.state.keyword);
	}

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

	delete(data) {
		api('GET', 'link/del/'+ data.key).then((res) => {
			message.success('删除成功');
        }).catch((data) => {
        	message.error(data.responseText);
        });
	}

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

	search(value) {
		this.setState({ keyword:value });
		this.getLinks({ current:1,pageSize:this.state.pagination.pageSize }, value);
	}

	handleSubmit(e){
	    e.preventDefault();
	    var self = this;
	    this.props.form.validateFields((err, values) => {
	      if (!err) {
	      	for(var k in values){
	      		if(values[k]) values[k] = values[k].trim();
	      	}
	      	values['select'] = this.state.target;
	      	console.dir(values);
	        api('POST', 'link',values).then((res) => {
            	if(res && res.result){
            		self.setModalVisible(false);
            		self.getLinks({limit:this.state.pagination.pageSize,skip:0},this.state.keyword);
            	}
        	});
	      }
	    });
  }
  	handleTargetChange(e){
  		console.dir(e.target.value);
  		this.props.form.resetFields && this.props.form.resetFields();
  		this.setState({target:e.target.value})
  	}

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

	render(){
		const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
		const columns = [
			{
			  title: '推广页名称',
			  dataIndex: 'name',
			  key: 'name',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '推广语',
			  dataIndex: 'slogan',
			  key: 'slogan',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '优惠券链接',
			  dataIndex: 'quan',
			  key: 'quan',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},{
			  title: '商品连接',
			  dataIndex: 'good',
			  key: 'good',
			  width: 100,
			   render: text => <span href="#">{text}</span>,
			},
			{
			  title: 'PID',
			  dataIndex: 'pid',
			  key: 'pid',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '目标链接',
			  dataIndex: 'target',
			  key: 'target',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '推广渠道',
			  dataIndex: 'qd',
			  key: 'qd',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '大图',
			  dataIndex: 'img',
			  key: 'img',
			  width: 100,
			  render: text => <img style= {{height:'70px'}} src = { text }/>,
			},
			{
			  title: '创建日期',
			  dataIndex: 'create',
			  key: 'create',
			  width: 100,
			  render: text => <span href="#">{text}</span>,
			},
			{
			  title: '操作',
			  dataIndex: 'delete',
			  key: 'delete',
			  width: 10,
			  render: (text,data) =><div>
			  						 	<Button type="primary"  onClick={ this.delete.bind(this,data) } style = {{ marginLeft:'10px' }}>
		          							删除
		        					 	</Button>
		        					</div>
			}
			];
			let data = [];
			let links = this.state.links;
			for(let i = 0;i<links.length;i++){
				data.push({
					key:links[i]._id,
					name:links[i].name,
					quan:links[i].quan,
					slogan:links[i].title,
					good:links[i].good,
					pid:links[i].pid,
					target:links[i].target,
					qd:(links[i].qd ) || '暂无',
					img:links[i].pic,
					create:links[i].createdAt
				});
			}
		return (
			this.state.username == 'admin' ? <div>
			    <Button type="primary" icon="plus"  onClick={ this.createLink.bind(this) } style={{ margin:'10px 0px'}}>
          			创建推广页
        		</Button>
        		<Search
			      placeholder="搜索推广页"
			      onSearch={ this.search.bind(this) }
			      style={{ width: 200, float:'right' }}
			    />

			    <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
		            label="推广目标"
		           >
		            <Radio.Group defaultValue="target" onChange={this.handleTargetChange.bind(this)}>
		            	<Radio.Button value="target">二合一链接</Radio.Button>
		                <Radio.Button value="quan">优惠券链接</Radio.Button>
		                <Radio.Button value="good">商品链接</Radio.Button>
		                <Radio.Button value="notbk">推广链接(非淘宝客)</Radio.Button>
		            </Radio.Group>
		           </FormItem>
			       <FormItem>
			          {getFieldDecorator('name', {
			            rules: [{ required: true, message: '推广页名称不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>推广名称</span>} placeholder="例如：商品页1" />
			          )}
			        </FormItem>
			        {
			        	this.state.target == 'good'  || this.state.target == 'notbk' ? <div></div> :  <FormItem>
				          {getFieldDecorator('quan', {
				            rules: [{ required: true, message: '优惠券链接不能为空' }],
				          })(
				            <Input prefix={<span style={{ fontSize: 13 }}>优惠券链接</span>} placeholder="例如：https://taoquan.taobao.com/coupon/unify_apply.htm?sellerId=2194810505&activityId=5c3186407cd441d48ecd2460815793e6" />
				          )}
				        </FormItem>
			        }
			        {
			        	this.state.target == 'good' ? <FormItem>
				          {getFieldDecorator('good_id', {
				            rules: [{ required: true, message: 'id不能为空' }],
				          })(
				            <Input prefix={<span style={{ fontSize: 13 }}>商品ID</span>} placeholder="例如：2194810505" />
				          )}
				        </FormItem> : <div></div> 
			        }
			        {
			        	this.state.target == 'notbk' ?   <FormItem>
				          {getFieldDecorator('pic', {
				            rules: [{ required: true, message: '图片链接不能为空' }],
				          })(
				            <Input prefix={<span style={{ fontSize: 13 }}>图片链接</span>} placeholder="例如：..." />
				          )}
				        </FormItem> : <div></div>
			        }
			        <FormItem>
			          {getFieldDecorator('good', {
			            rules: [{ required: true, message: '商品连接不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>商品连接</span>}  placeholder="例如：https://detail.tmall.com/item.htm?id=40663494639" />
			          )}
			        </FormItem>
			        {
			         this.state.target == 'good' || this.state.target == 'notbk' ? <div></div> :  <FormItem>
			          {getFieldDecorator('pid', {
			            rules: [{ required: true, message: 'pid不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>PID</span>}  placeholder="例如：mm_33320967_40070156_153504280" />
			          )}
			        </FormItem>
			    	}
			         <FormItem>
			          {getFieldDecorator('title', {
			            rules: [{ required: false, message: '推广语不能为空' }],
			          })(
			            <Input prefix={<span style={{ fontSize: 13 }}>推广语</span>}  placeholder="例如：推广语" />
			          )}
			        </FormItem>
			       {/* <FormItem
			            label="推广使用"
			          >
			             {getFieldDecorator('select')(
			            <RadioGroup>
			              <Radio value="quan">优惠券链接</Radio>
			              <Radio value="target">二合一链接</Radio>
			            </RadioGroup>
			          )}
			       </FormItem>*/}
			        <FormItem>
			          <Button type="primary" htmlType="submit" className="login-form-button">
			            一键生成
			          </Button>
			        </FormItem>
			      </Form>
		        </Modal>
			</div> : <Alert
			      message="抱歉"
			      description="您没有权限"
			      type="warning"
			    />
			)
	}
}

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



