import React from 'react';
import { Icon,  Modal, message,  AutoComplete,Spin, Input, Select, Button, Form,Upload } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import './userMangagement.less';
import {urlType} from '../../../dataDic.js';
const Option = AutoComplete.Option;

const Addjurisdiction = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            visible:false
        };
    },
    //保存
    handleSubmit(e) {
    	e.preventDefault();
    	let theType;
    	if(this.props.userDetaile){
			if (!this.state.auto) {
				message.warning('请输入上级模块')
				return false;
			}
		}
    	let api=this.props.userDetaile?'/api/admin/updateById':'/api/admin/addSupPermission';
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                  method: "POST",
                  dataType: "json",
                  crossDomain: false,
                  url: globalConfig.context + api,
                  data: {
                    id: this.state.ids,
                    name: this.state.name, //接口名称
                    url: this.state.url, //接口路径
                    type: this.state.urlType || "0",
                    superId: this.state.auto, //接口上级模板功能
                    showOrder: this.state.showOrder,
                  },
                }).done(
                  function (data) {
                    this.setState({
                      loading: false,
                    });
                    if (!data.error.length) {
                      message.success("保存成功!");
                      this.props.closeDesc(false, true);
                    } else {
                      message.warning(data.error[0].message);
                    }
                  }.bind(this)
                );
            }
        });
    },
    //主管初始加载(自动补全)
	supervisor(e){
		$.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/selectName",
            data:{
            	name:e
            },
            success: function (data) {
				       let thedata=data.data;
				    if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thedata = {};
              };
					this.setState({
						customerArr:thedata,
                    });
				}.bind(this),
			}).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
	},
	//上级主管输入框失去焦点是判断客户是否存在
	selectAuto(value,options){
		this.setState({
			auto:value
		})
	},
	blurChange(e){
		let theType;
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType=item.id
                }
           });
   	    }
		this.setState({
			theTypes:theType
		})
	},
	//值改变时请求客户名称
	httpChange(e){
		if(e.length>=1){
			this.supervisor(e);
		}
		this.setState({
			auto:e
		})
	},
	//查看基本详情基本信息
    loaduser(record){
    	if(record){
    	$.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/selectAllById',
            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 = {};
                };
                this.setState({
                  ids: thisData.id,
                  name: thisData.name, //接口名称
                  urlType: thisData.type.toString(),
                  url: thisData.url, //接口路径
                  preModule: thisData.preModule, //接口上级模板功能
                  createId: thisData.createId,
                  createTime: new Date(thisData.createTime).toLocaleString(),
                  updateTime: new Date(thisData.updateTime).toLocaleString(),
                  autNo: thisData.autNo,
                  auto: thisData.superId,
                  showOrder: thisData.showOrder,
                });
            }.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);
    },
    componentWillReceiveProps(nextProps) {
    	this.state.visible = nextProps.showDesc;
    	this.state.Detaile=nextProps.userDetaile;
		if(!nextProps.userDetaile){
			this.state.name='';
			this.state.url='';
			this.state.urlType=undefined;
   		}else{
    		this.loaduser(nextProps.datauser)
    	   }
      },
    render() {
        const theData = this.state.datauser||{};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };
        const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group,index) =>
				      <Option key={index} value={group.name}>{group.name}</Option>
				     )
        return (
          <div>
            <Modal
              maskClosable={false}
              visible={this.state.visible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
              width="600px"
              title={this.props.userDetaile ? "权限详情" : "新建权限"}
              footer=""
              className="admin-desc-content"
            >
              <Form
                layout="horizontal"
                onSubmit={this.handleSubmit}
                id="demand-form"
              >
                <Spin spinning={this.state.loading}>
                  <div className="clearfix">
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="接口名称"
                    >
                      <Input
                        placeholder="接口名称"
                        value={this.state.name}
                        style={{ width: "230px" }}
                        onChange={(e) => {
                          this.setState({ name: e.target.value });
                        }}
                        required="required"
                      />
                      <span className="mandatory">*</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="接口路径"
                    >
                      <Input
                        placeholder="接口路径"
                        value={this.state.url}
                        style={{ width: "230px" }}
                        onChange={(e) => {
                          this.setState({ url: e.target.value });
                        }}
                        required="required"
                      />
                      <span className="mandatory">*</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="接口类型"
                    >
                      {this.props.userDetaile ? (
                        <Select
                          placeholder="选择接口类型"
                          style={{ width: "230px" }}
                          value={this.state.urlType}
                          onChange={(e) => {
                            this.setState({ urlType: e });
                          }}
                        >
                          {urlType.map(function (item) {
                            return (
                              <Select.Option key={item.value}>
                                {item.key}
                              </Select.Option>
                            );
                          })}
                        </Select>
                      ) : (
                        <span>导航</span>
                      )}
                    </FormItem>
                  </div>
                    {this.props.userDetaile ? <div
                    className="clearfix"
                  >
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="上级功能模块"
                    >
                      <AutoComplete
                        className="certain-category-search"
                        dropdownClassName="certain-category-search-dropdown"
                        dropdownMatchSelectWidth={false}
                        dropdownStyle={{ width: 230 }}
                        size="large"
                        style={{ width: "230px" }}
                        dataSource={options}
                        placeholder="输入名称"
                        value={this.state.auto}
                        onChange={this.httpChange}
                        filterOption={true}
                        onBlur={this.blurChange}
                        onSelect={this.selectAuto}
                      >
                        <Input />
                      </AutoComplete>
                      <span className="mandatory">*</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="排序"
                    >
                      <Input
                        placeholder="排序数字"
                        value={this.state.showOrder}
                        style={{ width: "230px" }}
                        onChange={(e) => {
                          this.setState({ showOrder: e.target.value });
                        }}
                        required="required"
                      />
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="权限编号"
                    >
                      <span>{this.state.autNo}</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="创建人"
                    >
                      <span>{this.state.createId}</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="创建时间"
                    >
                      <span>{this.state.createTime}</span>
                    </FormItem>
                    <FormItem
                      className="half-middle"
                      {...formItemLayout}
                      label="更新时间"
                    >
                      <span>{this.state.updateTime}</span>
                    </FormItem>
                  </div> : null}
                  <FormItem className="half-middle">
                    <Button
                      className="set-submit"
                      type="primary"
                      htmlType="submit"
                      style={{ marginLeft: "150px" }}
                    >
                      保存
                    </Button>
                    <Button
                      className="set-submit"
                      type="ghost"
                      onClick={this.handleCancel}
                    >
                      取消
                    </Button>
                  </FormItem>
                </Spin>
              </Form>
            </Modal>
          </div>
        );
    }
}));

export default Addjurisdiction;