// 公共库导入
import React from 'react';
import { Modal, Table, Input, message, Button, Form, Row, Col, Select } from 'antd';
import { $http } from '../../../containers/config/https';
import '../style/index.less'

let {Option} = Select;

class CommonLibraryImport extends React.Component {
	constructor(props) {
    super(props);
    this.state = {
      visible: false,
      tableData: [],
      rowData: [], // 选中行数据
      selectedRowKeys: [], // 选中的行数
      descripts: undefined, // 科室名称
      rowId: '', // 选中行id
      selectData: {},
      hospitalData: []
    };
    this.columns = [{
      key: 1,
      title: '科室代码',
      dataIndex: 'code',
      width: 200,
      align: 'left',
      }, {
      key: 2,
      title: '科室名称',
      dataIndex: 'descripts',
      align: 'left'
    }]
  }
	
	componentDidMount() {
    this.initData(); // 初始化下拉框数据
    this.props.onRef(this);
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state,callback)=>{ return; }
  }
  
  initData = () => {
    if(this.props.selectData.locType&&this.props.selectData.floor&&this.props.selectData.build) {
      if(this.props.selectData !== this.state.selectData) {
          this.setState({selectData: this.props.selectData})
      }
    } else {
        this.getSelectData();
    }
    if (this.props.hospitalData&&this.props.hospitalData.length > 0) {
        if (this.props.hospitalData !== this.state.hospitalData) {
            this.setState({hospitalData: this.props.hospitalData})
        }
    } else {
        this.loadHospitalMsg();
    }
  }

  // 获取下拉框数据
	getSelectData() {
		let data = {
			params: [
				{
					locTypeFlag: '1',
          buildFlag: '1',
          floorFlag: '1',
				}
			]
		}
		$http.post('urlS', this, {
			code: "01040009",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ selectData: res })
				} else {
					this.setState({ selectData: {} })
				}
			}
		})
	}

  //获取所属医院
	loadHospitalMsg() {
    let user = sessionStorage ? JSON.parse(sessionStorage.getItem('userData')) : {};
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: user&&user.groupID ? user.groupID : '', //登录角色id
				logonHospID: user&&user.hospID ? user.hospID : '', // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalData: res.depDoctor,
						// hospitalId: res.depDoctor ? res.depDoctor[0].id : undefined
					})
					var result = res.depDoctor && res.depDoctor.some(item => {
						if (item.id === user.hospID) {
								return true
						}
					})
					if (!result) {
						this.setState({
								hospitalId: undefined
						})
					} else {
						this.setState({hospitalId: user.hospID ? user.hospID : undefined})
						this.getDepartmentInformation(user.hospID)
					}
				}
			}
		});
	}

	// 打开弹框
  showModal = () => {
    this.setState({
      visible: true,
    }, () => {
      if (this.state.tableData.length < 1) {
        // 获取列表数据
        this.resetFields();
        this.setState({descripts: undefined}, () => {
          this.getCommonLibraryData();
        })
      }
    });
  }

	// 确定
  handleOk = (e) => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let arr = this.state.rowData ? this.state.rowData.map(item => {
          return {
            locCode: item.code,
            locDesc: item.descripts,
            updateUserID: user.userID, // 当前登陆人ID
            hospID: values.hospID,
            locTypeID: values.locTypeID,
            locFloorID: values.locFloorID,
            locBuildID: values.locBuildID,
          }
        }) : '';
        let data = {
          params: arr
        }
        $http.post('urlADS', this, {
          code: "01050001",
          data: data,
          success: function (res) { 
            if (+res.errorCode === 0) {
              // 成功提示
              message.success(res.errorMessage);
              // 关闭弹框
              this.handleCancel();
            }
          }
        })
      }
    })
  }

	// 关闭
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  }
  
  // 获取科室名称数据
  getDescriptsHandle = (e) => {
    this.setState({descripts: e.target.value})
  }

  // 获取公共科室列表数据
  getCommonLibraryData = () => {
    let data = {
      params: [{
        locDesc: this.state.descripts
      }]
    }
    $http.post('urlS', this, {
			code: "01050008",
			data: data,
			success: function (res) { 
        if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.data.length; i++) {
						res.result.data[i].key = res.result.data[i].id
					}
					this.setState({tableData: res.result.data, selectedRowKeys: [], rowData: [], record: ''})
				} else {
          this.setState({tableData: []})
        }
			}
		})
  }

  // 选择行数据
  onClickRow = (record) => {
    return {
      onClick: () => {
        let { selectedRowKeys, rowData } = this.state;
        let findFlag = false;
        let start = 0;
        if (selectedRowKeys) {
          selectedRowKeys.find(function (value, key) {
            if (value === record.id) {
              //遍历找到选中的数据，并记录下选中数据在数组中的key
              findFlag = true;
              start = key;
            }
          })
        }
        if (findFlag) {
          //再次点击移除选中
          selectedRowKeys.splice(start, 1);
          rowData.splice(start, 1);
        } else {
          //将点击的行添加到选中
          selectedRowKeys.push(record.id);
          rowData.push(record);
        }
        if (this.state.rowId === "") {
          this.setState({
            rowId: record.id,
            selectedRowKeys,
            rowData
          });
        } else {
          if (this.state.rowId !== record.id) {
              this.setState({
                rowId: record.id,
                selectedRowKeys,
                rowData
              });
          } else {
            this.setState({
                rowId: "",
                selectedRowKeys,
                rowData
            });
          }
        }
      }
    }
  }

  // 选中行class名
  setRowClassName = (record) => {
    return (("^" + this.state.selectedRowKeys.join("^") + "^").indexOf("^" + record.id + "^") > -1) ? 'clickRowStyle' : '';
  }

  // 重置表单
  resetFields = () => {
    this.props.form.resetFields(); //清空所有
    this.setState({rowData: [], selectedRowKeys: [], rowId: '', descripts: undefined});
  }

  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      selectedRows: this.state.rowData,
      onChange: (selectedRowKeys, selectedRows) => {
        // console.log(selectedRowKeys, selectedRows)
        let rowId= "";
        if (selectedRowKeys.length !== 0) {
          rowId=selectedRowKeys[selectedRowKeys.length-1];
        }
        this.setState({selectedRowKeys: selectedRowKeys, rowData: selectedRows, rowId: rowId})
      }
    };
    const { getFieldDecorator } = this.props.form;
    const formItemInput = {
      labelCol: {
        span: 8
      },
      wrapperCol: {
        span: 16
      },
    };
     // 所属医院
		let affiliatedHospitalOption = this.state.hospitalData && this.state.hospitalData.map((item, index) => {
			return (<Option value={+item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		// 科室类型
		let sectionTypeOption = this.state.selectData.locType && this.state.selectData.locType.map((item, index) => {
			return (<Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    // 科室楼层
    let departmentFloorOption = this.state.selectData.floor && this.state.selectData.floor.map((item, index) => {
			return (<Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    // 科室楼号
    let departmentBuildingOption = this.state.selectData.build && this.state.selectData.build.map((item, index) => {
			return (<Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return (
			<Modal
				title="导入科室"
				visible={this.state.visible}
				onOk={this.handleOk}
        onCancel={this.handleCancel}
        okText="导入"
        width={600}
			>
        <div style={{width: '100%', height: '500px'}}>
          <Form className="depart-form" style={{minHeight: '150px', maxHeight: '170px'}}>
						<Row>
							<Col span={12}>
								<Form.Item label="所属医院：" {...formItemInput}>
									{getFieldDecorator('hospID', {
											initialValue: undefined,
											rules: [{ required: true, message: '请选择所属医院' }]
									})(
										<Select showSearch optionFilterProp="seatchprop" placeholder="请选择">
										  {affiliatedHospitalOption}
                    </Select>
									)}
								</Form.Item>
							</Col>
              <Col span={12}>
								<Form.Item label="科室类型：" {...formItemInput}>
									{getFieldDecorator('locTypeID', {
											initialValue: undefined,
											rules: [{ required: true, message: '请选择科室类型' }]
									})(
										<Select showSearch optionFilterProp="seatchprop" placeholder="请选择">
											{sectionTypeOption}
										</Select>
									)}
								</Form.Item>
							</Col>
						</Row>
            <Row>
							<Col span={12}>
								<Form.Item label="科室楼层：" {...formItemInput}>
									{getFieldDecorator('locFloorID', {
											initialValue: undefined,
											rules: [{ required: true, message: '请选择科室楼号' }]
									})(
										<Select showSearch optionFilterProp="seatchprop" placeholder="请选择">
                      {departmentFloorOption}
										</Select>
									)}
								</Form.Item>
							</Col>
              <Col span={12}>
								<Form.Item label="科室楼号：" {...formItemInput}>
									{getFieldDecorator('locBuildID', {
											initialValue: undefined,
											rules: [{ required: true, message: '请选择科室楼号' }]
									})(
										<Select showSearch optionFilterProp="seatchprop" placeholder="请选择">
                      {departmentBuildingOption}
										</Select>
									)}
								</Form.Item>
							</Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="科室名称：" {...formItemInput}>
                  <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.getCommonLibraryData} value={this.state.descripts} onChange={this.getDescriptsHandle} />
								</Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item>
                  <Button onClick={this.getCommonLibraryData} style={{background: 'rgba(255,255,255,1)', marginLeft: '12px'}}>查询</Button>
                  {/* <Button onClick={this.resetFields} style={{marginLeft: '12px'}}>重置</Button> */}
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Table
            rowSelection={rowSelection}
            columns={this.columns}
            dataSource={this.state.tableData}
            pagination={false}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
            style={{overflow: 'auto', height: '350px'}}
            className="clearBackground"
          />
        </div>
			</Modal>
    );
  }
};
const CommonLibraryImportForm = Form.create()(CommonLibraryImport);
export default CommonLibraryImportForm;