import React from 'react';
import ReactDom from 'react-dom';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import { Form,Radio, Icon, Button, Input, Select, Spin, Table, Switch, message, DatePicker, Modal, Upload ,Checkbox,Tabs} from 'antd';
import Newrole from "./newRole.jsx"
import './userMangagement.less'
import {roleResources} from '../../../dataDic.js';
import {ChooseList} from "../../order/orderNew/chooseList";
const CheckboxGroup = Checkbox.Group;

const {TabPane} = Tabs
const Roles=Form.create()(React.createClass({
	loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/roles',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                roleName:this.state.roleNameSearch,
            },
            success: function (data) {
                let theArr = [];
                if (!data.data) {
                    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,
	                         roleName: thisdata.roleName,
	                         creater:thisdata.creater,
	                         createTime:thisdata.createTimez,
                        });
                    };
                    this.setState({
                        page: data.data.pageNo
                    })
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                };
                if(!data.data.list.length){
					this.state.pagination.current=0
					this.state.pagination.total=0
				}
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination,
                    selectedRowKeys:[]
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
        	datauser:{},
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            page: 1,
            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: 'roleName',
                    key: 'roleName',
                    width:'300px'
                }, {
                    title: '创建人',
                    dataIndex: 'creater',
                    key: 'creater',
                    width:'300px'
                }, {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                },{
                    title: '离职转交配置',
                    dataIndex: 'ee',
                    key: 'ee',
                    render: (text, record, index) => {
                    	return <div>
							<Button onClick={(e) =>{ e.stopPropagation(), this.visit(record)}} type="primary">离职转交配置</Button>
                        </div>
					}
                },
            ],
            dataSource: [],
        };
    },
    //进入离职权限配置
	visit(record) {
		let rid=record.id;
		this.state.resources=undefined;
		this.setState({
            visible2: true,
            rid:record.id,
            name:record.roleName,
        });
        this.resourcesDetail(rid);
	},
	//关闭离职配置
	handleCancel2(){
		this.setState({
            visible2: false
        });
	},
	 //点击离职资源配置保存
    resourcesDetail(rid) {
        this.setState({
            selectedRowKeys: [],
            loading: true,
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/role/ResourcesDetail",
            data: {
            	rid:rid,
            }
        }).done(function (data) {
            if (!data.error.length) {
            	let resourcesData=[];
            	for(let i=0;i<data.data.length;i++){
            		resourcesData.push(data.data[i].resources.toString())
            	}
                this.setState({
                    loading: false,
                    resources:resourcesData
                });
            } else {
                message.warning(data.error[0].message);
            };

        }.bind(this));
    },
	 //点击离职资源配置保存
    resourcesSubmit(e) {
    	e.preventDefault();
        this.setState({
            selectedRowKeys: [],
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/role/addResources",
            data: {
            	rid:this.state.rid,
            	resources:this.state.resources.join(","),

            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('配置成功！');
                this.setState({
                    loading: false,
                    visible2: false
                });
            } else {
                message.warning(data.error[0].message);
            };

        }.bind(this));
    },
    componentWillMount() {
        this.loadData();
    },
    tableRowClick(record, index) {
    	this.state.userDetaile=true;
        this.state.datauser = record;
        this.setState({
            showDesc: true
        });
    },
    //删除
    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: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/role/delete",
            data: {
            	data:JSON.stringify(
            		deletedIds
            	)

            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功！');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData(this.state.page);
        }.bind(this));
    },
    addClick() {
    	this.state.userDetaile=false;
        this.setState({
            showDesc: true
        });
    },
    closeDesc(e, s) {
    	this.state.userDetaile=false;
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
    	this.state.roleNameSearch='';
        this.loadData();
    },
    changeList(arr) {
        const newArr = [];
        this.state.columns.forEach(item => {
            arr.forEach(val => {
                if (val === item.title) {
                    newArr.push(item);
                }
            });
        });
        this.setState({
            changeList: newArr
        });
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
	                this.setState({
	                    selectedRows: selectedRows.slice(-1),
	                    selectedRowKeys: selectedRowKeys.slice(-1)
	                });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
			   this.setState({
			   		selectedRowKeys:[]
			   })
			},
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        const FormItem = Form.Item
        return (
            <div className="user-content" >
                <div className="content-title">
                    <Tabs
                        defaultActiveKey="1"
                        onChange={this.callback}
                        className="test">
                        <TabPane tab="搜索" key="1">
	                <div className="user-search">
	                    <Input placeholder="角色名称" style={{width:'150px'}}
	                        value={this.state.roleNameSearch}
	                        onChange={(e) => { this.setState({ roleNameSearch: e.target.value }); }} />
	                    <Button type="primary" onClick={this.search}>搜索</Button>
	                    <Button onClick={this.reset}>重置</Button>
	                    <Button type="danger"
	                        disabled={!hasSelected}
	                        onClick={this.delectRow}>删除<Icon type="minus" /></Button>

                    </div>
                    </TabPane>
                        <TabPane tab="新增用户" key="2">
                            <Button type="primary" className="addButton" style={{float:"left",marginBottom:10,marginLeft:10}} onClick={this.addClick} >新增用户<Icon type="user" /></Button>
                    </TabPane>
                        <TabPane tab="更改表格显示数据" key="3">
                            <div style={{ marginLeft: 10 }}>
                                <ChooseList
                                    columns={this.state.columns}
                                    changeFn={this.changeList}
                                    changeList={this.state.changeList}
                                    top={55}
                                    margin={11}
                                />
                            </div>
                        </TabPane>
                    </Tabs>
	                <div className="patent-table">
	                    <Spin spinning={this.state.loading}>
	                        <Table columns={
                                this.state.changeList
                                    ? this.state.changeList
                                    : this.state.columns
                                 }
	                            dataSource={this.state.dataSource}
	                            rowSelection={rowSelection}
	                            pagination={this.state.pagination}
	                            onRowClick={this.tableRowClick} />
	                    </Spin>
	                </div>
	                <Newrole
	                    userDetaile={this.state.userDetaile}
	                    datauser={this.state.datauser}
	                    showDesc={this.state.showDesc}
	                    closeDesc={this.closeDesc} />
	            </div >
	            <div className="patent-desc">
                    <Modal maskClosable={false} visible={this.state.visible2}
                        onOk={this.checkResources} onCancel={this.handleCancel2}
                        width='600px'
                        title='离职转交配置'
                        footer=''
                        className="admin-desc-content">
                         <Form horizontal onSubmit={this.resourcesSubmit} id="add-form">
			                <Spin spinning={this.state.loading}>
			                	<FormItem
		                         	labelCol={{ span: 10 }}
			                        wrapperCol={{ span: 4 }}
		                           	label="角色名称"
		                         >
									{this.state.name}
		                   		 </FormItem>
			                    <FormItem
		                         	labelCol={{ span: 10 }}
			                        wrapperCol={{ span: 4 }}
		                           	label="请选择离职转交配置"
		                         >
	                              <CheckboxGroup options={roleResources} value={this.state.resources} onChange={(e)=>{this.setState({resources:e})}} />

		                   		 </FormItem>
			                    <FormItem wrapperCol={{ span: 12, offset: 7 }}>
			                        <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
			                        <Button className="set-submit" type="ghost" onClick={this.handleCancel2} style={{marginLeft:'100px'}}>取消</Button>
			                    </FormItem>
			                </Spin>
			            </Form >
                    </Modal>
            	 </div>
            </div>
        );
    }
}));

export default Roles;

