/*
 * Creator:     ML
 * CreatDate:   
 * descripts：诊断模板(诊断模板)
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Input, Table, Select, DatePicker, Button, Modal, message, Divider, Popconfirm, Tooltip, Icon, Card, Checkbox, Badge, Fragment, Pagination, Spin } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import PublicDataOrderAdjustment from 'pages/common/PublicDataOrderAdjustment';
import './css/OrderTemple.less';

const { TextArea } = Input;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />
const FormItem = Form.Item;
const Option = Select.Option;

const DiagnoseTemplate = Form.create()(
  class DiagnoseTemplate extends React.Component {
    cacheOriginData = {};
    constructor() {
      super()
      this.state = {
        leftData: [],//左边查询到的表格数据
        rightData: [],//右边双击后的表格数据
        rightUnitDr: [],
        findInfo: '请输入查询条件',//查询提示信息
        checked: true,//默认选择生效
        visible: false,//添加/修改诊断模板弹窗显示
        isMod: -1,//是否点击编辑
        ordTempletID: '',//编辑行id
        ordTempletDesc: '',//模板名称
        ordTempletAlias: '',//模板别名
        ordTempletCat: '',//医嘱分类
        rowId: '',//表格行id 设置颜色
        ordShow: false,//当前模板显示
        orderTemplType: [],//添加诊断模板类型选择
        baseTempType: [],//添加诊断模板类型选择
        selectedData: [],//医嘱明细选中
        selectedId: [],//医嘱明细选中
        tempChildDis: false,//左侧编辑 选择类型
        btnStatus: true,
        selectedRowKeys_right: [],//右侧勾选中行
        selectedRow_right: [],
        selectrow: '',//获取行 当前选中行
        deteleOrdId: '',//选中删除行
        leftDisRow: false,
        ordTempId: 1,//医嘱大类选择值
        isAdd: false,//是否点击添加
        ordDetailValue: '',//医嘱明细输入值
        ordDetailData: [],//医嘱项表格数据
        OrdDaShow: false,//医嘱项表格数据显隐
        OrdDaRowId: '',//医嘱项表格行id
        OrdCanType: '',//医嘱项允许录入类型
        ordTemPrice: 0,//医嘱项行单价
        editDis: true,//未选中
        total: 0,//医嘱项表格总数据
        page: 1,//页数
        pageSize: 10,//显示数
        nowRowID: '',//医嘱明细表格行id
        canSaveStatus: true,//能否保存
        initRored: {},//原始右侧表格行
        ordTempletDetailItemDesc: '',
        ordTempletDetailQty: '',
        ordTempletDetailQtyUnitDr: '',
        ordTempletDetailID: '',
        disAdd: false,//是否可新增
        baseUnit: [],
        searchLoading: false,//诊断明细搜索
      }
      this.diagInput = React.createRef();
      this.otherName = React.createRef();
      this.keyDownElements = this.keyDownAddMidical.bind(this)

      //左侧查询数据表
      this.columns = [{
        key: '1',
        align: 'center',
        title: '类型',
        dataIndex: 'templetTypeDesc',
        width: '100px',
      }, {
        key: '2',
        align: 'center',
        width: '200px',
        title: '名称',
        dataIndex: 'descripts',
      }, {
        align: 'center',
        width: '250px',
        title: '别名',
        dataIndex: 'alias',
        key: '3',
      }, {
        key: '4',
        align: 'center',
        width: '80px',
        title: '操作员',
        dataIndex: 'userName',
      }, {
        key: '5',
        align: 'center',
        width: '80px',
        title: '状态',
        dataIndex: 'locDesc',
        render: (text, row, index) => {
          if (row.activeFlag == 'Y') {
            text = '生效'
          } else {
            text = '失效'
          }
          return text
        }
      }, {
        key: '6',
        align: 'center',
        width: '120px',
        title: '操作',
        dataIndex: 'createdAt',
        fixed: 'right',
        render: (text, record) => (
          <span className="table-operation">
            <a onClick={() => this.editDocMes(record, '1')} style={{ border: '0', background: '0', boxShadow: '0 0 0', color: '#1890ff' }}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.editDocMes(record, "2")} >
              <a disabled={record.activeFlag == 'N'} style={{ border: '0', background: '0', boxShadow: '0 0 0', color: (record.activeFlag == 'N' ? 'rgba(0, 0, 0, 0.25)' : '#f5222d') }} >删除</a>
            </Popconfirm>
          </span>
        ),
      }];
    }

    componentDidMount = () => {
      // 初始化设置table的高度以及表体的高度
      if (document.querySelector('.ant-table-body')) {
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px'
      }
      this.handleQuery()
      //获取诊断模板类型下拉框数据
      let data = {}
      data = {
        params: [{
          ordTempletCatFlag: '1',
          orderTemplItemTypeFlag: '1',
          orderTemplTypeFlag: '1',
          unitFlag: '1'
        }],
      }
      $http.post('urlS', this, {
        code: '03050017',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            //   console.log('添加诊断模板',res)
            this.setState({
              orderTemplType: res.orderTemplType,
              baseTempType: res.orderTemplItemType,
            })
          }
        }
      })
      document.addEventListener('keydown', this.keyDownElements)
    }

    componentWillUnmount() {
      document.removeEventListener('keydown', this.keyDownElements)
      // 组件销毁前将静止让setState修改state的状态
    }

    keyDownAddMidical(e) {
      if (e && e.keyCode) {
        let currKey = 0;
        e = e || event || window.event;
        currKey = e.keyCode || e.which || e.charCode;
        //快捷键F1
        // if (currKey == 112 && (e.ctrlKey || e.metaKey || e.shiftKey)) {
        if (currKey == 112) {
          e.preventDefault();
          this.addOrd();
        }
      }
    }

    //回车查找诊断模板数据
    handleQuery = () => {
      // console.log('111111',this.props.form.getFieldValue('info'))
      let data = {}
      data = {
        params: [{
          locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : '',
          active: this.state.checked == true ? 'Y' : 'N',
          findDesc: this.props.form.getFieldValue('info'),
        }],
      }
      $http.post('urlS', this, {
        code: '03050035',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              leftData: res.result.templateList,
              findInfo: res.result && res.result.templateList.length == 0 ? '未查询到满足条件的病人信息，请核对信息' : ''
            })
          } else {

          }
        }
      })
    }

    //添加诊断模板弹出
    openDocMes = () => {
      this.props.form.setFieldsValue({ startTime: moment(), })
      this.props.form.setFieldsValue({ overTime: undefined, })
      this.setState({
        visible: true
      })
    }

    //点击是否生效
    changeChecked = (e) => {
      this.setState({
        checked: e.target.checked
      }, () => {
        this.handleQuery()
      })
    }

    //点击添加/修改遗嘱模板弹窗确认按钮
    handleOk = (e) => {
      this.props.form.validateFields((err, values) => {
        // console.log('点击确认',this.state.ordTempletID)
        if (!err) {
          let data = {}
          data = {
            params: [{
              userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : '',
              locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : '',
              id: this.state.isMod == 1 ? this.state.ordTempletID : '',
              desc: this.props.form.getFieldValue('docMesName'),
              templetTypeID: this.props.form.getFieldValue('docMesType'),
              alias: this.props.form.getFieldValue('othName'),
              note: this.props.form.getFieldValue('note'),
              activeDate: moment(this.props.form.getFieldValue('startTime')).format('YYYY-MM-DD') || '',
              invalidDate: this.props.form.getFieldValue('overTime') ? moment(this.props.form.getFieldValue('overTime')).format('YYYY-MM-DD') : '',
            }],
          }
          $http.post('urlS', this, {
            code: '03050034',
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                // console.log('新建',res)
                this.setState({
                  visible: false
                })
                if (this.state.isMod == 1) {
                  message.success('修改成功');
                  this.handleQuery()
                  this.setState({
                    rowId: this.state.ordTempletID,
                  });
                } else {
                  message.success('新建成功');
                  this.handleQuery()
                }
                this.initData()
              } else {

              }
            }
          })
        }
      })
    }

    //点击Row 左侧表格
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            ordTempletDesc: record.descripts,
            ordTempletAlias: record.alias,
            ordTempletCat: record.templetTypeDesc,
            ordShow: true,
            OrdCanType: record.templetTypeDesc,
            canSaveStatus: true,
            btnStatus: true,
            disAdd: false,
            selectedRowKeys_right: []
          })
          if (record.id) {
            if (this.state.rowId === '') {
              this.setState({
                rowId: record.id,
              });
            } else {
              if (this.state.rowId !== record.id) {
                this.setState({
                  rowId: record.id,
                });
              } else {
                this.setState({
                  rowId: '',
                  ordShow: false
                });
              }
            }
          }
          //获取诊断诊断明细
          let data = {}
          data = {
            params: [{
              templateID: record.id,
            }],
          }
          $http.post('urlS', this, {
            code: '03050071',
            data: data,
            success: function (res) {
              if (+res.errorCode === 0 && res.result) {
                res.result.map((item, i) => {
                  res.result[i].key = item.id
                  res.result[i].keys == Number(i)
                  this.setState({
                    rightUnitDr: item.id,
                    selectedRowKeys_right: []
                  })
                })
                this.setState({
                  rightData: res.result
                })

              }
            }
          })
        },
        onDoubleClick: () => {
          // console.log('获',record)
          if (record.id) {
            this.setState({
              rowId: record.id,
            })
          }

        }
      };
    }

    //设置点击row颜色 --左侧表格
    setRowClassName = (record) => {
      return record.id === this.state.rowId ? 'clickRowStyle' : '';
    }

    //点击右侧表格行
    onClickRightRow = (record) => {
      const { rightData } = this.state
      return {
        onClick: () => {
          this.setState({
            initRored: record
          })
          if (this.state.selectrow === '') {
            this.setState({
              selectrow: record.id,
            }, () => {
            });
          } else {
            if (this.state.selectrow !== record.id) {
              this.setState({
                // selectrow: record.ordTempletDetailID,
              }, () => {
              });
            } else {
              this.setState({
                selectrow: '',
              });
            }
          }
        },
      }
    }

    setRowClassNames = (record) => {
      return (('^' + this.state.selectedRowKeys_right.join('^') + '^').indexOf('^' + record.id + '^') > -1) ? 'clickRowStyle' : '';
      // return record.ordTempletDetailTemplItemTypeID === this.state.selectedRowKeys_right ? 'clickRowStyle' : '';
    }

    //编辑诊断模板
    editDocMes = (data, num) => {
      if (num == '1') {
        this.props.form.setFieldsValue({ docMesName: data.descripts });
        this.props.form.setFieldsValue({ othName: data.alias });
        this.props.form.setFieldsValue({ docMesType: String(data.templetTypeID) });
        this.props.form.setFieldsValue({ startTime: moment(data.startDate) });
        this.props.form.setFieldsValue({ overTime: data.stopDate ? moment(data.stopDate) : undefined });
        this.props.form.setFieldsValue({ note: data.note });
        this.setState({
          isMod: 1,
          visible: true,
          ordTempletID: data.id
        })
        if (!data.activeFlag == 'Y') {
          this.setState({
            tempChildDis: true
          })
        }
      } else {
        //删除诊断模板
        let datas = {}
        datas = {
          params: [{
            templetID: data.id,
          }],
        }
        $http.post('urlS', this, {
          code: '03050069',
          data: datas,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success('删除成功');
              this.setState({
                rowId: '',
                ordShow: false
              }, () => {
                this.handleQuery();
              })
            }
          }
        })
      }
    }

    //上移
    moveUp = () => {
      var keys = this.state.selectedRowKeys_right
      var data = this.state.rightData
      var newKeys = []
      keys = keys.sort(function (m, n) {
        if (m < n) return -1
        else if (m > n) return 1
        else return 0
      });
      for (var i = 0; i < keys.length; i++) {
        if (keys[i] === 0) {
          newKeys.push(keys[i])
          message.warn('已经到顶了，无法再移动！')
          return
        }
        var curRowData = data[keys[i]]
        var curRowKey = curRowData.key
        var upRowData = data[keys[i] - 1]
        var upRowKey = upRowData.key
        upRowData.key = curRowKey
        curRowData.key = upRowKey
        data[keys[i]] = upRowData
        data[keys[i] - 1] = curRowData
        newKeys.push(keys[i] - 1)
      }
      this.setState(
        {
          rightData: data,
          selectedRowKeys_right: newKeys
        }
      )
    }

    //下移
    moveDown = () => {
      var keys = this.state.selectedRowKeys_right
      var data = this.state.rightData
      var newKeys = []
      keys = keys.sort(function (m, n) {
        if (m < n) return -1
        else if (m > n) return 1
        else return 0
      });
      for (var i = keys.length - 1; i >= 0; i--) {
        if (keys[i] === data.length - 1) {
          newKeys.push(keys[i])
          message.warn('已经到底了，无法再移动！')
          return
        }
        var curRowData = data[keys[i]]
        var upRowData = data[keys[i] + 1]
        var curRowKey = curRowData.key
        var upRowKey = upRowData.key
        upRowData.key = curRowKey
        curRowData.key = upRowKey
        data[keys[i]] = upRowData
        data[keys[i] + 1] = curRowData
        newKeys.push(keys[i] + 1)
      }
      this.setState(
        {
          rightData: data,
          selectedRowKeys_right: newKeys
        }
      )
    }
    // //移动医嘱项
    // handleMove = status => {
    //   const that = this
    //   let { rightData, selectedRowKeys_right } = this.state;
    //   function _mapData(arr) {
    //     for (let index = 0, len = arr.length; index < len; index++) {
    //       const item = arr[index]
    //       if (selectedRowKeys_right.some(ele => ele === item.key)) {
    //         if (status === 'up') {
    //           arr = that.moveUp(arr, index)
    //         } else if (status === 'down') {
    //           arr = that.moveDown(arr, index)
    //           index += 1
    //         }
    //       }
    //       if (item.children && item.children.length > 0) {
    //         _mapData(item.children)
    //       }
    //     }
    //   }
    //   _mapData(rightData)
    //   this.setState({
    //     rightData
    //   })
    // }

    //获取诊断模板
    getOrdDeteil = () => {
      let data = {}
      data = {
        params: [{
          templateID: this.state.rowId,
        }],
      }
      $http.post('urlS', this, {
        code: '03050071',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            // console.log('获取诊断诊断明细信息',res)
            res.result.map((item, i) => {
              res.result[i].key = item.id
              res.result[i].keys == Number(i)
              this.setState({
                rightUnitDr: item.id,
                selectedRowKeys_right: []
              })
            })
            this.setState({
              rightData: res.result
            })
          }
        }
      })
    }

    //删除医嘱项模板
    handleDetele = () => {
      const { selectedRow_right } = this.state
      let arr = []
      if (selectedRow_right && selectedRow_right.length > 0) {
        selectedRow_right.map(item => {
          arr.push(item.id)
        })
        let data = {
          params: [{
            templetDetailIDs: arr
          }]
        }
        $http.post('urlS', this, {
          code: '03050070',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success('删除成功');
              this.setState({
                selectedRowKeys_right: [],
                btnStatus: true,
                canSaveStatus: true,
                disAdd: false,
                // ordShow:false,
              })
              //获取诊断诊断明细
              this.getOrdDeteil()
            }
          },
          error: function (error) {
            message.error('删除失败：' + error);
          }
        })
      }
    }

    openTemp = (data) => {
      this.setState({
        ordTempId: data
      })
      this.addOrd()
    }

    //新增医嘱项模板
    addOrd = () => {
      const { rightData, rowId } = this.state;
      const newData = {
        // ordTempletDetailTemplItemTypeCode:'01',
        templateID: rowId,
        id: '',
        diagID: '',
        descripts: '',
        ICDCode: '',
        CMark: '',
        ordTempletDetailID: '',
        key: rightData && rightData.length > 0 ? rightData.length + 1 : 1,
        // ordTempletDetailItemDesc:'',
        // ordTempletDetailQty:'',
        // ordTempletDetailQtyUnitDr:'',
        editable: true,
        isAdd: true,
      }
      // this.index += 1;
      this.setState({ ordTempletDetailID: '', ordDetailValue: '', isAdd: true, disAdd: false, ordTemPrice: 0, rightData: [...rightData, newData] }, () => {
        setTimeout(() => {
          this.diagInput.current.focus();
        }, 300)
        // console.log('rightData', this.state.rightData)
      });
    }

    //获取操作行数据对象
    getRowByKey(key, newData) {
      // debugger;
      // console.log('获取操作行数据对象',newData)
      const { rightData } = this.state;
      return (newData || rightData).filter(item => item.key === key)[0];
    }

    //文本框数据修改
    handleFieldChange = (e, fieldName, key) => {
      const { rightData } = this.state;
      const newData = rightData.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      // if(fieldName=='ordTempletDetailQtyUnitDr'){
      //   for (var i = 0; i < newData.length; i++) {
      //     if (newData[i].key === key) {
      //       newData[i].ordTempletDetailQtyUnitDr = e
      //     }
      //   }
      //   this.setState({
      //     rightData:newData,
      //     canSaveStatus:false,
      //   })
      //   return
      // }
      // console.log('newData=-----',newData)
      if (target) {
        target[fieldName] = e.target.value;
        this.setState({
          rightData: newData,
          canSaveStatus: false,
          ordDetailValue: e.target.value
        })

      }
    }

    //名称/规格信息明细 回车
    openNameDetail = (e, fieldName, key, data) => {
      // console.log(e, fieldName, key,data)
      const { ordTempId, ordDetailValue, page, pageSize, rightData } = this.state;
      if (!ordDetailValue) {
        message.warning('请输入检索名称')
        return
      }
      this.setState({
        searchLoading: true,
        // nowRowID: key
      })
      // debugger;

      const newData = rightData.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      let targetValue = ''
      if (target) {
        // debugger;
        targetValue = ordDetailValue;
      }
      if (ordDetailValue && ordDetailValue) {
        // debugger;
        //获取医嘱项信息
        let data = {}
        data = {
          params: [{
            hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
            desc: ordDetailValue ? ordDetailValue : targetValue,
          }],
          pagination: [{
            pageSize: pageSize,
            currentPage: page,
          }]
        }
        $http.post('urlS', this, {
          code: '03050031',
          data: data,
          success: function (res) {
            // debugger;
            if (+res.errorCode === 0 && res.result.data && res.result.data.length > 0) {
              for (var i = 0; i < res.result.data.length; i++) {
                res.result.data[i].key = i
              }
              this.setState({
                searchLoading: false,
                OrdDaShow: true,
                OrdDaRowId: res.result.data[0].id,
                ordDetailData: res.result.data,
                total: res.result.totalCount
              })
            } else {
              this.setState({
                searchLoading: false,
              })
            }
          }
        })
      }
    }

    //医嘱项明细 保存/修改
    handleSave = () => {
      //保存/修改医嘱项信息
      // console.log('医嘱', this.state.rightData)
      let data = {}
      const { rightData, rowId } = this.state
      for (var i = 0; i < rightData.length; i++) {
        if (rightData[i].diagID == '' && rightData[i].descripts == '') {
          message.warning('请回车检索诊断明细或者填写诊断注释')
          return
        }
      }
      data = {
        params: rightData,
      }
      $http.post('urlS', this, {
        code: '03050072',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              selectedRowKeys_right: [],
              btnStatus: true,
              canSaveStatus: true
            })
            message.success('保存成功')
            this.setState({
              selectedRowKeys_right: [],
              btnStatus: true,
              disAdd: false,
              canSaveStatus: true
            })
            this.getOrdDeteil()
          }
        }
      })
    }

    //点击医嘱项表行信息
    onClickOrdDaRow = (record) => {
      return {
        onClick: () => {
          if (this.state.OrdDaRowId === '') {
            this.setState({
              OrdDaRowId: record.id,
            });
          } else {
            if (this.state.OrdDaRowId !== record.id) {
              this.setState({
                OrdDaRowId: record.id,
              });
            } else {
              this.setState({
                OrdDaRowId: '',
              });
            }
          }
        },
        onDoubleClick: () => {
          this.checkNowData(record)
        }
      };
    }

    checkNowData = (record) => {
      const { rightData, nowRowID } = this.state
      // console.log('信息带回', record, 'rightData', rightData, 'nowRowID', nowRowID)
      this.setState({
        OrdDaRowId: record.id,
        // ordDetailValue:record.medDesc,
        isAdd: true,
        ordTempletDetailItemDesc: record.diagDesc
      })
      for (var i = 0; i < rightData.length; i++) {
        if (nowRowID == rightData[i].key) {
          // rightData[i].ordTempletDetailItemID =record.id;
          rightData[i].diagDesc = record.diagDesc
          rightData[i].diagID = record.id;
          rightData[i].ICDCode = record.ICDCode
          rightData[i].CMark = record.CMark;
          // rightData[i].ordTempletDetailQty 
          // rightData[i].ordTempletDetailQty =record.medDurQty?record.medDurQty:1;
          // rightData[i].ordTempletDetailQtyUnitDesc =record.medUnitDesc;
          // rightData[i].ordTempletDetailQtyUnitDr =record.medUnitID;
        }
      }
      this.setState({
        // ordTemPrice:record.medPrice,
        editDis: false,
        addInfo: true
      })
      this.handleTemDaCancel()
    }

    //详细信息页面上下移动
    handleOnKeydown = (e) => {
      var e = window.event || e;
      let id = '';
      const { ordDetailData } = this.state
      let oneArr = ordDetailData && ordDetailData.length > 0 ? ordDetailData : [];
      switch (e.keyCode) {
        case 13:
          e.preventDefault();
          if (this.state.OrdDaRowId) {
            this.setState({
              visible: false,
            })
            let obj = {}
            for (var i = 0; i < oneArr.length; i++) {
              if (oneArr[i].id === this.state.OrdDaRowId) {
                obj = i > 0 ? oneArr[i] : oneArr[0];
                break;
              }
            }
            // console.log('当前',obj)
            this.setState({
              visible: false,
              OrdDaRowId: obj.id,
            })
            this.checkNowData(obj)
            // this.confirmSelection(obj);
          } else {
            message.info('请选择一条需要操作的数据')
          }
          break;
        case 38: //上
          if (this.state.OrdDaRowId) {
            for (var i = 0; i < oneArr.length; i++) {
              if (oneArr[i].id === this.state.OrdDaRowId) {
                id = i > 0 ? oneArr[i - 1].id : oneArr[0].id;
                break;
              }
            }
            this.setState({ OrdDaRowId: id })
          } else {
            this.setState({ OrdDaRowId: oneArr[0].id })
          }
          break;
        case 40: //下
          if (this.state.OrdDaRowId) {
            for (let i = 0; i < oneArr.length; i++) {
              oneArr[i].disblock = false
              if (oneArr[i].id === this.state.OrdDaRowId) {
                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].id : oneArr[i + 1].id;
                break;
              }
            }
            this.setState({ OrdDaRowId: id })
          } else {
            this.setState({ OrdDaRowId: oneArr[0].id })
          }
          break;
      }
    }

    //设置医嘱项表row颜色
    setOrdDaRowClassName = (record) => {
      return record.id === this.state.OrdDaRowId ? 'clickRowStyle' : '';
    }

    //检测药品名称--失去焦点
    initRord = (e, record) => {
      const { rightData } = this.state
      // console.log('record',record,'this.state.rightData',this.state.rightData,'this.state.ordTempletDetailItemDesc',this.state.ordTempletDetailItemDesc)
      if (e.target.value != this.state.ordTempletDetailItemDesc) {
        rightData.map((item, index) => {
          if (record.id && record.id && record.id == rightData[index].id) {
            rightData[index].diagDesc = this.state.ordTempletDetailItemDesc
          }
        })
      }
    }

    //检测药品名称--进入
    focusRord = (e, record) => {
      // console.log('进入',record,' e.target.value', e.target.value)
      this.setState({
        ordTempletDetailItemDesc: e.target.value,
        ordDetailValue: e.target.value,
        nowRow: record.key,
        nowRowID: record.key,
      }, () => {
        // console.log('检测药品名称--进入nowRow',this.state.nowRow,record)
      })
    }

    //编辑 医嘱项表格行
    toggleEditable = (e, key, record) => {
      // console.log('geren--key', key, record)
      e.preventDefault();
      this.setState({
        ordTempletDetailItemDesc: record.diagDesc,
        // ordTempletDetailQty:record.ordTempletDetailQty,
        // ordTempletDetailQtyUnitDr:record.ordTempletDetailQtyUnitDr,
        ordTempletDetailID: record.id,
        // disAdd:true,
      })
      const { rightData } = this.state;
      const newData = rightData.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      if (target) {
        if (!target.editable) {
          this.cacheOriginData[key] = { ...target };
        }
        target.editable = !target.editable;
        this.setState({
          rightData: newData,
          // canSaveStatus:false,
        })
      }
      setTimeout(() => {
        this.diagInput.current.focus();
      }, 300)
    }

    //取消 医嘱项表格行
    cancel = (e, key) => {
      this.clickedCancel = true;
      e.preventDefault();
      const { rightData } = this.state;
      const newData = rightData.map((item) => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      if (this.cacheOriginData[key]) {
        Object.assign(target, this.cacheOriginData[key]);
        delete this.cacheOriginData[key];
      }
      target.editable = false;
      this.setState({ rightData: newData, canSaveStatus: true, disAdd: false, });
      this.ClickedCancel = false;
    }

    //删除 医嘱项表格行
    cut = (e, key) => {
      // e.stopPropagation();
      // e.nativeEvent.stopImmediatePropagation();
      // e.preventDefault();
      const { rightData } = this.state;
      // const { onChange } = this.props;
      const newData = rightData.filter(item => item.key !== key);
      let bs = false
      newData.map((item, i) => {
        if (item.seqNo && item.editable && item.editable == true) {
          bs = true
          this.setState({
            canSaveStatus: false,
            disAdd: false,
            rightData: newData,
          })
          return
        }
      })
      if (!bs) {
        this.setState({ rightData: newData, disAdd: false, canSaveStatus: true, });
      }
      // onChange(newData);
    }

    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }

    // 修改page和pageSize 跳转至---
    onChange = (page, pageSize) => {
      this.setState({ page: page, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.openNameDetail();
      })
    }

    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.openNameDetail();
      })
    }

    handleTemDaCancel = () => {
      this.setState({
        OrdDaShow: false,
        page: 1,
        pageSize: 10
      })
    }

    //初始化信息
    initData = () => {
      this.setState({
        isMod: -1,
        ordShow: false,
        tempChildDis: false,
        rowId: ''
      })
      this.props.form.setFieldsValue({ docMesName: undefined });
      this.props.form.setFieldsValue({ note: undefined });
      this.props.form.setFieldsValue({ othName: undefined });
      this.props.form.setFieldsValue({ docMesType: '1' });
    }

    //点击添加/修改遗嘱模板弹窗取消按钮
    handleCancel = () => {
      this.setState({
        visible: false
      })
      this.initData()
    }

    //输入名车回车、失焦自动生成别名
    getOtherName = () => {
      let data = {}
      data = {
        params: [{
          descripts: this.props.form.getFieldValue('docMesName') || '',
        }]
      }
      $http.post('urlS', this, {
        code: '01040117',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.props.form.setFieldsValue({ othName: this.props.form.getFieldValue('docMesName') + '_' + res.result })
            setTimeout(() => {
              this.otherName.current.focus();
            }, 300)
          }
        }
      })
    }

    // 排序
    handleSort = () => {
      const { leftData } = this.state;
      let columns = this.columns.slice(1, this.columns.length - 1);
      this.sortRef && this.sortRef.modifyVisible(true, {
        tableData: leftData,
        columns,
        totalWidth: 510,
        saveCode: '03020074',
        recordIdIndex: 'id',
        modalTitle: '诊断模板排序', // 弹窗title
        interfaceParams: {
          type: 'DM', // 医嘱套餐（西药及其他） 【 X-西药及其他 Z-中草药 M-医嘱模板 DM-诊断模板 】
        }
      })
    }

    render() {
      const { getFieldDecorator, baseUnit } = this.props.form;
      let { ordTempletDesc, ordTempletAlias, ordTempletCat, ordShow, orderTemplType, baseTempType, tempChildDis, OrdDaShow, searchLoading } = this.state
      let ordtype = []
      orderTemplType && orderTemplType.map(item => {
        ordtype.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
      })
      let ordTemp = []
      baseTempType && baseTempType.map(item => {
        ordTemp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
      })
      let ordUnit = []
      baseUnit && baseUnit.map(item => {
        ordUnit.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
      })

      //右侧医嘱明细表
      const rightColumns = [{
        align: 'center',
        title: '诊断编码',
        dataIndex: 'diagCode',
        key: 'diagCode',
        // render: (text, record, index) => {
        //   if(text=='Y'){
        //     return '西医'
        //     }else{
        //       return '中医'
        //     }
        // },
      }, {
        align: 'center',
        title: '诊断类型',
        dataIndex: 'CMark',
        key: 'CMark',
        render: (text, record, index) => {
          if (text == 'Y') {
            return '中医'
          } else if (text == 'N') {
            return '西医'
          }
        },
      }, {
        align: 'center',
        title: '诊断明细',
        dataIndex: 'diagDesc',
        key: 'diagDesc',
        editable: true,
        render: (text, record, index) => {
          const { isAdd } = this.state
          if (record.editable) {
            <FormItem >
              {getFieldDecorator('name', {
                initialValue: { text },
                rules: [{ required: false, message: '' }],
              })(
                <span style={{ textAlign: 'center', border: '0', width: '100%', display: 'inline-block' }} />
              )}
            </FormItem>
            return (
              <Spin spinning={this.state.nowRow == record.key && searchLoading ? true : false} indicator={antIcon}>
                <Input
                  ref={this.diagInput}
                  placeholder="回车检索 输入名称"
                  style={{ textAlign: "center", width: "100%" }}
                  onBlur={(e) => this.initRord(e, record)}
                  onFocus={(e) => this.focusRord(e, record)}
                  onPressEnter={(e) => this.openNameDetail(e, 'diagDesc', record.key, record)}
                  value={text}
                  loading={true}
                  onChange={(e) => this.handleFieldChange(e, 'diagDesc', record.key)} />
              </Spin>
            )
          } if (!record.editable) {
            return (
              <Input placeholder="回车检索 输入名称" style={{ textAlign: "center", border: "0" }}
                readOnly
                value={text} />
            )
          }
          return text;
        },
      }, {
        width: 200,
        align: "center",
        title: '诊断注释',
        dataIndex: 'descripts',
        key: 'descripts',
        editable: true,
        render: (text, record, index) => {
          if (record.editable) {
            return (
              <TextArea maxLength={100} style={{ height: "68px", resize: "none" }} placeholder="字数限制100" value={text} onChange={(e) => this.handleFieldChange(e, 'descripts', record.key)} />
              // <Input style={{textAlign:"center"}}
              // value={text} type="number" min="1" onChange={(e) => this.handleFieldChange(e, 'ordTempletDetailQty',record.key)}/>
            )
          } if (!record.editable) {
            return (
              // <Input style={{textAlign:"center"}}
              // value={text} readOnly type="number" min="1" />
              <TextArea readOnly style={{ height: "32px", resize: "none" }} maxLength={100} placeholder="字数限制100" value={text} />
            )
          }
          return text;
        },
      }, {
        title: '操作',
        dataIndex: 'operation',
        key: 'action',
        align: "center",
        key: 'ordTempletEdit',
        width: 200,
        render: (text, record, index) => {
          if (record.isAdd) {
            return (
              <span style={{ textAlign: "center" }}>
                <a style={{ color: "red" }} onClick={(e) => this.cut(e, record.key)}>删除</a>
              </span>
            )
          }
          if (!record.editable) {
            return (
              <span style={{ textAlign: "center" }}>
                <a onClick={(e) => this.toggleEditable(e, record.key, record)}>编辑</a>
              </span>
            )
          } else {
            return (
              <span style={{ textAlign: "center" }}>
                <a onClick={(e) => this.cancel(e, record.key)}>取消</a>
              </span>
            )
          }
        }
      }];

      //右侧查询医嘱项明细表
      const OrdDaColumns = [
        {
          align: "center",
          title: '编码',
          dataIndex: 'diagCode',
          key: '1'
        },
        {
          align: "center",
          title: '名称*规格',
          dataIndex: 'diagDesc',
          key: '2'
        },
        // { 
        //   align: "center",
        //   title: '大类',
        //    dataIndex: 'medCatDesc', 
        //    key: '3'
        // },
        // { 
        //   align: "center",
        //   title: '子类',
        //   dataIndex: 'medSubCatDesc',
        //   key: '4'
        // },
        // { 
        //   align: "center",
        //   title: '供应商',
        //   dataIndex: '',
        //   key: '5' 
        // },
        // { 
        //   align: "center",
        //   title: '产地', 
        //   dataIndex: '', 
        //   key: '6',
        //  },
      ];
      const rowSelection_right = {
        selectedRowKeys: this.state.selectedRowKeys_right,
        onChange: (selectedRowKeys, selectedRows) => {
          let btnStatus = false;
          let canSaveStatus = false;
          let selectrow = '';
          if (selectedRowKeys.length === 0) {
            btnStatus = true;
            canSaveStatus = true;
          } else {
            selectrow = selectedRowKeys[selectedRowKeys.length - 1];
          }
          this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          if (selectedRows.length > 0) {
            this.setState({
              btnStatus: false,
              canSaveStatus: false,
            })
          } else {
            this.setState({
              btnStatus: true,
              canSaveStatus: true,
            })
          }
          this.setState({ selectedRow_right: selectedRows });
        }
      };
      return (
        <div>
          <Row gutter={60} className="diagDom orderTempletDom">
            <Col span={8} style={{ padding: "0" }}>
              <Card
                title="诊断模板列表"
                style={{ marginRight: "4px" }}
                className="moreInfoCard"
              >
                <Row>
                  <Col span={13} style={{ marginRight: '10px' }}>
                    <FormItem>
                      {getFieldDecorator('info', {
                        initialValue: undefined,
                      })(
                        <Input allowClear placeholder='输入模板或套餐名称/别名回车查询' onPressEnter={this.handleQuery} autoFocus />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={4}>
                    <FormItem >
                      {getFieldDecorator('checkInp', {
                        initialValue: undefined,
                        rules: [{ required: false, message: '' }],
                      })(
                        <Button style={{ background: 'rgba(66,185,131,1)', color: '#fff', }} onClick={this.openDocMes}>+诊断模板</Button>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={5}>
                    <FormItem>
                      {getFieldDecorator('sort', {
                        initialValue: undefined,
                        rules: [{ required: false, message: '' }],
                      })(
                        <Button ghost type="primary" style={{ marginLeft: '12px' }} onClick={this.handleSort}>设置个人排序</Button>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row style={{ marginBottom: '6px' }}>
                  <Checkbox checked={this.state.checked} onChange={this.changeChecked}>仅显示生效</Checkbox>
                </Row>
                <Row className="table-body-height">
                  <Table
                    bordered
                    expandRowByClick
                    className="components-table-demo-nested"
                    columns={this.columns}
                    pagination={false}
                    scroll={{ x: 610, y: store.getState().tableHeight.y + 46 }}
                    rowClassName={this.setRowClassName}
                    onRow={this.onClickRow}
                    rowKey={record => record.key}
                    locale={{ emptyText: this.state.findInfo }}
                    // expandedRowRender={expandedRowRender}
                    dataSource={this.state.leftData}
                  />
                </Row>
                <div
                  tabIndex={1}
                  onKeyDown={this.handleOnKeydown}
                  style={{ outline: 'none' }}
                  className="ordTempDateil"
                >
                  <Modal
                    key="3"
                    width="800px"
                    visible={OrdDaShow}
                    closable={false}
                    title={false}
                    centered={true}
                    pagination={false}
                    footer={null}
                    onCancel={this.handleTemDaCancel}>
                    <Table
                      columns={OrdDaColumns}
                      pagination={false}
                      rowClassName={this.setOrdDaRowClassName}
                      onRow={this.onClickOrdDaRow}
                      rowKey={record => record.key}
                      // expandedRowRender={expandedRowRender}
                      dataSource={this.state.ordDetailData}
                      style={{
                        height: '500px',
                        overflow: 'auto'
                      }}
                    />
                    <div style={{ position: "absolute", bottom: "8px" }}>
                      <p>当前允许录入类型:{this.state.OrdCanType}</p>
                    </div>
                    <Pagination
                      showTotal={() => this.showTotal(this.state.total)}
                      size="small"
                      showQuickJumper
                      showSizeChanger
                      defaultCurrent={1}
                      current={this.state.page ? this.state.page : 1}
                      total={this.state.total ? this.state.total : 0}
                      onChange={this.onChange}
                      onShowSizeChange={this.onShowSizeChange}
                      style={{ textAlign: "right", marginTop: '13px' }}
                    />
                  </Modal>
                </div>

              </Card>
            </Col>
            <Col span={16} style={{ padding: "0" }}>
              <Card
                title="诊断模板及明细项维护"
                className="moreInfoCard topDom"
              >
                <div style={{ display: (ordShow ? "none" : "block"), height: "48px", lineHeight: "48px", marginLeft: "20px" }}>
                  <p>暂无明细项，请先添加模板</p>
                </div>
                <div style={{ display: (ordShow ? "block" : "none") }}>
                  <Row style={{ background: "#cae3f7", }} >
                    <div style={{ marginBottom: "0", display: (ordShow ? "block" : "none") }}>
                      <span style={{ display: "inline-block", height: "38px", lineHeight: "38px", paddingLeft: "20px" }}>当前模板：{ordTempletDesc}({ordTempletAlias})<Divider style={{ background: "#9e9a9a" }} type="vertical" />{ordTempletCat}</span>
                    </div>
                  </Row>
                  <Row style={{ margin: "12px 0" }} className="editSpan">
                    {/* <span  onClick={this.addOrd}><Icon type="plus-circle" />新增</span> */}
                    {/* <Select placeholder="新增" className="addSelect" onSelect={this.openTemp}>
                                {ordTemp}
                            </Select> */}
                    {/* </span> */}
                    {/* <span onClick={this.handleDetele}><Icon type="delete" /> */}
                    {/* </span> */}
                    {/* <span style={{color:(this.state.btnStatus !== 'active'?"green":"red")}} onClick={this.handleMove.bind(this, 'up')}><Icon type="up-circle" />上移</span>
                            <span onClick={this.handleMove.bind(this, 'down')}><Icon type="down-circle" />下移</span>
                            <span onClick={this.handleSave}><Icon type="printer" />保存</span> */}
                    <Button disabled={this.state.disAdd} onClick={this.addOrd} size="small" type="primary" style={{ marginRight: '10px' }}><Icon type="plus-circle" />新增（F1）</Button>
                    <Button onClick={this.handleDetele} disabled={this.state.btnStatus} size="small" type="danger" style={{ marginRight: '10px' }}><Icon type="delete" />删除</Button>
                    <Button disabled={this.state.btnStatus} size="small" type="dashed" onClick={this.moveUp} style={{ marginRight: '10px' }}><Icon type="up-circle" />上移</Button>
                    <Button disabled={this.state.btnStatus} size="small" type="dashed" onClick={this.moveDown} style={{ marginRight: '10px' }}><Icon type="down-circle" />下移</Button>
                    <Button disabled={this.state.canSaveStatus} onClick={this.handleSave} size="small" type="primary" style={{ marginRight: '10px' }}><Icon type="printer" />保存</Button>
                  </Row>
                  <Row className="table-body-height">
                    <Table
                      bordered
                      columns={rightColumns}
                      pagination={false}
                      rowClassName={this.setRowClassNames}
                      onRow={this.onClickRightRow}
                      // expandedRowRender={expandedRowRender}
                      dataSource={this.state.rightData}
                      rowKey={record => record.keys}
                      rowSelection={rowSelection_right}
                      className="clearBackground"
                      scroll={{ x: 1000, y: store.getState().tableHeight.y + 44 }}
                    />
                  </Row>
                </div>
              </Card>
            </Col>
          </Row>
          <Modal
            key="2"
            width="600px"
            visible={this.state.visible}
            title={this.state.isMod == 1 ? '编辑诊断模板' : '添加诊断模板'}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
              <Button key="submitc" type="primary" onClick={this.handleCancel}>取消</Button>,
              <Button key="submits" type="primary" onClick={this.handleOk}>确定</Button>,
            ]}>
            <div>
              <Form>
                <Row gutter={60}>
                  <Col span={27}>
                    <FormItem label='名称' wrapperCol={{ span: 21 }} labelCol={{ span: 3 }}>
                      {getFieldDecorator('docMesName', {
                        initialValue: undefined,
                        rules: [{ required: true, message: '请输入名称' }],
                      })(
                        <Input placeholder="请输入名称，按回车键生成别名" onBlur={this.getOtherName} onPressEnter={this.getOtherName} maxLength={30} style={{ width: "100%" }} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={60}>
                  <Col span={12}>
                    <FormItem label='别名' wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                      {getFieldDecorator('othName', {
                        initialValue: undefined,
                        rules: [{ required: false, message: '' }],
                      })(
                        <Input ref={this.otherName} placeholder="不能超过30字" maxLength={30} />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem label='类型' wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                      {getFieldDecorator('docMesType', {
                        initialValue: undefined,
                        rules: [{ required: true, message: '' }],
                      })(
                        <Select style={{ width: "100%" }} disabled={tempChildDis}>
                          {ordtype}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={60}>
                  <Col span={12}>
                    <FormItem label='生效日期' wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                      {getFieldDecorator('startTime', {
                        initialValue: moment(),
                        rules: [{ required: true, message: '请选择生效日期' }],
                      })(
                        <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                          return curDate && curDate > moment().endOf('day');
                        }} />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem label='失效日期' wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                      {getFieldDecorator('overTime', {
                        initialValue: undefined,
                        rules: [{ required: false, message: '' }],
                      })(
                        <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                          return curDate < moment(this.props.form.getFieldValue('startTime')).format('YYYY-MM-DD');
                        }} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={60}>
                  <Col span={24}>
                    <FormItem label='备注' wrapperCol={{ span: 21 }} labelCol={{ span: 3 }}>
                      {getFieldDecorator('note', {
                        initialValue: undefined,
                        rules: [{ required: false, message: '' }],
                      })(
                        <TextArea maxLength={100} placeholder="字数限制100" />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
          </Modal>

          {/* 列表顺序调整 */}
          <PublicDataOrderAdjustment handleQuery={this.handleQuery} onRef={ref => this.sortRef = ref} />
        </div>
      )
    }
  })
export default DiagnoseTemplate