/*
 * Creator:     ML
 * CreatDate:   2019-10-28
 * descripts：  科室设备维护表
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Table, Col, Card } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import CommonPagination from 'components/pagination';
import DepartmentDeatil from './DepartmentDeatil'


const { Option } = Select;

class Departmen extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      tableData: [], // 列表数据
      total: 0,
      page: 1,
      pageSize: 10,
      size: "small",
      search: "",
      hospData:[],
      locData:[]
    };
  }

  componentDidMount() {
    var x = document.querySelectorAll(".ant-table-body");
    for (var i = 0; i < x.length; i++) {
        x[i].style.height = store.getState().tableHeight.y  + 'px';
    }    if (this.state.size == "small") {
      this.setState({
        pageSize: 10
      })
    } else {
      this.setState({
        pageSize: 50
      })
    }
    this.getFindDate()
    this.getHospData()
  }
  //获取医院下拉数据框
 getHospData=()=>{
  let data = {
    params: [{
      hospID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID:"",
      logonGroupID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID:"",
      logonHospID:sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID:"",
    }],
  }
  $http.post('urlS', this, {
    code: '01040001',
    data: data,
    success: function (res) {
      if (+res.errorCode === 0) {
        this.setState({
         hospData:res.result
        })
        this.childAtt.getHospData(res.result)
      }
    }
  })
}
 //点击医院选项过滤开单科室
 handleHosp=(e,id)=>{
  this.props.form.setFieldsValue({locID:undefined})
  this.getPublicLocSelect(id)
}
//清除科室
clearLocData=(e,v)=>{
  if(!e&&!v){
    this.props.form.setFieldsValue({locID:undefined})
    this.setState({
      locData:[]
    })
  }
}
 //获取公共科室下拉框
 getPublicLocSelect = (hospID) => {
  let data = {}
  data = {
      params: [{
          hospID:hospID&&hospID?hospID:"",
      }],
  }
  $http.post('urlS', this, {
      code: '01050029',
      data: data,
      success: function (res) {
          if (+res.errorCode === 0 && res.result.Data) {
              let arr = res.result.Data && res.result.Data.map((item, index) => {
                  res.result.Data[index].key = Number(index)
              })
              this.setState({
                  locData: res.result.Data,
              })
          } else {

          }
      }
  })
}
  //调子组件
  onAttRef = (ref) => {
    this.childAtt = ref
  }
  // 点击查询
  handleQuery = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          values,
        }, () => {
          this.onShowSizeChange("1",this.state.pageSize)
        })
      }
    })
  }
  //查询
  getFindDate = (values,e) => {
    let { page, pageSize, } = this.state;
    let data = {
      params: [{
        locID: values && values.locID || "",
        status:values && values.status || "",
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: '04150011',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            search:e,
            tableData: res.result.Data,
            total: res.result.TotalCount,
          })
        }
      }
    })
  }
  // 修改page和pageSize 跳转至---
  onChange = (e) => {
    this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
      // 重新调用查询方法
      let { values } = this.state;
      this.getFindDate(values);
    })
  }
  //下拉选择页数
  onShowSizeChange = (page, pageSize) => {
    this.setState({ page: 1, pageSize: pageSize }, () => {
      // 重新调用查询方法
      let { values } = this.state;
      this.getFindDate(values, "search");
    })
  }
  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }

  //点击Row
  onClickRow = (record) => {
    return {
      onClick: () => {
        this.setState({
          parms: record,
        })
        this.childAtt.clearInfo()
        if (this.state.rowIds === "") {
          this.setState({
            rowIds: record.locEquipmentID,
          })
          this.childAtt.setHoLo(record.hospId,record.locID)
          this.childAtt.getInfo(record)
        } else {
          if (this.state.rowIds !== record.locEquipmentID) {
            this.setState({
              rowIds: record.locEquipmentID,
            });
            this.childAtt.setHoLo(record.hospId,record.locID)
            this.childAtt.getInfo(record)
          } else {
            this.setState({
              rowIds: "",
            });
            this.childAtt.clearInfo()
          }
        }
      },
    };
  }
  //点击查询后 表格行
  setRowClassNames = (record) => {
    return record.locEquipmentID === this.state.rowIds ? 'clickRowStyle' : '';
  }
  render() {
    const { tableData, total, page, rowData,hospData,locData } = this.state;

    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '科室设备',
        dataIndex: 'equipmentDesc',
        width: 80,
        align: "center",
        key: '0',
      }, {
        title: '工作开始时间',
        dataIndex: 'workStartTime',
        width: 50,
        align: "center",
        key: '3'
      }, {
        title: '工作结束时间',
        dataIndex: 'workStopTime',
        width: 50,
        align: "center",
        key: '4',
        render: (text, record, index) => {
          if (text == "") {
            return "--";
          } else{
            return text;
          }
        },
      }, {
        title: '耗时',
        dataIndex: 'intervalTime',
        width: 50,
        align: "center",
        key: '2'
      },{
        title: '设备状态',
        dataIndex: 'statusDr',
        width: 50,
        align: "center",
        key: '1',
      },{
        title: '可用状态',
        dataIndex: 'status',
        width: 20,
        align: "center",
        key: '1',
         render: (text, record, index) => {
          if (text == "Y") {
            return "生效";
          } else{
            return "失效";
          }
        },
      },]

    const formLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
    }
    const selectData = [
      {
        id: "",
        descripts: "全部"
      },
      {
        id: "Y",
        descripts: "可用"
      },
      {
        id: "N",
        descripts: "不可用"
      }
    ]
      // 状态选择
      let statusOpt = [];
      selectData && selectData.map((item, index) => {
        statusOpt.push(<Option key={index} value={item.id} title={item.descripts} >{item.descripts}</Option>)
      });
     // 医院选择
     let hospOpt = [];
     hospData && hospData.map((item, index) => {
      hospOpt.push(<Option key={index} value={item.id}  onClick={(e,)=>this.handleHosp(e,item.id)} title={item.descripts} >{item.descripts}</Option>)
     });
     // 科室选择
     let locOpt = [];
     locData && locData.map((item, index) => {
      locOpt.push(<Option key={index} value={item.id} title={item.descripts} >{item.descripts}</Option>)
     });
 
    return (
      <div>
        <div>
          <Form layout={'horizontal'}>
            <Row>
            <Col span={4}>
                <Form.Item label='医院' {...formLayout}>
                  {getFieldDecorator('hospID', {
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select allowClear style={{ width: '100%' }} placeholder="请选择" onChange={(e,v)=>this.clearLocData(e,v)}>
                      {hospOpt}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item label='科室' {...formLayout}>
                  {getFieldDecorator('locID', {
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select allowClear style={{ width: '100%' }} placeholder="请先选择医院">
                      {locOpt}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item label='状态' {...formLayout}>
                  {getFieldDecorator('status', {
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select allowClear style={{ width: '100%' }} placeholder="请选择">
                      {statusOpt}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={4}>
                <Button style={{ margin: '3px 0 0 10px' }} type="primary" onClick={this.handleQuery}>查询</Button>
              </Col>
            </Row>
          </Form>
        </div>
        <Row>
          <Col span={8}>
            <Card>
              <Table
                scroll={{x:1080}}
                columns={columns}
                dataSource={this.state.tableData}
                pagination={false}
                rowKey={record => record.key}
                onRow={this.onClickRow}
                rowClassName={this.setRowClassNames}
                bordered
                style={{ height: store.getState().tableHeight.y  + 'px',overflow:"auto"}}
              />
              <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                onChange={this.onChange.bind(this)} />

            </Card>
          </Col>
          <Col span={16} style={{marginLeft:"-1px"}}>
            <Card>
              <DepartmentDeatil  onAttRef={this.onAttRef} handleQuery={this.handleQuery}></DepartmentDeatil>
            </Card>
          </Col>
        </Row>

      </div>
    )
  }
};
const Department = Form.create()(Departmen);
export default Department;