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

const { Option } = Select;

class DepartmentDeatils extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      info: {},
      EquData:[],
      hospData:[],
      locData:[]
    };
  }

  componentDidMount() {
    this.props.onAttRef(this)
    this.getMainType()
    this.getEquipment()
  }
  getHospData=(data)=>{
    this.setState({
      hospData:data
    })
  }
  //点击医院选项过滤开单科室
 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:[]
    })
  }
}
setHoLo=(hospID,locID)=>{
  this.props.form.setFieldsValue({hospID:hospID,locID:locID})
  this.getPublicLocSelect(hospID)
}
 //获取公共科室下拉框
 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 {

          }
      }
  })
}
    //获取设备表
    getEquipment = (values,e) => {
      // debugger
      let { page, pageSize, } = this.state;
      let data = {
        params: [{
          hospID:values && values.hospID || "",
          code: values && values.code || "",
          descripts: values && values.dec || "",
          status: values && values.status || "",
        }],
        pagination: [{
          pageSize: 999,
          currentPage: 1,
        }]
      }
      $http.post('urlS', this, {
        code: '04150008',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              search:e,
              EquData: res.result.Data,
            })
          }
        }
      })
    }
  getMainType = () => {
    let data = {}
    data = {
      params: [{
      }]
    }
    $http.post('urlS', this, {
      code: '05100259',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            mainTypeArr: res.result.Data
          })
        }
      }
    })
  }
  getInfo = (info) => {
    this.setState({
      info,
    })
  }
  clearInfo = () => {
    this.props.form.resetFields();
    this.setState({
      info: {},
      locData:[]
    })
  }
  saveAtt = () => {
    const { info, } = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let data = {
          params: [{
            locEquipmentID: info && info.locEquipmentID ? info.locEquipmentID : "",
            locID: values && values.locID || "",
            equipmentID: values && values.equipmentID || "",
            statusID: values && values.statusID || "",
            intervalTime: values && values.intervalTime || "",
            startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,
            endDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : undefined,
            workStartTime: values.workStartTime ? moment(values.workStartTime).format('HH:mm') : undefined,
            workStopTime: values.workStopTime ? moment(values.workStopTime).format('HH:mm') : undefined,
            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
          }]
        }
        $http.post('urlS', this, {
          code: '04150012',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              if (info && info.locEquipmentID) {
                message.success("更新成功")
                this.props.handleQuery()
              } else {
                message.success("添加成功")
                this.props.handleQuery()
              }

            }
          }
        })
      }
    })
  }
  del = (info) => {
    let data = {
      params: [{
        locEquipmentID: info && info.locEquipmentID ? info.locEquipmentID : "",
        updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
      }]
    }
    $http.post('urlS', this, {
      code: '04150013',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success("删除成功")
          this.props.handleQuery()
          this.clearInfo()
        }
      }
    })
  }

  render() {
    const { info, mainTypeArr,EquData,hospData,locData } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    }
    //科室设备
    let equOpt = []
    EquData && EquData.map(item => {
      equOpt.push(<Option key={item.equipmentID} value={String(item.equipmentID)}>{item.descripts}</Option>)
    })
     // 医院选择
     let hospOpt = [];
     hospData && hospData.map((item, index) => {
      hospOpt.push(<Option key={index} value={item.hospID}  onClick={(e,)=>this.handleHosp(e,item.hospID)} title={item.hospDesc} >{item.hospDesc}</Option>)
     });
     // 科室选择
     let locOpt = [];
     locData && locData.map((item, index) => {
      locOpt.push(<Option key={index} value={item.id} title={item.descripts} >{item.descripts}</Option>)
     });

    return (
      <div>
        <Form layout={'horizontal'}>
          <Row>
            <Col span={6}>
              <Form.Item label="设备" {...formLayout}>
                {getFieldDecorator('equipmentID', {
                  initialValue: info.equipmentID && info.equipmentID ? info.equipmentID : undefined,
                  rules: [{ required: true, message: '请选择设备' }]
                })(
                  <Select>
                      {equOpt}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='设备状态' {...formLayout}>
                {getFieldDecorator('statusID', {
                  initialValue: info.statusDr && info.statusDr ? info.statusDr : undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <Input ></Input>
                )}
              </Form.Item>
            </Col>
            <Col span={6} className="starDataDom">
              <Form.Item label='生效日期' {...formLayout}>
                {getFieldDecorator('startDate', {
                  initialValue: info && info.startDate ? moment(info.startDate, "YYYY-MM-DD") : moment(),
                  rules: [{ required: true, message: '请选择开始日期' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'开始日期'} disabledDate={(curDate) => {
                    return curDate && curDate > moment().endOf('day');
                  }} />
                )}
              </Form.Item>
            </Col>
            <Col span={6} >
              <Form.Item label='失效日期' {...formLayout}>
                {getFieldDecorator('stopDate', {
                  initialValue: info && info.stopDate ? moment(info.stopDate, "YYYY-MM-DD") : undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'请选择失效日期'} />
                )}
              </Form.Item>
            </Col >
          </Row>
          <Row>
          <Col span={6}>
                <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={6}>
                <Form.Item label='科室' {...formLayout}>
                  {getFieldDecorator('locID', {
                    rules: [{ required: true, message: '请选择科室' }],
                  })(
                    <Select allowClear style={{ width: '100%' }} placeholder="请先选择医院">
                      {locOpt}
                    </Select>
                  )}
                </Form.Item>
              </Col>
          <Col span={6}>
            <Form.Item label="工作开始时间" {...formLayout}>
                  {getFieldDecorator('workStartTime', {
                    initialValue: info.workStartTime ? moment(info.workStartTime, 'HH:mm') : undefined,
                  })(
                    <TimePicker
                      separator=":"
                      showToday
                      format={'HH:mm'}
                      style={{ width: '100%' }}
                      placeholder="请选择时间"
                    />
                  )}
                </Form.Item>
            </Col>
            <Col span={6}>
            <Form.Item label="工作结束时间" {...formLayout}>
                  {getFieldDecorator('workStopTime', {
                    initialValue: info.workStopTime ? moment(info.workStopTime, 'HH:mm') : undefined,
                  })(
                    <TimePicker
                      separator=":"
                      showToday
                      format={'HH:mm'}
                      style={{ width: '100%' }}
                      placeholder="请选择时间"
                    />
                  )}
                </Form.Item>
            </Col>
          </Row>
          <Row>
          <Col span={6}>
            <Form.Item label="耗时(分钟)" {...formLayout}>
                  {getFieldDecorator('intervalTime', {
                    initialValue: info.intervalTime || info.intervalTime==0 ?info.intervalTime: undefined,
                    getValueFromEvent: (event) => {
                      return event.target.value.replace(/\D/g, '')
                  },
                  })(
                   <Input></Input>
                  )}
                </Form.Item>
            </Col>
          </Row>
          <Row style={{ display: "flex", justifyContent: "space-between", justifyItems: "center", alignItems: "center", height: "48px" }}>
            <Button type="primary" onClick={this.saveAtt}>保存</Button>
            <Popconfirm title="是否要删除此事项" onConfirm={() => this.del(info)}>
              <Button disabled={info && !info.locEquipmentID} type="danger">删除</Button>
            </Popconfirm>
            <Button type="primary" onClick={this.clearInfo}>重置</Button>
          </Row>
        </Form>
      </div>
    )
  }
};
const DepartmentDeatil = Form.create()(DepartmentDeatils);
export default DepartmentDeatil;