import React from 'react';
import ReactDom from 'react-dom';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import '../content.less';
import { Form,Radio, Icon, Button, Input, Select, Spin, Table, Switch, message, DatePicker, Modal, Upload,Popconfirm,TimePicker } from 'antd';
import {categoryState} from '../../../dataDic.js';
import {getCategoryState} from '../../../tools.js';
const BusinessCategory=Form.create()(React.createClass({
	loadData(pageNo, apiUrl) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/open/api/admin/Varieties/vtList',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                cname: this.state.cname, //品类名称
                superName:this.state.superName,//上级品类编号
                layer:this.state.layer,//组织层级
                status:this.state.depNo,//品类状态
            },
            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,//品类ID
                            cid: thisdata.cid,//品类编号
                            cname: thisdata.cname,//品类名称
                            layer: thisdata.layer,//品类层级
                            superName: thisdata.superName,//上级品类
                            status: thisdata.status,//上级品类状态
                        });
                    };
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                };
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            searchMore: true,
            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: 'cid',
                    key: 'cid',
                }, {
                    title: '品类名称',
                    dataIndex: 'cname',
                    key: 'cname',
                },  {
                    title: '品类层级',
                    dataIndex: 'layer',
                    key: 'layer',
                    //render: text => { return getAchievementCategory(text); }
                }, {
                    title: '上级品类',
                    dataIndex: 'superName',
                    key: 'superName',
                },{
                    title: '品类状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: text => { return getCategoryState(text) }
                }
            ],
            dataSource: [],
        };
    },
    componentWillMount() {
       this.selectSuperId();
    },
    //获取上级品类
    selectSuperId() {  
    	this.state.data = []
         $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/open/api/admin/Varieties/getSuperList",
                data:{
                  
                },
                success: function (data) { 
                	console.log(data);
                		let theArr = [];
					    let thedata=data.data;
					    if (!thedata) {
		                    if (data.error && data.error.length) {
		                        message.warning(data.error[0].message);
		                    };	
		                    thedata = {}; 
		              };   
					    var contactIds=[];
				        //for (let item in data.data) {
				        	for(var i=0;i<data.data.length;i++){
		                    let theData = data.data[i];
		                    theArr.push(
		                        <Select.Option value={i.toString()} key={theData.cname}>{theData.cname}</Select.Option>
		                    );
		                };
						this.setState({	
							SuperArr:thedata,
		                    contactsOption: theArr, 
		                    orderStatusOptions:data.data,
	                    });
	                    
					}.bind(this),
				}).always(function () {
				this.loadData();
	            this.setState({
	                loading: false
	            });
	        }.bind(this));
	},
    //整行点击
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    //新增一个品类，保存
    addhandleSubmit(e){
    	e.preventDefault();	
//  	if(!this.state.theTypes){
//  		message.warning('请输入负责人姓名');
//  		return false;
//  	}
//  	if(!this.state.typeOrganization){
//  		message.warning('请选择组织类型');
//  		return false;
//  	}
//  	if(!this.state.upOrganization){
//  		message.warning('请选择上级组织'); 
//  		return false;
//  	}
		this.props.form.validateFields((err, values) => {                                 
            if (!err) {
                this.setState({
                    loading: true
                }); 
                //上级组织字典
//              let nameText=this.state.SuperArr
//              let superText=nameText[parseInt(this.state.upOrganization)].name
                $.ajax({
                    method: "post",
                    dataType: "json",
                    crossDomain: false,
                    url:globalConfig.context + '/open/api/admin/Varieties/addVarieties',
                    data:{
                    	cname:this.state.nameOrganization,//组织名称
                    	superId:superText,//上级组织
                        remarks:this.state.remarksOrganization,//组织职能说明
                    	}
                }).done(function (data) { 
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功！'); 
                        this.handleCancel();
                        this.loadData(); 
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    delectRow() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            };
        };
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/open/api/admin/Varieties/deleteState",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功！');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
    addClick() {
        this.state.RowData = {};
        this.setState({
            visible: true
        });
    },
    editClick() {
        this.state.RowData = {};
        this.setState({
            editvisible: true
        });
    },
   	handleCancel() {
        this.setState({ visible: false })
    },
    edithandleCancel() {
        this.setState({ editvisible: false })
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.serialNumber = undefined;
        this.state.name = undefined;
        this.state.keyword = undefined;
        this.state.category = undefined;
        this.state.ownerType = undefined;
        this.state.releaseStatus = undefined;
        this.state.auditStatus = undefined;
        this.state.searchName = undefined;
        this.state.releaseDate = [];
        this.state.boutique = '';
        this.state.hot='' ;
        this.loadData();       
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    render() {
    	const FormItem = Form.Item
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1)
                });
            }
        };
         const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
       };
       	const { getFieldDecorator } = this.props.form;
        const hasSelected = this.state.selectedRowKeys.length > 0;
        const { RangePicker } = DatePicker;
        
        return (
            <div className="user-content" >
                <div className="content-title">
	                <div className="user-search">
	                    <Input placeholder="业务品类名称" style={{width:'150px',marginRight:'10px',marginBottom:'10px'}}
	                        value={this.state.serialNumber}
	                        onChange={(e) => { this.setState({ serialNumber: e.target.value }); }} />
	                    <Select placeholder="上级品类"
                            style={{ width:'200px',marginRight:'10px' }}
                            value={this.state.superId}
                            onChange={(e) => { this.setState({ superId: e }) }} notFoundContent="未获取到上级品类列表">
                            {this.state.contactsOption}
		                </Select>
	                    <Button type="primary" onClick={this.search} style={{marginRight:'10px'}}>搜索</Button>
	                    <Button onClick={this.reset} style={{marginRight:'10px'}}>重置</Button>
                        <Popconfirm title="是否删除?" onConfirm={this.delectRow} okText="是" cancelText="否">
						     <Button style={{ background: "#ea0862", border: "none", color: "#fff",marginRight:'10px' ,marginLeft:'10px'}}
	                   			 disabled={!hasSelected} 
	                    		 >删除<Icon type="minus" />
	           			     </Button>
						</Popconfirm>
						<Popconfirm title="是否停用?" onConfirm={this.blockRow} okText="是" cancelText="否">
						     <Button style={{ background: "#ea0862", border: "none", color: "#fff",marginRight:'10px' ,marginLeft:'10px'}}
	                   			 disabled={!hasSelected} 
	                    		 >停用<Icon type="minus" />
	           			     </Button>
						</Popconfirm>
	                    <span style={{marginRight:'20px'}}>更多搜索    <Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
	                    <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {display: 'inline-block'}}>
	                    	<Select placeholder="品类层级"
	                            style={{ width:'150px',marginRight:'10px' }}
	                            value={this.state.shareTypeSearch}
	                            onChange={(e) => { this.setState({ shareTypeSearch: e }) }}>
	                            <Select.Option value="1" >一级</Select.Option>
	                            <Select.Option value="2" >二级</Select.Option>
	                            <Select.Option value="3" >三级</Select.Option>
	                            <Select.Option value="4" >四级</Select.Option>
	                            <Select.Option value="5" >五级</Select.Option>
	                            <Select.Option value="6" >六级</Select.Option>
		                	</Select>
		                    <Select placeholder="品类状态"
		                            style={{width:'150px',marginRight:'50px'}}
		                            value={this.state.shareTypeSearch}
		                            onChange={(e) => { this.setState({ shareTypeSearch: e }) }}>
		                            <Select.Option value="0" >正常</Select.Option>
		                            <Select.Option value="1" >停用</Select.Option>
		                    </Select>
	                    </div>
	                    <Button type="primary" className="addButton" onClick={this.addClick} style={{float:'right',marginRight:'200px'}}>新增客户<Icon type="plus" /></Button>
	                	<Button type="primary" className="addButton" onClick={this.editClick}>编辑客户<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>
	             
	                 <div className="patent-desc">
	                    <Modal maskClosable={false} visible={this.state.visible}
	                        onOk={this.checkPatentProcess} onCancel={this.handleCancel}
	                        width='400px'
	                        title='新增品类'                       
	                        footer=''
	                        className="admin-desc-content">
	                         <Form horizontal onSubmit={this.addhandleSubmit} id="demand-form">
				                <Spin spinning={this.state.loading}>
				                    <div className="clearfix">
				                    	<FormItem className="half-item"
					                            labelCol={{ span: 7 }}
					                        	wrapperCol={{ span: 12 }}
					                            label="品类名称" >
				                    	     <Input placeholder="品类名称" value={this.state.nameCategory} style={{width:'95%'}}
				                                onChange={(e)=>{this.setState({nameCategory:e.target.value})}} required="required"/>
				                           		<span className="mandatory" style={{color:'red',marginLeft:'5px'}}>*</span>
					                    </FormItem>
				                    </div>
				                    <div className="clearfix">
					                    <FormItem  
					                    	labelCol={{ span: 7 }}
					                        wrapperCol={{ span: 12 }}
				                           label="上级品类"
			                               > 
			                                <Select placeholder="请选择上级品类" value={this.state.upCategory} onChange={(e)=>{this.setState({upCategory:e})}}
				                                notFoundContent="未获取到上级品类列表" style={{width:'95%'}} required="required">
				                                {this.state.contactsOption}
				                            </Select> 
				                            <span className="mandatory" style={{color:'red',marginLeft:'5px'}}>*</span>
			                   		    </FormItem>
		                   		    </div>
				                    <FormItem wrapperCol={{ span: 12, offset: 7 }}>
				                        <Button className="set-submit" type="primary" htmlType="submit">保存</Button>  
				                        <Button className="set-submit" type="ghost" onClick={this.handleCancel} style={{marginLeft:'50px'}}>取消</Button>
				                    </FormItem> 
				                </Spin>
				            </Form >
	                    </Modal>
                	 </div>
                	 
                	 
                	 
                	 <div className="patent-desc">
	                    <Modal maskClosable={false} visible={this.state.editvisible}
	                        onOk={this.checkPatentProcess} onCancel={this.edithandleCancel}
	                        width='600px'
	                        title='编辑品类'                       
	                        footer=''
	                        className="admin-desc-content">
	                         <Form horizontal onSubmit={this.edithandleSubmit} id="demand-form">
				                <Spin spinning={this.state.loading}>
				                    <div className="clearfix">
				                    	<FormItem className="half-item"
					                            labelCol={{ span: 7 }}
					                        	wrapperCol={{ span: 12 }}
					                            label="品类名称" >
				                    	     {getFieldDecorator('name', {
				                                rules: [{ required: true, message: '此项为必填项!' }],
				                                initialValue: this.state.name
				                            })(
				                                <Input placeholder="品类名称" />
				                                )}
					                    </FormItem>
				                    </div> 
				                    <div className="clearfix">
				                    	<FormItem className="half-item" 
				                         	labelCol={{ span: 7 }}
					                        wrapperCol={{ span: 12 }}
				                           	label="品类状态"
				                         > 
				                         {getFieldDecorator('societyTagt', {
					                                rules: [{ required: true, message: '此项为必填项!' }],
					                                initialValue: this.state.societyTagt
				                                })(
											  <Select placeholder="品类状态"> 
				                                {
				                                    categoryState.map(function (item) {
				                                        return <Select.Option key={item.value} >{item.key}</Select.Option>
				                                    })
				                                }
				                              </Select>
				                            )}
				                   		 </FormItem>
				                    </div>
				                    <div className="clearfix">
					                    <FormItem  
					                    	labelCol={{ span: 7 }}
					                        wrapperCol={{ span: 12 }}
				                           label="上级品类"
			                               > 
			                               {getFieldDecorator('societyTagt', {
					                                rules: [{ required: true, message: '此项为必填项!' }],
					                                initialValue: this.state.societyTagt
				                                })(
						                        <Select placeholder="上级品类"  
								                        value={this.state.lastName}
								                        onChange={this.hundleName}>
								                        {this.state.orderStatusOption}
						                    	</Select>
					                    	 )}
			                   		    </FormItem>
		                   		    </div>
		                   		    <div className="clearfix">
				                    	<FormItem className="half-item"
						                    labelCol={{ span: 7 }}
						                    wrapperCol={{ span: 12 }}
						                    label="品类层级"
					                        >
					                        <span>{}</span>
					                    </FormItem>
					                </div>
		                   		    <div className="clearfix">
				                    	<FormItem className="half-item"
						                    labelCol={{ span: 7 }}
						                    wrapperCol={{ span: 12 }}
						                    label="品类编号"
					                        >
					                        <span>{}</span>
					                    </FormItem>
					                </div>
					                <div className="clearfix" >
				                    	<FormItem className="half-item"
						                    labelCol={{ span: 7 }}
						                    wrapperCol={{ span: 12 }}
						                    label="创建人"
					                        >
					                        <span>{}</span>
					                    </FormItem>
					                </div>
					                <div className="clearfix">
				                    	<FormItem className="half-item"
						                    labelCol={{ span: 7 }}
						                    wrapperCol={{ span: 12 }}
						                    label="创建时间"
					                        >
					                        <span>{}</span>
					                    </FormItem>
					                </div>
		                   		    <div className="clearfix">
			                   		   <FormItem className="half-item"
				                            labelCol={{ span: 7 }}
					                    	wrapperCol={{ span: 12 }}
				                            label="更新时间" >	
			                               <DatePicker placeholder="更新日期" value={moment(this.state.createYear,'YYYY-MM-DD')} onChange={(time) => {this.setState({createYear: time});}}/>					                               			                               		                           
					                       <TimePicker placeholder="更新时间" value={moment(this.state.creatMent, 'HH:mm:ss')} onChange={(time) => { this.setState({creatMent: time}); }}/>	
			            				</FormItem> 
					                </div>    
				                    <FormItem wrapperCol={{ span: 12, offset: 7 }}>
				                        <Button className="set-submit" type="primary" htmlType="submit">保存</Button>  
				                        <Button className="set-submit" type="ghost" onClick={this.edithandleCancel} style={{marginLeft:'100px'}}>取消</Button>
				                    </FormItem> 
				                </Spin>
				            </Form >
	                    </Modal>
                	 </div>
                	 
            	</div>
            </div>
        );
    }
}));

export default BusinessCategory;
