import React from 'react';
import { Icon, Table, Modal, message, Spin, Input, Select, Button, Form ,Tree} from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import './userMangagement.less';
const TreeNodet = Tree.TreeNode;

const Newrole = Form.create()(React.createClass({
	addloadData() {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "post",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + '/api/admin/permissions',
			data: {
			},
			success: function(data) {
				let theArr = [];
				if(!data.data || !data.data.one) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
				} else {
					this.setState({
						Interface: data.data.one,
					});
				};
			}.bind(this),
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	getInitialState() {
		return {
			loading: false,
			visible: false,
			expandedKeys: [],
			autoExpandParent: true,
			checkedKeys: [],
			selectedKeys: [],
			renderTreeNodes: undefined,
			Interface:[]
		};
	},
	handleSubmit(e) {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			let selectAllId = this.state.checkedKeys||[];
			if(!err) {
				this.setState({
					loading: true
				});
				if(selectAllId.checked){
					if(selectAllId.checked[0]==null){
						selectAllId.checked.splice(0,1)
					}
				}
				$.ajax({
					method: "POST",
					dataType: "json",
					crossDomain: false,
					url: globalConfig.context + '/api/admin/role',
					data: {
						data:JSON.stringify({
							'id':this.state.ids?this.state.ids:null,
							'roleName': this.state.roleName,
							'permissions': selectAllId.checked?selectAllId.checked:selectAllId
						})
					}
				}).done(function(data) {
					this.setState({
						loading: false
					});
					if(!data.error.length) {
						message.success('保存成功！');
						this.handleOk()
					} else {
						message.warning(data.error[0].message);
					}
				}.bind(this));
			}
		});
	},
	//查看基本详情基本信息
    loaduser(record){
    	if(record){
    	$.ajax({
            method: "post",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + '/api/admin/role/rolePermission',
            data: {
              id: record.id
            },
            success: function (data) {
                let thisData = data.data;                
                if (!thisData) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thisData = {};
                };
                let idList=[];
                thisData.map(function(item){
                	idList.push(
                		item.pid
                	)
                })
                this.setState({
					ids:record.id,
                	roleName:thisData[0].rname,
                	checkedKeys:idList,	
                });                  
            }.bind(this),
       }).always(function () {
            this.setState({            	
                loading: false
            });
        }.bind(this));  
       }
    },
	handleOk(e) {
		this.setState({
			visible: false,
		});
		this.props.closeDesc(false, true);
	},
	handleCancel(e) {
		this.setState({
			visible: false,
		});
		this.props.closeDesc(false);
	},
	componentWillMount() {
		this.addloadData()
	},
	componentWillReceiveProps(nextProps) { //props改变时触发
		this.state.visible = nextProps.showDesc;
		if(nextProps.userDetaile && nextProps.showDesc) {
			if(nextProps.datauser && nextProps.datauser.id) {
				this.loaduser(nextProps.datauser)
			}
		}else{
			this.setState({
				checkedKeys: [],
				datauser: {},
				roleName:'',
				ids:'',
			})
		}
	},
	//权限多选
	onExpand(expandedKeys){
		this.setState({
			expandedKeys,
			autoExpandParent: false,
		});
	},
	onCheck(checkedKeys){
		this.setState({checkedKeys:checkedKeys });
	},
	onSelect(selectedKeys, info){
		this.setState({ selectedKeys });
	},
	renderTreeNodes(data){
		return data.map((item) => {
			if(item.children) {
				return(
					<TreeNodet title={item.name} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNodet>
				);
			}
			return <TreeNodet {...item} />;
		});
	},
	tableRowClick(record, index) {
	},
	render() {
		const FormItem = Form.Item
		const formItemLayout = {
			labelCol: { span: 8 },
			wrapperCol: { span: 14 },
		};
		return(
			<div>
            <Modal maskClosable={false} visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='1000px'
                        title={!this.props.userDetaile?'添加角色':'编辑角色'}                      
                        footer=''
                        className="admin-desc-content">
			            <Form layout="horizontal" onSubmit={this.handleSubmit} id="demand-form" style={{paddingBottom:'40px'}} required="required">
			                <Spin spinning={this.state.loading}>
			                        <div className="clearfix">
			                            <div className="clearfix">
					                    	<FormItem className="half-item"
						                            {...formItemLayout}
						                            label="角色名称" >                             
					                                    <Input placeholder="角色名称" value={this.state.roleName} onChange={(e)=>{this.setState({roleName:e.target.value})}} style={{width:'200px'}} required="required"/>
						                    		<span className="mandatory">*</span>
						                    </FormItem>
						                    <FormItem className="half-item"
						                            {...formItemLayout}
						                            label="" > 
							                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>  
				                                <Button className="set-submit" type="ghost" onClick={this.handleCancel}>返回</Button> 
			                                </FormItem>
						                </div>
						                <div className="clearfix" style={{marginLeft:'90px'}}>
						                		<Tree
											        checkable
											        onExpand={this.onExpand}
											        checkStrictly={true}
											        expandedKeys={this.state.expandedKeys}
											        autoExpandParent={this.state.autoExpandParent}
											        onCheck={this.onCheck}
											        checkedKeys={this.state.checkedKeys}
											        onSelect={this.onSelect}
											        selectedKeys={this.state.selectedKeys}
											      >
											        {this.renderTreeNodes(this.state.Interface)}
											      </Tree>
						                </div>
				                    </div>
			                </Spin>
			            </Form >
			        </Modal>    
    	    </div>
		)
	}
}));

export default Newrole;