import React from 'react';
import { Icon, Button, Input,InputNumber, Select, Spin, Table, message, DatePicker ,Modal,Form} from 'antd';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import NewDesc from '@/administration/messagePush/messageIn/messageDesc';
import '@/account/demand/techDemand.less';
import '@/administration/news/news.less';
import {getCouponCome,getCouponAuthState} from '@/tools.js';
import {couponCome} from '@/dataDic.js';
const DemandList = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            selectedRowKeys:[],
            page:pageNo,
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/voucher/selectList",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                name: this.state.name, //券面名称
            },
            success: function (data) {
                let theArr = [];
                if (!data.data || !data.data.list) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        theArr.push({
                            key: i,
                            id: thisdata.id,
                            name: thisdata.name,//券面名称
                            source:thisdata.source,//券面来源
                            money:thisdata.money,//面额
                            durationDay: thisdata.durationDay, //活动期限
                            activeState: thisdata.activeState, //抵用券状态
                        });
                    };
                };
                this.state.pagination.current = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
                if(data.data&&data.data.list&&!data.data.list.length){
					this.state.pagination.current=0;
					this.state.pagination.total=0;
				};
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            searchMore: true,
            validityPeriodDate: [],
            releaseDate: [],
            visitModul:false,
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            columns: [
                 {
                    title: '劵面名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '数量(枚)',
                    dataIndex: 'money',
                    key: 'money',
                },
                {
                    title: '抵用券有效期(天)',
                    dataIndex: 'durationDay',
                    key: 'durationDay'
                },
                {
                    title: '抵用券来源',
                    dataIndex: 'source',
                    key: 'source',
                    render: text => { return getCouponCome(text); }
                },
                {
                    title: '抵用券状态',
                    dataIndex: 'activeState',
                    key: 'activeState',
                    render: text => { return getCouponAuthState(text); }
                }
            ],
            dataSource: [],
            searchTime: [,]
        };
    },
    //发布
    submission(record){
        this.setState({
            loading:true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/message/sendMessage",
            data: {
                messageId:record.id,
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('推送成功.');
                this.setState({
                    loading: false,
                });
                this.loadData(this.state.page)
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    //抵用券停用
    block(){
    	let id;
		for(let idx = 0; idx < this.state.selectedRows.length; idx++) {
			let rowItem = this.state.selectedRows[idx];
			if(rowItem.id) {
				id=rowItem.id;
			};
		};
        this.setState({
            loading:true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/voucher/update",
            data: {
                id:id,
                activeState:"0"
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('该劵已停用');
                this.loadData(this.state.page)
            } else {
                message.warning(data.error[0].message);
            };
            this.setState({
                loading: false,
            });
        }.bind(this));
    },
    //进入页面
    componentWillMount() {
        this.loadData();
    },
   //新增抵用券
    newSubmit(e) {
        e.preventDefault();
        if(!this.state.newName) {
			message.warning('请填写券面名称');
			return false;
		};
		if(!this.state.source) {
			message.warning('请确认券的来源');
			return false;
		};
		if(!this.state.money) {
			message.warning('请填写券面金额');
			return false;
		};
		if(!this.state.durationDay) {
			message.warning('请填写使用期限');
			return false;
		};
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/voucher/save",
            data: {
                name:this.state.newName,//抵用券名称
                source:this.state.source,//抵用券来源
                money:this.state.money,//抵用券面额
                durationDay:this.state.durationDay,//抵用券使用期限
                limitUse:0,//是否限定，在这里固定传0
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('新增成功！');
                this.setState({
                    loading: false,
                    visitModul:false
                });
                    this.loadData(this.state.page);
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },

    addClick() {
        this.state.RowData = {};
        this.setState({
            newName:'',
            source:undefined,
            money:'',
            durationDay:'',
            visitModul: true
        });
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData(this.state.page);
        };
    },
    //详情打开
	visitOk(e) {
		this.setState({
			visitModul: false
		});
	},
	//详情关闭
	visitCancel(e) {
		this.state.fileList = [];
		this.setState({
			visitModul: false,
		});
	},
    search() {
        this.loadData();
    },
    reset() {
        this.state.name = '';
        this.loadData();
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1)
                });
            }
        };
        const FormItem = Form.Item;
        const { RangePicker } = DatePicker;
        const hasSelect = this.state.selectedRowKeys.length;
        const formItemLayout = {
			labelCol: { span: 6 },
			wrapperCol: { span: 14 },
		};
		const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="user-content" >
                <div className="content-title">
                    <span>券面管理</span>
                </div>
                <div className="user-search">
              	  	<Button type="primary" onClick={this.addClick} style={{float:'right'}}>新增通用劵<Icon type="plus" /></Button>
                    <Input placeholder="劵面名称"
                        value={this.state.name}
                        onChange={(e) => { this.setState({ name: e.target.value }); }} />
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <Button type="primary" onClick={this.block} disabled={!hasSelected}>停用<Icon type="plus" /></Button>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            rowSelection={rowSelection}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <NewDesc
                    data={this.state.RowData}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
                <Modal	
				      className="customeDetails"
				      footer=''
			          title="新增通用券"
			          width='400px'
			          visible={this.state.visitModul}
			          onOk={this.visitOk}
					  onCancel={this.visitCancel}							          							          
			        >	
			    	<Form layout="horizontal" onSubmit={this.newSubmit} id="demand-form">
	                	<Spin spinning={this.state.loading}>
	                		<div className="clearfix" >
		                		<FormItem 
				                     {...formItemLayout}
				                    label={<span><strong style={{color:'#f00'}}> * </strong>劵面名称</span>}
			                        >
		                    	 	<Input placeholder="券面名称"  value={this.state.newName} onChange={(e) => {
			                        this.setState({ newName:  e.target.value }) }} />
		                    	 </FormItem>
		                    	 <FormItem 
				                     {...formItemLayout}
				                    label={<span><strong style={{color:'#f00'}}> * </strong>优惠券来源</span>}
			                        >
		                    	 	 <Select placeholder="优惠券来源" value={this.state.source}  
								    		onChange={(e)=>{this.setState({source:e})}}> 
	                                     {
	                                        couponCome.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>  
		                    	 </FormItem>
		                    	 <FormItem 
				                     {...formItemLayout}
				                    label={<span><strong style={{color:'#f00'}}> * </strong>数量</span>}
			                        >
                                     <InputNumber min={0} 
                                        formatter={(value)=>value}
                                        parser={(val)=>parseInt(val)||0}
                                        max={999999} step={0} placeholder="数量" value={this.state.money} onChange={(e) => {
			                        this.setState({ money:  e }) }} /> 枚
		                    	 </FormItem>
		                    	 <FormItem 
				                     {...formItemLayout}
				                    label={<span><strong style={{color:'#f00'}}> * </strong>使用期限</span>}
			                        >
                                    <InputNumber min={0} max={9999} 
                                     formatter={(value)=>value}
                                     parser={(val)=>parseInt(val)||0}
                                     step={0} placeholder="使用期限"  value={this.state.durationDay} onChange={(e) => {
			                        this.setState({ durationDay:  e }) }} /> 天
		                    	 </FormItem>
	                    	 </div>
	                    	 <Button className="setSubmit" type="primary" htmlType="submit" style={{marginLeft:'92px'}}>保存</Button>  
					         <Button  type="ghost" onClick={this.visitCancel}  style={{marginLeft:'40px',marginBottom:20}}>取消</Button>
	                	</Spin>
					</Form>	
			    </Modal>
            </div>
        );
    }
});

export default DemandList;