import React from 'react';
import {
  Form, Row, Col, Select, Input, Button, message, Icon, Divider, Table
} from 'antd';
import { $http } from '../../../containers/config/https';
import DepartmentFindAdd from './DepartmentFindAdd.jsx'; // 添加的子组件
import DepartmentFindAddTabel from './DepartmentFindAddTabel.jsx';
import DepartmentFindModel from './DepartmentFindModel.jsx';
//import PublicModalTable from '../../common/PublicModalTable.jsx';

const { Option } = Select;

class DepartmentFind extends React.Component {
  constructor() {
    super();
    this.myRef1 = React.createRef();
    this.myRef2 = React.createRef();
    this.myRef3 = React.createRef();
    this.myRef4 = React.createRef();
    this.myRef5 = React.createRef();
    this.myRef6 = React.createRef();
    this.state = {
      options: {},
      bedNo: [],
      total: 0,
      data: [],
      page: 1,
      pageSize: 10,
      flag: false,
      roomTypeDr: "",
      locResDocDr: "",
      locResNurDr: "",
      locRoomDr: "",
      locBedDr: "",
      statusDr: "",
      rowData: {}, // 编辑保存的行数据
      record: "",
      docterPage: 1,
      docterPageSize: 10,
      doctorData: [],
      doctorTotal: 0,
      doctorRowData: {}, // 选中的行医生数据
      doctorValue: '', //
      docterTop: 0,
      docterLeft: 0,
    };
    this.columns = [
      {
        key: 1,
        title: '房间号',
        dataIndex: 'bedRoomDesc',
        align: "center",
        width: '13%'
      },
      {
        key: 2,
        title: '床位号',
        dataIndex: 'bedDesc',
        align: "center",
        width: '13%'
      },
      {
        key: 3,
        title: '房间类型',
        dataIndex: 'bedRoomTypeDesc',
        align: "center",
        width: '13%',
      },
      {
        key: 4,
        title: '责任医生',
        dataIndex: 'bedResDocDesc',
        align: "center",
        width: '13%',
      },
      {
        key: 5,
        title: '责任护士',
        dataIndex: 'bedResNurDesc',
        align: "center",
        width: '13%',

      },
      {
        key: 6,
        title: '固定费用',
        dataIndex: 'bedStableFee',
        align: "center",
        width: '13%',
        render: (text, record) => (
          record.bedStableFee.split(";").map(
            (item) => {
              return (
                <div>
                  {item}
                </div>
              )
            }
          )

        ),
      },
      {
        title: '操作',
        key: 7,
        align: "center",
        width: '13%',
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            {/* 分割线 */}
            {/* <Divider type="vertical" />
					<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
				  <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
				  </Popconfirm> */}
            <Divider type="vertical" />
            <span className='span' onClick={() => this.handleShowModel(text, record)}>固定费用</span>
          </span>
        ),
      }
    ];
    this.modalColumns = [
      {
        key: 1,
        title: 'code',
        dataIndex: 'code',
        align: "center",
      },
      {
        key: 2,
        title: '房间号',
        dataIndex: 'descripts',
        align: "center",
      }
    ];
  }
  handleShowModel = (text, record) => {
    this.setState({ record: record, visible_department: true })
  }

  // 下拉框选中事件
  handleOnSelect = (num, query, value) => {
    setTimeout(() => {
      this[`myRef${num + 1}`].current.focus();
    }, 300)
    this.setState({
      [query]: value
    })
  }
  // 下拉框选中事件
  handleOnChange = (num, query, e) => {
    setTimeout(() => {
      this[`myRef${num + 1}`].current.focus();
    }, 300)
    this.setState({
      [query]: e.target.value
    })
  }
  componentDidMount() {
    if (this.props.locID !== '') {
      // 初始化列表数据
      this.handleQuery()
    }
    // 组件加载完毕关闭loading
    this.setState({ showLoading: false })
    this.getOptions()
    this.getBedOptions()
  }
  //获取下拉框数据
  getOptions = () => {
    const data = [{
      locID: this.props.locID,
      roomTypeFlag: '1',
      resDoctorFlag: '1',
      resNurseFlag: '1',
      bedNoFlag: '1',
      statusFlag: '1',
      roomFlag: '1',
    }]
    $http.post('urlS', this, {
      code: "01040022",
      data: { params: data },
      success: function (res) {
        if (res.errorCode === '0') {
          this.setState({
            options: res,
            hbLocDesc: res.hbLocDesc,
            hospDesc: res.hospDesc

          })
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }
  getBedOptions = () => {
    const data = [{
      locDr: '',
      bedNoFlag: '1'
    }]
    $http.post('urlS', this, {
      code: "01040022",
      data: { params: data },
      success: function (res) {
        if (res.errorCode === '0') {
          this.setState({
            bedNo: res.bedNo
          })
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }


  // //获取房间列表数据
  // getDocterListData(values) {
  //   let { docterPage, docterPageSize } = this.state;
  //   let data = {
  //     params: [
  //       {
  //         input: values,
  //       }
  //     ],
  //     pagination: [
  //       {
  //         currentPage: docterPage,
  //         pageSize: docterPageSize
  //       }
  //     ]

  //   }
  //   $http.post('urlS', this, {
  //     code: "01040005",
  //     data: data,
  //     success: function (res) {
  //       if (+res.errorCode === 0) {
  //         for (var i = 0; i < res.Data.length; i++) {
  //           res.Data[i].key = i
  //         }
  //         this.setState({ doctorData: res.Data, doctorTotal: res.TotalCount })
  //       }
  //     }
  //   })
  // }


  // // 获取房间号信息信息
  // getDoctorData = (e) => {
  //   this.setState({
  //     docterTop: '304px',
  //     docterLeft: '557px',
  //     docterPage: 1,
  //     docterPageSize: 10,
  //     doctorValue: e.target.value
  //   }, () => {
  //     let { doctorValue } = this.state;
  //     this.getDocterListData(doctorValue);
  //   });
  //   this.child.showModal();
  // }

  // compileDoctorPage = (page, pageSize) => {
  //   this.setState({ docterPage: page, docterPageSize: pageSize }, () => {
  //     this.getDocterListData()
  //   })
  // }


  // // 房间号操作弹框
  // onClickRowDoctor = (record) => {
  //   return {
  //     onDoubleClick: () => {
  //       this.confirmSelectionDoctor(record);
  //     }
  //   }
  // }

  //   // 当房间号失去焦点后
  // 	onBlurDirector = (e) => {
  //     let descripts = this.state.doctorRowData && this.state.doctorRowData.descripts ? this.state.doctorRowData.descripts : (this.state.userInfo ? this.state.userInfo.roomDesc : '')
  //     if (e.target.value !== descripts) {
  //         this.props.form.setFieldsValue({locRoomNo: undefined});
  //     }
  // }

  // // 双击选中房间号行数据的回调
  // confirmSelectionDoctor = (record) => {
  //   this.setState({locRoomDr:record.id,doctorRowData: record }, () => {
  //     this.props.form.setFieldsValue({ locRoomNo: record.descripts })
  //     // 关闭弹窗
  //     this.child.handleCancel();
  //   })
  // }

  // // 删除
  // 		handleDelete = (record) => {
  // 			let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
  // 			let data = {
  // 				params: [{
  // 					ID: record.id,
  // 					UpdateUserDr: user.userId
  // 				}]
  // 			}
  // 			$http.post('urlADS', this, {
  // 				code: '01050022',
  // 				data: data,
  // 				success: function (res) {
  // 					if (+res.errorCode === 0) {
  // 						message.success('删除成功');
  // 						// 刷新列表数据
  // 						this.handleQuery();
  // 					} else {
  // 						message.error('删除失败：' + res.errorMessage);
  // 					}
  // 				},
  // 				error: function (error) {
  // 					message.error('删除失败：' + error);
  // 				}
  // 			})
  // 		}
  // 调用公共组件的连接事件
  onRef = (ref) => {
    this.child = ref
    //this.libraryChild = ref
  }
  // 调用子组件公共库导入的连接事件
  libraryOnRef = (ref) => {
    this.libraryChild = ref
  }
  // 点击公共库导入显示弹框
  handleLibraryImport = () => {
    this.setState({ flag: 'add', record: "" })
    this.libraryChild.showModal();
  }
  //查询
  handleQuery = () => {
    let { page, pageSize, roomTypeDr, locResDocDr, locResNurDr, locRoomDr, locBedDr, statusDr } = this.state;
    let data = {
      params: [{
        locID: this.props.locID,
        cbRoomTypeID: roomTypeDr,
        locResDocID: locResDocDr,
        locResNurID: locResNurDr,
        cbRoomID: locRoomDr,
        cbBedID: locBedDr,
        statusID: statusDr
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: "01050021",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }

  changePages = (page, pageSize) => {
    this.setState({ page: page, pageSize: pageSize }, () => {
      this.handleQuery();
    })
  }

  editerFun = () => {
    this.setState({
      flag: 'compile'
    })
  }

  handleCompile = record => {
    //console.log(record)
    this.setState({ record: record, flag: 'compile' }, () => {
      this.libraryChild.showModal();
    })
  }


  render() {
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: this.state.data,
      // 数据总条数
      total: this.state.total,
      page: this.state.page,
      // 表格的宽度
      x: 900
    }
    const { getFieldDecorator } = this.props.form;
    let userInfo = this.props.userInfo ? this.props.userInfo : {};
    const formItemInput = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 }
    };
    let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    // let handparam = {
    //   width: 540,
    //   top: this.state.docterTop,
    //   left: this.state.docterLeft,
    //   height: 400,
    //   columns: this.modalColumns,
    //   data: this.state.doctorData,
    //   isOnRow: true,
    //   showPagination: true,
    //   total: this.state.doctorTotal,
    //   page: this.state.docterPage
    // }
    return (
      <div className="dynamic-component">
        <Form
          className="ant-advanced-search-form dynamic-component-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={24} style={{ marginTop: '10px' }}>
            <Col span={8}>
              <Form.Item label="房间类型："  {...formItemInput}>
                {getFieldDecorator('cbRoomTypeID', {
                  // initialValue: userInfo.roomType ? userInfo.roomType : undefined,
                })(
                  <Select allowClear placeholder="请选择房间类型" ref={this.myRef1} onChange={this.handleOnSelect.bind(this, 1, 'roomTypeDr')}>
                    {this.state.options.roomType && this.state.options.roomType.map(item => {
                      return <Option value={item.id} key={item.id}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="责任医生："  {...formItemInput}>
                {getFieldDecorator('resDoc', {
                  // initialValue: userInfo.resDoctor ? userInfo.resDoctor : undefined,
                })(
                  <Select allowClear optionFilterProp="title" showSearch placeholder="请选择责任医生" ref={this.myRef2} onChange={this.handleOnSelect.bind(this, 2, 'locResDocDr')}>
                    {this.state.options.resDoc && this.state.options.resDoc.map(item => {
                      return <Option value={item.id} key={item.id} title={item.descripts + item.descriptsSPCode.toLowerCase()}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="责任护士："  {...formItemInput}>
                {getFieldDecorator('resNur', {
                  // initialValue: userInfo.resNur ? userInfo.resNur : undefined,
                })(
                  <Select allowClear optionFilterProp="title" showSearch placeholder="请选择责任护士" ref={this.myRef3} onChange={this.handleOnSelect.bind(this, 3, 'locResNurDr')}>
                    {this.state.options.resNur && this.state.options.resNur.map(item => {
                      return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="房间号"  {...formItemInput}>
                {getFieldDecorator('locRoomID', {
                  // initialValue: userInfo.roomDr ? userInfo.roomDr : undefined,
                  //  rules: [{ required: true, message: '请输入房间号' }],
                })(
                  <Select allowClear optionFilterProp="title" showSearch placeholder="请选择房间号" ref={this.myRef1} onChange={this.handleOnSelect.bind(this, 1, 'locRoomDr')} onSelect={this.handelDirectorDr}>
                    {this.state.options.roomNo && this.state.options.roomNo.map(item => {
                      return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
                {/* {getFieldDecorator('locRoomNo', {
                   initialValue: userInfo.roomDesc ? userInfo.roomDesc : undefined,
                })(
                  <Input placeholder="请输入描述" onPressEnter={this.getDoctorData} onBlur={this.onBlurDirector} />
                )} */}
              </Form.Item>

            </Col>
            <Col span={8}>
              <Form.Item label="床位号"  {...formItemInput}>
                {getFieldDecorator('locBedID', {
                  // initialValue: userInfo.locBedNo ? userInfo.locBedNo : undefined,
                })(
                  <Select allowClear optionFilterProp="title" showSearch placeholder="请输入床位号" ref={this.myRef5} onChange={this.handleOnSelect.bind(this, 4, 'locBedDr')}>
                    {this.state.bedNo && this.state.bedNo.map(item => {
                      return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="状态："  {...formItemInput}>
                {getFieldDecorator('bedStatusID', {
                  // initialValue: userInfo.status ? userInfo.status : undefined,
                })(
                  <Select placeholder="请选择状态" ref={this.myRef6} onChange={this.handleOnSelect.bind(this, 5, 'statusDr')}>
                    {this.state.options.status && this.state.options.status.map(item => {
                      return <Option value={item.id} key={item.id}>{item.descripts}</Option>
                    })}
                  </Select>
                )}
              </Form.Item>

            </Col>
          </Row>
          <Row style={{ paddingBottom: '12px' }}>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Button onClick={this.handleQuery} style={{ marginRight: '15px', background: 'rgba(255,255,255,1)', marginTop: '-10px' }}>查询</Button>
              <Button icon="plus" onClick={this.handleLibraryImport} style={{ background: 'rgba(247,128,93,1)', color: '#fff', marginRight: '40px', marginTop: '-10px' }}>新床位</Button>
            </Col>
          </Row>
        </Form>
        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <DepartmentFindAdd
          // selectData={{ ...this.props.selectData, ...this.state.options }}
          hbLocDesc={this.state.hbLocDesc}
          hospDesc={this.state.hospDesc}
          onRef={this.libraryOnRef}
          data={this.state.record}
          locID={this.props.locID}
          flag={this.state.flag}
          handleThis={this}
          hideModal={() => this.setState({ visible_edit: false })}
        />
        <DepartmentFindAddTabel
          getChildrenData={(value) => this.setState({ record: value })}
          // selectData={{ ...this.props.selectData, ...this.state.options }} 
          data={this.state.data}
          editerFun={this.editerFun}
          changePages={this.changePages}
          onRef={this.onRef}
          param={param}
          columns={this.columns}
        />

        <DepartmentFindModel
          locID={this.props.locID}
          visible={this.state.visible_department}
          record={this.state.record}
          medData={this.state.medData || {}}
          hideModal={() => this.setState({ visible_department: false })}
        />
        {/* <PublicModalTable
          onClickRowPublic={this.onClickRowDoctor}
          compilePage={this.compileDoctorPage}
          param={handparam} onRef={this.onRef}
        /> */}
      </div>
    );
  }
}

export default Form.create({ name: 'department_find' })(DepartmentFind);
