// 产程记录
import React from 'react';
import { Select, Row, Col, Button, DatePicker, TimePicker, Input, Divider, message, Table, Form, Popconfirm, Switch } from 'antd';
import { $http } from '../../../containers/config/https';
import store from 'store';
import PatientInfo from '../Patient/PatientInfo';
import moment from 'moment';
import { Util } from 'tools';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import fetchJsonp from 'fetch-jsonp';


const switchHash = {
  'Y': true,
  'N': false,
};
let initAdmID
const FormItem = Form.Item;
const { Option } = Select;
// 用户数据
let userData;
const BirthRecord = Form.create()(
  class BirthRecord extends React.Component {
    constructor(props) {
      super(props);
      let patientData = {};
      if (window.sessionStorage.patientData) {
        patientData = JSON.parse(window.sessionStorage.patientData);
      }
      initAdmID = patientData.admID ? patientData.admID : '';
      userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
      this.state = {
        admID: initAdmID,
        // contractionsStartDate: '',
        // contractionsStartTime: '',
        tableData: [], //列表
        birthrecord: {},
        index: '',
        columns: [],//列
        showLoading: true,//加载
        // 主菜单分页数据
        total: 0,
        page: 1,
        pageSize: 10,
        birthRecordID: '',
        tableWidth: "",
        ENObj: {},
        CNObj: {},
        expectedDate:""
	  };
	  this.refPulse = React.createRef();
	  this.refInducedMethod = React.createRef();
	  this.refFetalHeart = React.createRef();
	  this.refContractions = React.createRef();
	  this.refDiameterPipe = React.createRef();
	  this.refCervix = React.createRef();
	  this.refFetalMembrane = React.createRef();
	  this.refFetalOrientation = React.createRef();
	  this.refPresentation = React.createRef();
	  this.refAbnormalSituation = React.createRef();
	  this.refAnusVagina = React.createRef();
	  this.refHandle = React.createRef();
    }

    componentDidMount() {
      this.loadColumn();
     
      // 初始化设置table的高度以及表体的高度
      document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
      //this.setState({ showLoading: false });
     
    }
	changeFocus = (code) => {
		setTimeout(() => {
			this['ref' + code].current.focus();
		}, 300)
	}

       //查询列头数据
    loadColumn = () => {
        let data = {
            params: [{
                compontName: 'LaborHistoryRecord',
                type: "C",
                reactCode: ['LaborHistoryRecord'],
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                console.log(res);
                if (+res.errorCode === 0) {
                    var columns = []
                    columns = res.result.C
                    if (columns) {
                        for (var ci = 0; ci < columns.length; ci++) {
                            if (columns[ci].dataIndex == 'recordDate') {
                                var diagColumns = [];
                                    diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <DatePicker
                                            onClick={this.handleStopPropagation}
                                            format='YYYY-MM-DD'
                                            value={record.recordDate ? moment(record.recordDate, 'YYYY-MM-DD') : moment(moment().format("L"), 'YYYY-MM-DD')}
                                            onChange={(val, e) => this.handleSwitchChangeDay(e, 'recordDate', record)}
                                          />
                                        )
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'recordTime') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <TimePicker
                                            style={{ width: '100px' }}
                                            onClick={this.handleStopPropagation}
                                            format='HH:mm:ss'
                                            value={record.recordTime ? moment(record.recordTime, 'HH:mm:ss') : moment(new Date(), 'HH:mm:ss')}
                                            onChange={(val, e) => this.handleSwitchChangeTime(e, 'recordTime', record)}
                                          />
                                        )
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'bloodPressure') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record,index ) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
											onChange={e => this.handleFieldChange(e, 'bloodPressure', record)}
											onPressEnter={() => this.changeFocus('Pulse')}
                                          //onKeyPress={e => this.handleKeyPress(e, record.key)}
                                          // placeholder="代码"
                                          />);
                                      }
                                      return text;
                                    },
                                })
                                columns[ci] = diagColumns[0]
                            }

                            

                            if (columns[ci].dataIndex == 'pulse') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record, index) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
											onChange={e => this.handleFieldChange(e, 'pulse', record)}
											ref={this.refPulse}
											onPressEnter={() => this.changeFocus('InducedMethod')}
                                          // placeholder="代码"
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'inducedMethod') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'inducedMethod', record)}
											ref={this.refInducedMethod}
											onPressEnter={() => this.changeFocus('FetalHeart')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'fetalHeart') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'fetalHeart', record)}
											ref={this.refFetalHeart}
											onPressEnter={() => this.changeFocus('Contractions')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'contractions') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'contractions', record)}
											ref={this.refContractions}
											onPressEnter={() => this.changeFocus('DiameterPipe')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'diameterPipe') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'diameterPipe', record)}
											ref={this.refDiameterPipe}
											onPressEnter={() => this.changeFocus('Cervix')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'cervix') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'cervix', record)}
											ref={this.refCervix}
											onPressEnter={() => this.changeFocus('FetalMembrane')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'fetalMembrane') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width: columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                          
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'fetalMembrane', record)}
											ref={this.refFetalMembrane}
											onPressEnter={() => this.changeFocus('FetalOrientation')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'fetalOrientation') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    width:columns[ci].width,
                                    align: columns[ci].align,
                                    render: (text, record) => {
                                      if (record.editable) {
                                        return (
                                          <Input
                                            onClick={this.handleStopPropagation}
                                            value={text}
                                            autoFocus
                                            onChange={e => this.handleFieldChange(e, 'fetalOrientation', record)}
											ref={this.refFetalOrientation}
											onPressEnter={() => this.changeFocus('Presentation')}
                                          />);
                                      }
                                      return text;
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }


                            if (columns[ci].dataIndex == 'presentation') {
                              var diagColumns = [];
                              diagColumns.push({
                                  title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                  dataIndex: columns[ci].dataIndex,
                                  width: columns[ci].width,
                                  align: columns[ci].align,
                                  render: (text, record) => {
                                    if (record.editable) {
                                      return (
                                        <Input
                                          onClick={this.handleStopPropagation}
                                          value={text}
                                          autoFocus
                                          onChange={e => this.handleFieldChange(e, 'presentation', record)}
										  ref={this.refPresentation}
										  onPressEnter={() => this.changeFocus('AnusVagina')}
                                        />);
                                    }
                                    return text;
                                  }
                              })
                              columns[ci] = diagColumns[0]
                          }


                          
                          if (columns[ci].dataIndex == 'anusVagina') {
                            var diagColumns = [];
                            diagColumns.push({
                                title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                dataIndex: columns[ci].dataIndex,
                                width: columns[ci].width,
                                align: columns[ci].align,
                                render: (text, record) => {
                                  if (record.editable) {
                                    return (
                                      <Input
                                        onClick={this.handleStopPropagation}
                                        value={text}
                                        autoFocus
                                        onChange={e => this.handleFieldChange(e, 'anusVagina', record)}
										ref={this.refAnusVagina}
										onPressEnter={() => this.changeFocus('AbnormalSituation')}
                                      />);
                                  }
                                  return text;
                                }
                            })
                            columns[ci] = diagColumns[0]
                        }


                        
                        if (columns[ci].dataIndex == 'abnormalSituation') {
                          var diagColumns = [];
                          diagColumns.push({
                              title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                              dataIndex: columns[ci].dataIndex,
                              width: columns[ci].width,
                              align: columns[ci].align,
                              render: (text, record) => {
                                if (record.editable) {
                                  return (
                                    <Input
                                      onClick={this.handleStopPropagation}
                                      value={text}
                                      autoFocus
                                      onChange={e => this.handleFieldChange(e, 'abnormalSituation', record)}
									  ref={this.refAbnormalSituation}
									  onPressEnter={() => this.changeFocus('Handle')}
                                    />);
                                }
                                return text;
                              }
                          })
                          columns[ci] = diagColumns[0]
                      }

                      if (columns[ci].dataIndex == 'handle') {
                        var diagColumns = [];
                        diagColumns.push({
                            title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                            dataIndex: columns[ci].dataIndex,
                            width: columns[ci].width,
                            align: columns[ci].align,
                            render: (text, record) => {
                              if (record.editable) {
                                return (
                                  <Input
                                    onClick={this.handleStopPropagation}
                                    value={text}
                                    autoFocus
                                    onChange={e => this.handleFieldChange(e, 'handle', record)}
									ref={this.refHandle}
                                  />);
                              }
                              return text;
                            }
                        })
                        columns[ci] = diagColumns[0]
                    }

                    if (columns[ci].dataIndex == 'overflowMarker') {
                      var diagColumns = [];
                      diagColumns.push({
                          title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                          dataIndex: columns[ci].dataIndex,
                          width: columns[ci].width,
                          align: columns[ci].align,
                          render: (text, record, index) => {
                            if (record.editable) {
                              return (
                                <Switch
                                  onClick={this.handleStopPropagation}
                                  // defaultChecked={(record.overflowMarker == 'Y' || record.overflowMarker == 'N') ? false : true}
                                  defaultChecked={switchHash[text]}
                                  onChange={(val, e) => this.handleSwitchChange(val, e, 'overflowMarker', record)}
                                />
                              );
                            }
                            return text;
                          }
                      })
                      columns[ci] = diagColumns[0]
                  }

                  if (columns[ci].dataIndex == 'updateUser') {
                    var diagColumns = [];
                    diagColumns.push({
                        title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                        dataIndex: columns[ci].dataIndex,
                        width: columns[ci].width,
                        align: columns[ci].align,
                        render: (text, record) => {
                          if (record.editable) {
                            return (
                              <Input
                                onClick={this.handleStopPropagation}
                                value={text}
                                autoFocus
                                readOnly="ture"
                                disabled
                                onChange={e => this.handleFieldChange(e, 'userID', record)}
                                //onKeyPress={e => this.handleKeyPress(e, record.key)}
                                placeholder=""
                              />);
                          }
                          return text;
                        }
                    })
                    columns[ci] = diagColumns[0]
                }

                if (columns[ci].dataIndex == 'operation') {
                  var diagColumns = [];
                  diagColumns.push({
                      title: userData.language != 'EN' ? userData.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                      dataIndex: columns[ci].dataIndex,
                      width: columns[ci].width,
                      align: columns[ci].align,
                      render: (text, record) => {
                        const { loading } = this.state;
                        if (!!record.editable && loading) {
                          return null;
                        }
                        if (record.editable) {
                          // console.log("-------",record)
                          if (record.isNew) {
                            return (
                              <span>
                                <a onClick={(e) => this.saveRow(e, record)}>添加</a>
                                <Divider type="vertical" />
                                <a onClick={() => this.cut(record.key)}>删除</a>
                              </span>
                            )
                          }
                          if (record.birthRecordID) {
                            return (
                              <span>
                                <a onClick={(e) => this.saveRowUpdate(e, record)}>保存</a>
                                <Divider type="vertical" />
                                <a onClick={(e) => this.cancel(e, record)}>取消</a>
                              </span>
                            )
                          }
            
                        }
                        return (
                          <span>
                            <a onClick={(e) => this.toggleEditable(e, record)}>编辑</a>
                            <Divider type="vertical" />
                            <Popconfirm title="是否要删除此行" onConfirm={() => this.remove(record.birthRecordDetailID)}>
                              <a>删除</a>
                            </Popconfirm>
                          </span>
                        )
                      },
                  })
                  columns[ci] = diagColumns[0]
              }







                            

                            
                        }
                    }
                    this.setState({
                        columns: columns,
                        tableWidth: res.totalWidth,
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN,
                    }, () => {
                      this.handleQuery();
                    })
                }
            }
        })
    }



    componentWillUnmount() {
      // 组件销毁前将静止让setState修改state的状态
      this.setState = (state, callback) => { return; }
    }
    onColumnRef = (ref) => {
      this.columnRef = ref;
    }
    //查询
    handleQuery = () => {
      let patientData = {};
      if (sessionStorage.patientData) {
        patientData = JSON.parse(sessionStorage.patientData);
      }
      let data = {
        params: [{
          admID: patientData.admID ? patientData.admID : ''
        }],
      };
      $http.post('urlS', this, {
        code: '04110007',
        data: data,
        success: (res) => {
          if (res.errorCode === "0") {
            // console.log('%c tableData:', 'color:red', res.result.detail);
            this.setState({
              //total: res.result.TotalCount,
              tableData: res.result.detail,
              birthRecordID: res.result.id,
              gravida: res.result.gravida,
              deliveryTimes: res.result.deliveryTimes,
              expectedDate: res.result.expectedDate,
              placentalOverflowDate: res.result.placentalOverflowDate,
              placentalOverflowTime: res.result.placentalOverflowTime,
              contractionsStartDate: res.result.contractionsStartDate,
              contractionsStartTime: res.result.contractionsStartTime
            });
          } else {
            this.setState({
              // total: 0,
              tableData: []
            });

          }
        }
      });

    }
    //保存 
    handelSave = () => {
      const formData = this.props.form.getFieldsValue();
      this.props.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
      let data = {
        params: [{
          admID: initAdmID ? initAdmID : '',
          expectedDate: formData.expectedDate ? moment(formData.expectedDate).format('YYYY-MM-DD') : '',
          contractionsStartDate: formData.contractionsStartDate ? moment(formData.contractionsStartDate).format('YYYY-MM-DD') : '',
          contractionsStartTime: formData.contractionsStartTime ? moment(formData.contractionsStartTime).format('HH:mm:ss') : '',
          placentalOverflowDate: formData.placentalOverflowDate ? moment(formData.placentalOverflowDate).format('YYYY-MM-DD') : '',
          placentalOverflowTime: formData.placentalOverflowTime ? moment(formData.placentalOverflowTime).format('HH:mm:ss') : '',
          userID: userData.userID,
          childbirthRegGravida: formData.gravida,
          childbirthRegDeliveryTimes: formData.deliveryTimes,
          detail: this.state.tableData.length > 0 ? this.state.tableData : []
        }]
      }
      $http.post('urlS', this, {
        code: "04110006",
        data: data,
        success: (res) => {
          if (+res.errorCode === 0) {
            this.setState({
              tableData: []
            })
            message.success('保存成功');
            this.handleQuery();

          }
        }
      })
    }

    // 阻止默认事件
    handleStopPropagation = (e) => {
      if (typeof e == 'object') {
        e.stopPropagation();
      }
    }


    // 重置表单
    resetFields = () => {
      this.props.form.resetFields(); //清空所有

    }
    //新增 
    newAdd = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          const { tableData } = this.state;
          const newData = tableData.map((item) => ({ ...item }));
          newData.push({
            key: `NEW_TEMP_ID_${this.state.index}`,
            birthRecordID: this.state.birthRecordID,
            birthRecordDetailID: '',
            recordDate: moment().format('YYYY-MM-DD'),
            recordTime: moment().format('HH:mm:ss'),
            bloodPressure: '',
            pulse: '',
            inducedMethod: '',
            fetalHeart: '',
            contractions: '',
            diameterPipe: '',
            cervix: '',
            fetalMembrane: '',
            fetalOrientation: '',
            presentation: '',
            anusVagina: '',
            abnormalSituation: '',
            handle: '',
            overflowMarker: '',
            editableUpdate: true,
            editable: true,
            isNew: true,
            column:[]
          });
          this.setState({
            tableData: newData,
            index: this.state.index + 1,
          });
        } else {
          message.warning("请输入必填项")
        }
      });


    }
    //新增
    saveRow(e, key) {
      const formData = this.props.form.getFieldsValue();

      e.persist();
      const target = this.getRowByKey(key) || {};
      if (!target.medID || !target.conCreatType) {
        // message.error('请填写完整配置信息');
        e.target.focus();
        this.setState(
          { loading: false, }
        )
      }
      delete target.isNew;
      let obj = JSON.parse(JSON.stringify(target));
      let dataArr = [];
      dataArr.push(obj);
      this.setState({
        tableData: dataArr
      });
      let dataObj = {
        admID: initAdmID ? initAdmID : '',
        expectedDate: formData.expectedDate ? moment(formData.expectedDate).format('YYYY-MM-DD') : formData.expectedDate,
        contractionsStartDate: formData.contractionsStartDate ? moment(formData.contractionsStartDate).format('YYYY-MM-DD') : formData.contractionsStartDate,
        contractionsStartTime: formData.contractionsStartTime ? moment(formData.contractionsStartTime).format('HH:mm:ss') : formData.contractionsStartTime,
        placentalOverflowDate: formData.placentalOverflowDate ? moment(formData.placentalOverflowDate).format('YYYY-MM-DD') : '',
        placentalOverflowTime: formData.placentalOverflowTime ? moment(formData.placentalOverflowTime).format('HH:mm:ss') : '',
        userID: userData.userID,
        childbirthRegGravida: formData.gravida,
        childbirthRegDeliveryTimes: formData.deliveryTimes,
        detail: this.state.tableData
      }
      let postArr = [];
      postArr.push(dataObj);
      let data = {
        params: postArr
      };
      $http.post('urlADS', this, {
        code: '04110006',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            //  message.success('新增成功');
            this.handleQuery();
            this.handelSave();
          }
        }
      });
    }
    //更新
    saveRowUpdate = (e, key) => {
      e.persist();
      const target = this.getRowByKey(key) || {};
      if (!target.medID || !target.conCreatType) {
        e.target.focus();
        this.setState(
          { loading: false, }
        )
      }
      delete target.isNew;
      let obj = JSON.parse(JSON.stringify(target));
      let dataArr = [];
      dataArr.push(obj);
      this.setState({
        tableData: dataArr
      });
      let dataObj = {
        admID: initAdmID ? initAdmID : '',
        userID: userData.userID,
        detail: this.state.tableData
      }
      let postArr = [];
      postArr.push(dataObj);
      let data = {
        params: postArr
      };
      $http.post('urlADS', this, {
        code: '04110006',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success('更新成功');
            this.handleQuery();
          }
        }
      });
    }
    //文本框数据修改
    handleFieldChange(e, fieldName, record) {
      record[fieldName] = e.target.value;
      this.forceUpdate();
    }
    //开关
    handleSwitchChange = (val, e, el, record) => {
      this.handleStopPropagation(e)
      record[el] = val ? "Y" : "N";
      this.forceUpdate();
    }
    handleSwitchChangeDay(e, el, record) {
      // console.log('====record', record)
      // console.log('====e', e)
      this.handleStopPropagation(e)
      record[el] = e;
      this.forceUpdate();
    }
    handleSwitchChangeTime(e, el, record) {
      // console.log('====record', record);
      // console.log('====val', e.target.value)
      this.handleStopPropagation(e)
      record[el] = e;
      this.forceUpdate();

    }
    //获取操作行数据对象
    getRowByKey(key, newData) {
      const { tableData } = this.state;
      //console.log("newData---",tableData)
      return (newData || tableData).filter(item => item.key === key)[0];
    }
    //添加-删除
    cut(key) {
      const { tableData } = this.state;
      const { onChange } = this.props;
      const newData = tableData.filter(item => item.key !== key);
      this.setState({ tableData: newData });
      // onChange(newData);
    }
    //取消
    cancel(e, record) {
      e.preventDefault();
      record.editable = false;
      this.forceUpdate();
    }

    //编辑
    toggleEditable = (e, record) => {
    	e.preventDefault();
    	// this.setState({})
    	record.editable = !record.editable;
    	this.forceUpdate();
    }
    //删除
    remove(id) {

      // debugger
      if (id === "") {
        message.success('请选中删除行');
        return;
      }
      let tempObj = {};
      let removeArr = [];
      removeArr.push(id);
      tempObj.birthRecordDetails = removeArr;
      tempObj.userID = userData.userID;
      let obj = JSON.parse(JSON.stringify(tempObj));
      let data = {
        params: []
      };
      data.params.push(Util.disposeData(obj));
      $http.post('urlADS', this, {
        code: '04110009',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success('删除成功');
            this.handleQuery();
          }
        },
      });
    }
    //预览产程图
    preview = () => {
      if (this.state.admID == '') {
          message.warn("请先选择患者");
          return;
      }
      let dllInput = {};
      dllInput.exeName = "XYSTemperature.exe";
      dllInput.path = "C:\\ProgramData\\XYS\\XYSService\\plugins\\Temperature\\";
      let parameter = "";
      let sessionObj = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      Object.keys(sessionObj).forEach(function (key) {
          parameter = parameter + key + ":" + sessionObj[key] + ",";

      });
      parameter = parameter + "wardID:" + sessionObj.locID;
      parameter = parameter + "," + "admID:" + this.state.admID;
      parameter = parameter +"," + "flag:" + "birthChild";
      dllInput.parameter = parameter;

      let data = 'input={"inputDir":"Temperature/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' + JSON.stringify(dllInput) + '}'
      let that = this
      fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
          jsonpCallback: 'JsonCallback',
          timeout: 30000,
      })
          .then(function (response) {
              return response.json()
          }).then(function (json) {
          }).catch(function (ex) {
          })
    }
    onColumnRef = (ref) => {
      this.columnRef = ref;
    }

    render() {
      const tableHeight = store.getState().tableHeight.y - 90;
      const formItemInput = {
        labelCol: { span: 10 },
        wrapperCol: { span: 14 },
      };
      const formItemLayout = {    // label 和input宽度
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      };
      const { getFieldDecorator } = this.props.form;
      const birthrecord = this.state.birthrecord;
      return (
        <div style={{ width: '100%', height: '100%', overflow: 'hidden' }} >
          <div className="department-header">
            <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName="LaborHistoryRecord"
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.loadColumn}
              />
            <Row style={{ width: '100%', height: '36px', textAlign: 'left', lineHeight: '36px', borderBottom: '1px solid #cccccc' }}>
              <PatientInfo admID={this.state.admID} />
            </Row>
            <Form onSubmit={this.handelSave}>
              <Row style={{ padding: '24px 24px 0' }}>

                <Col span={18} className="top-form">
                  <Row>
                    <Col span={4}>
                      <Form.Item label="宫缩日期：" {...formItemInput}>
                        {getFieldDecorator('contractionsStartDate', {
                          initialValue: moment(moment().format(this.state.contractionsStartDate), 'YYYY-MM-DD'),
                          rules: [{ required: true, message: '请填写宫缩日期' }]
                        })(

                          <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                            return curDate && curDate > moment().endOf('day');
                          }} />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item label="宫缩时间：" {...formItemInput}>
                        {getFieldDecorator('contractionsStartTime', {
                          initialValue: this.state.contractionsStartTime ? moment(this.state.contractionsStartTime, 'HH:mm:ss') : moment(),
                          rules: [{ required: true, message: '请填写宫缩时间' }]
                        })(

                          <TimePicker style={{ width: '100%' }}></TimePicker>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item label="娩出日期：" {...formItemInput}>
                        {getFieldDecorator('placentalOverflowDate', {
                          initialValue: moment(moment().format(this.state.placentalOverflowDate), 'YYYY-MM-DD'),

                        })(

                          <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                            return curDate && curDate > moment().endOf('day');
                          }} />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item label="娩出时间：" {...formItemInput}>
                        {getFieldDecorator('placentalOverflowTime', {
                          initialValue: this.state.placentalOverflowTime ? moment(this.state.placentalOverflowTime, 'HH:mm:ss') : moment(),


                        })(

                          <TimePicker style={{ width: '100%' }}></TimePicker>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item label="预产期:" {...formItemInput}>
                        {getFieldDecorator('expectedDate', {
                          initialValue: this.state.expectedDate ? moment(this.state.expectedDate, 'YYYY-MM-DD') : null,
                          rules: [{ required: true, message: '请填写预产期' }]
                        })(

                          <DatePicker style={{ width: '100%' }}
                          />
                          //  disabledDate={(curDate) => {
                          //   return curDate && curDate > moment().endOf('day');
                          // }}
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={4}>
                      <Form.Item label="孕次：" {...formItemInput}>
                        {getFieldDecorator('gravida', {
                          initialValue: birthrecord.gravida ? birthrecord.gravida : this.state.gravida,
                        })(
                          <Input />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item label="产次：" {...formItemInput}>
                        {getFieldDecorator('deliveryTimes', {
                          initialValue: birthrecord.deliveryTimes ? birthrecord.deliveryTimes : this.state.deliveryTimes,
                        })(
                          <Input />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Col>
                <Col span={5} style={{ marginLeft: '-176px' }}>
                  <FormItem>
                    <Button
                      type="primary"
                      onClick={this.handelSave}
                    >保存
                    </Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <Button type="primary" onClick={this.preview}>预览</Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </div>

          <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
          <div style={{ padding: 24 ,widht: '100%'}}>
            <Button type="primary" onClick={this.newAdd}>插入行</Button>&nbsp;&nbsp;&nbsp;&nbsp;
              <Table
              style={{ marginTop: '10px', height: `${tableHeight}px`,width:'100%' }}
              dataSource={this.state.tableData}
              columns={this.state.columns}
              pagination={false}
              rowKey={(row) => {
                return row.birthRecordDetailID
              }}
              scroll={{y:'calc(100% - 60px)'}}
              onHeaderRow={column => {
                return {
                    onDoubleClick: () => {
                        this.columnRef.onOpenModel();
                    },
                };
             }}
              //onRow={this.onClickRow}
              rowClassName={record => (record.editable ? 'record' : '')}
              scroll={{ x: 1920, y: tableHeight }}
              loading={this.state.loading}
              bordered
            />

          </div>

        </div>

      )
    }
  }
)
export default BirthRecord;
