/*
 * Creator:     ML
 * CreatDate:
 * descripts：医嘱模板(个人模板)
 * */
import React from 'react';
import moment from 'moment';
import {
  Form,
  Row,
  Col,
  Input,
  Table,
  Select,
  DatePicker,
  Button,
  Modal,
  message,
  Divider,
  Tooltip,
  Icon,
  Card,
  Checkbox,
  Popconfirm,
  Pagination,
  Spin,
  AutoComplete
} from 'antd';
import { $http } from '../../containers/config/https';
import { Util } from 'tools/index';
import store from '../../store';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import PublicDataOrderAdjustment from 'pages/common/PublicDataOrderAdjustment';
import './css/OrderTemple.less';

var totalCount = 0;//总数量
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />
const FormItem = Form.Item;
const Option = Select.Option;

const DepartmentTemplate = Form.create()(
  class DepartmentTemplate extends React.Component {
    cacheOriginData = {};
    constructor() {
      super()
      var userData = JSON.parse(sessionStorage.getItem('userData'));
      this.state = {
        leftData: [],//左边查询到的表格数据
        rightData: [],//右边双击后的表格数据
        rightUnitDr: [],
        findInfo: '请输入查询条件',//查询提示信息
        checked: true,//默认选择生效
        visible: false,//添加/修改医嘱模板弹窗显示
        isMod: -1,//是否点击编辑
        ordTempletID: '',//编辑行id
        ordTempletDesc: '',//模板名称
        ordTempletAlias: '',//模板别名
        ordTempletCat: '',//医嘱分类
        rowId: '',//表格行id 设置颜色
        ordShow: false,//当前模板显示
        baseOrdTepCat: [],//添加医嘱模板类型选择
        baseTempType: [],//添加医嘱模板类型选择
        baseUnit: [],//添加医嘱明细单位类型选择
        selectedData: [],//医嘱明细选中
        selectedId: [],//医嘱明细选中
        tempChildDis: false,//左侧编辑 选择类型
        btnStatus: true,
        disAdd: false,//是否可新增
        canSaveStatus: 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
        initRored: {},//原始右侧表格行
        ordTempletDetailItemDesc: '',
        ordTempletDetailQty: '',
        ordTempletDetailQtyUnitDr: '',
        ordTempletDetailID: '',
        newOpen: [],
        ordTempletCatID: '',//区分草药/西药
        searchLoading: false,//名称规格搜索
        userData: userData,
        loading: false
      }
      this.detailDeInput = React.createRef();
      this.otherName = React.createRef();

      //左侧查询数据表
      this.columns = [{
        key: '1',
        title: '类型',
        dataIndex: 'templetCatDesc',
        width: '120px',
      }, {
        key: '2',
        align: 'left',
        width: '200px',
        title: '名称',
        dataIndex: 'ordTempletDesc',
        render: (text, record) => {
          return (
            <Tooltip title={text}>
              <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
            </Tooltip>
          )
        }
      }, {
        key: '3',
        align: 'left',
        width: '250px',
        title: '别名',
        dataIndex: 'ordTempletAlias',
        render: (text, record) => {
          return (
            <Tooltip title={text}>
              <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
            </Tooltip>
          )
        }
      }, {
        key: '4',
        align: 'center',
        width: '80px',
        title: '操作员',
        dataIndex: 'ordTempletUserDesc',
      }, {
        key: '5',
        align: 'center',
        width: '80px',
        title: '状态',
        dataIndex: 'ordTempletStatus',
      }, {
        key: '6',
        align: 'center',
        width: '120px',
        title: '操作',
        dataIndex: 'createdAt',
        fixed: 'right',
        render: (value, row, index) => {
          const obj = {
            children: (
              row?.ordTempletID ? (
                <span>
                  <span className="span" style={{ cursor: 'pointer' }} onClick={() => this.editDocMes(row, '1')}>编辑</span>
                  <Divider type="vertical" />
                  <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.editDocMes(row, '2')} >
                    <span className="span" style={{ cursor: 'pointer', color: 'rgba(240,65,52,1)' }}>删除</span>
                  </Popconfirm>
                </span>
              ) : (
                <span className="span" onClick={(e) => this.handleSort(row, e)}>设置个人排序</span>
              )
            ),
            props: {},
          };
          return obj;
        },
      }];
    }

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

    initColumnData() {
      const { getFieldDecorator } = this.props.form;
      let { searchLoading } = this.state
      var params = {
        params: [{
          // userID: this.state.userData.userID,
          // hospID: this.state.userData.hospID,
          // locID: this.state.userData.locID,
          // admID: '',
          compontName: 'DepartmentTemplate',
          type: 'C',
        }]
      }
      $http.post('urlDeault', this, {
        code: '01040073',
        // code: '03010027',
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            var columns = res.result.C;
            var dynColumns = []
            if (columns) {
              for (var i = 0; i < columns.length; i++) {
                if (columns[i].dataIndex == 'ordTempletDetailItemDesc') {//名称规格
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    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.detailDeInput}
                              placeholder="回车检索 输入名称"
                              style={{ textAlign: "center", width: "100%" }}
                              onBlur={(e) => this.initRord(e, record)}
                              onFocus={(e) => this.focusRord(e, record)}
                              onPressEnter={(e) => this.openNameDetail(e, 'ordTempletDetailItemDesc', record.key, record)}
                              value={text}
                              onChange={(e) => this.handleFieldChange(e, 'ordTempletDetailItemDesc', record.key)}
                            />
                          </Spin>
                        )
                      } if (!record.editable) {
                        return (
                          <Input placeholder="回车检索 输入名称" style={{ textAlign: "center", border: "0" }}
                            readOnly
                            value={text} />

                        )
                      }
                      return text;
                    },
                  })
                }
                if (columns[i].dataIndex == 'ordDose') {//剂量
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      if (record.editable) {
                        return (
                          <Input style={{ textAlign: "center" }}
                            value={text} type="number" min="1" onChange={(e) => this.handleFieldChange(e, 'ordDose', record.key)} />
                        )
                      } if (!record.editable) {
                        return (
                          <Input style={{ textAlign: "center", border: "0" }}
                            readOnly
                            value={text} />

                        )
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordDoseUnitDesc') {//剂量单位
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var doseUnitList = record.doseUnitList;
                      var doseUnitListOption = []
                      doseUnitList && doseUnitList.map((item, index) => {
                        doseUnitListOption.push(<Option key={index} value={item.doseUnitID}>{item.doseUnitDesc}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordDoseUnitID} style={{ width: "100%", textAlign: "center" }}
                            onSelect={this.handleChangeSelect.bind(this, 'ordDoseUnitID', record, index)} disable={this.state.editDis}>
                            {doseUnitListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordFreqDesc') {//频次
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var frequenceList = record.frequenceList;
                      var frequenceListOption = []
                      frequenceList && frequenceList.map((item, index) => {
                        frequenceListOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode} endsp={item.enDescripts}
                          frequency={item.frequency} cycleDays={item.cycleDays} intervalDays={item.intervalDays}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={frequenceList && frequenceList.length > 0 ? record.ordFreqID : record.ordFreqDesc}
                            style={{ width: "100%", textAlign: "center" }} allowClear
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              || option.props.endsp.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            dropdownMatchSelectWidth={false} onFocus={this.onBlurFreqSelect.bind(this, 'ordFreqID', index, record)}
                            onSelect={this.handleChangeSelect.bind(this, 'ordFreqID', record, index)} disable={this.state.editDis}>
                            {frequenceListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordUsageDesc') {//用法
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var usageList = record.usageList;
                      var usageListOption = []
                      usageList && usageList.map((item, index) => {
                        usageListOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={usageList && usageList.length > 0 ? record.ordUsageID : record.ordUsageDesc}
                            style={{ width: "100%", textAlign: "center" }} allowClear
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            dropdownMatchSelectWidth={false} onFocus={this.handleLoadUsage.bind(this, 'ordUsageID', index, record)}
                            onSelect={this.handleChangeSelect.bind(this, 'ordUsageID', record, index)} disable={this.state.editDis}>
                            {usageListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordDurQty') {//疗程
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      if (record.editable) {
                        return (
                          <Input style={{ textAlign: "center" }}
                            value={text} type="number" min="1" onChange={(e) => this.handleFieldChange(e, 'ordDurQty', record.key)} />
                        )
                      } if (!record.editable) {
                        return (
                          <Input style={{ textAlign: "center", border: "0" }}
                            readOnly
                            value={text} />

                        )
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordDurationDesc') {//疗程单位
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var durationList = record.durationList;
                      var durationListOption = []
                      durationList && durationList.map((item, index) => {
                        durationListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordDurationID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordDurationID', record, index)} disable={this.state.editDis}>
                            {durationListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordbodyPartDesc') {//部位
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var bodyPartListOption = []

                      // var { recLocList } = this.state;
                      var bodyPartList = record.bodyPartList;
                      var newData = []
                      bodyPartList && bodyPartList.map((item, index) => {
                        bodyPartListOption.push(<Option key={index} value={item.id} partid={item.id} descripts={item.descripts}
                          mutexflag={item.mutexFlag} ordprice={Number(item.ordPrice)}
                        // onClick={this.handleOnSelectColumns.bind(this, 'ordbodyPartID', index, data)}
                        >{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          record.radioFlag == 'Y' ? <Select onChange={this.changeBodyPartRadio.bind(this, 'ordbodyPartID', index, record)} style={{ width: '100%' }}
                            value={record.ordbodyPartID}>{bodyPartListOption}
                          </Select> : <Select onChange={this.changeBodyPartSelect.bind(this, 'ordbodyPartID', index, record)} style={{ width: '100%' }}
                            mode='tags' value={record.ordbodyPartID}>
                            {bodyPartListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordTempletDetailQty') {//数量
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, data, index) => {
                      //(疗程数*factor*frequency)/cycleDays
                      var totalNum = 0;//总次数
                      var totalDosc = 0;//总剂量
                      var oneDosc = 0;//剂量
                      var oneQty = 0;//单次数量
                      if (Util.isEmpty(data.ordTempletDetailID)) {
                        if (data.cycleDays) {//优先使用cycleDays，计算总次数
                          totalNum = Math.ceil((parseFloat(!Util.isEmpty(data.ordDurQty) ? data.ordDurQty : 1) * parseFloat(data.duraFactor || 1) * parseFloat(data.frequency || 1)) / (data.cycleDays && parseFloat(data.cycleDays) > 0 ? parseFloat(data.cycleDays) : 1))
                        } else {
                          totalNum = Math.ceil((parseFloat(!Util.isEmpty(data.ordDurQty) ? data.ordDurQty : 1) * parseFloat(data.duraFactor || 1) * parseFloat(data.frequency || 1)) / (data.intervalDays && parseFloat(data.intervalDays) > 0 ? parseFloat(data.intervalDays) : 1))
                        }
                        //门诊
                        if (data.ordToalCountO == 'Y') {
                          totalDosc = Math.ceil((parseFloat(data.ordDose ? data.ordDose : 1) * totalNum * parseFloat(!Util.isEmpty(data.doseMolecule) ? data.doseMolecule : 1)).toFixed(2) / (parseFloat(data.doseDenominator) > 0 ? parseFloat(data.doseDenominator) : 1))
                          //最后算总数量
                          if (Util.isEmpty(data.duraFactor) || Util.isEmpty(data.ordDurQty) || Util.isEmpty(data.frequency) ||
                            Util.isEmpty(data.cycleDays) || Util.isEmpty(data.ordDose) || Util.isEmpty(data.doseMolecule)
                            || Util.isEmpty(data.doseDenominator) || Util.isEmpty(data.doseDenominator)) {
                            //阿卡波糖片问题，不知为何之前置位1
                            totalCount = Math.ceil((totalDosc * parseFloat(data.qtyMolecule ? data.qtyMolecule : 1)) / (parseFloat(data.qtyDenominator) > 0 ? parseFloat(data.qtyDenominator) : 1))
                            if (Util.isEmpty(data.ordTempletDetailID) /**&& data.qtyStatus == '2'**/) {
                              data.newQty = totalCount
                              data.totalCount = totalCount
                            }
                          } else {
                            totalCount = Math.ceil((totalDosc * parseFloat(data.qtyMolecule ? data.qtyMolecule : 1)) / (parseFloat(data.qtyDenominator) > 0 ? parseFloat(data.qtyDenominator) : 1))
                            if (Util.isEmpty(data.ordTempletDetailID) /**&& data.qtyStatus == '2'**/) {
                              data.newQty = totalCount
                              data.totalCount = totalCount
                            } else {
                              data.totalCount = data.ordQty ? data.ordQty : 1
                            }
                          }
                        } else {//先取整，再算
                          oneDosc = Math.ceil((parseFloat(data.ordDose ? data.ordDose : 1) * parseFloat(data.doseMolecule ? data.doseMolecule : 1)) / (parseFloat(data.doseDenominator) > 0 ? parseFloat(data.doseDenominator) : 1))
                          // totalDosc = oneDosc * totalNum
                          oneQty = Math.ceil((oneDosc * parseFloat(data.qtyMolecule ? data.qtyMolecule : 1)) / (parseFloat(data.qtyDenominator) > 0 ? parseFloat(data.qtyDenominator) : 1))
                          data.newQty = oneQty * totalNum
                        }
                      }
                      if (data.editable) {
                        return (
                          <Input style={{ textAlign: "center" }} value={data.medID ? (data.defaultStatus == true ? data.ordTempletDetailQty : data.newQty) : undefined}
                            onChange={this.handleChangeInput.bind(this, 'ordTempletDetailQty', data, index)} />
                        )
                      } if (!data.editable) {
                        return (
                          <Input style={{ textAlign: "center", border: "0" }}
                            readOnly
                            value={text} />

                        )
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordTempletDetailQtyUnitDesc') {//数量单位
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var qtyUnitList = record.qtyUnitList;
                      var qtyUnitListOption = []
                      qtyUnitList && qtyUnitList.map((item, index) => {
                        qtyUnitListOption.push(<Option key={index} value={item.unitID}>{item.unitDesc}</Option>)
                      })
                      // console.dir(qtyUnitList)
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordTempletDetailQtyUnitDr} style={{ width: "100%", textAlign: "center" }} onSelect={(e) => this.handleFieldChange(e, 'ordTempletDetailQtyUnitDr', record.key)} disable={this.state.editDis}>
                            {qtyUnitListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordTempletDetailItemPrice') {//单价
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    className: 'colClassName',
                    render: (text, record, index) => {
                      var price = 0;
                      var source = record.priceData;
                      source && source.map((item, index) => {
                        price += Number(item)
                      })
                      if (source) {
                        record.ordPrice = price
                        record.ordTempletDetailItemPrice = price
                      }
                      if (record.editable) {
                        return (
                          <span>{(record.priceData ? price : record.ordTempletDetailItemPrice)}</span>
                        )
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordTempletStatus') {//总价
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    className: 'colClassName',
                    render: (text, record, index) => {
                      const { isAdd } = this.state
                      if (record.editable) {
                        return (
                          <span style={{ textAlign: "center", border: "0", width: "100%", display: "inline-block" }}>
                            {record.ordTempletDetailQty ? ((record.medID ? (record.defaultStatus == true ? record.ordTempletDetailQty : record.newQty) : 1) * record.ordTempletDetailItemPrice).toFixed(2) : 0}</span>
                        )
                      }
                      if (record.editable && isAdd) {
                        return (
                          <FormItem >
                            {getFieldDecorator('ordTemToalPrice', {
                              initialValue: undefined,
                              rules: [{ required: false, message: '' }],
                            })(
                              <span style={{ textAlign: "center", border: "0", width: "100%", display: "inline-block" }} />
                            )}
                          </FormItem>
                        )
                      } else {
                        return (
                          <span style={{ textAlign: "center", border: "0", width: "100%", display: "inline-block" }}>{record.ordTempletDetailQty ? record.ordTempletDetailQty * record.ordTempletDetailItemPrice : 0}</span>
                        )
                      }

                    },
                  })
                }

                if (columns[i].dataIndex == 'ordSkinTestFlag') {//皮试
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      if (record.editable) {
                        return (
                          <Checkbox checked={record.ordSkinTestFlag == 'Y' ? true : (record.ordSkinTestFlagValue == 'Y' ? true : false)}
                            disabled={record.testFlag == 'N' ? true : false}
                            onChange={this.changeCheckBox.bind(this, 'ordSkinTestFlag', index)} />
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Checkbox disabled={true} checked={record.ordSkinTestFlag == 'Y' ? true : false} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordSkinTestWayDesc') {//皮试备注
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var skinTestWayList = record.skinTestWayList;
                      var skinTestWayListOption = []
                      skinTestWayList && skinTestWayList.map((item, index) => {
                        skinTestWayListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordSkinTestWayID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordSkinTestWayID', record, index)} disable={this.state.editDis}>
                            {skinTestWayListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordEMFlag') {//急诊
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      if (record.editable) {
                        return (
                          <Checkbox checked={record.ordEMFlag == 'Y' ? true : (record.ordEMFlagValue == 'Y' ? true : false)}
                            disabled={record.testEMFlag == 'Y' ? false : true}
                            onChange={this.changeCheckBox.bind(this, 'ordEMFlag', index)} />
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Checkbox disabled={true} checked={record.ordEMFlag == 'Y' ? true : false} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordPriorityDesc') {//医嘱优先级
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var priorityList = record.priorityList;
                      var priorityListOption = []
                      priorityList && priorityList.map((item, index) => {
                        priorityListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordPriorityID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordPriorityID', record, index)} disable={this.state.editDis}>
                            {priorityListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordSpecDesc') {//标本
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var specList = record.specList;
                      var specListOption = []
                      specList && specList.map((item, index) => {
                        specListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordSpecID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordSpecID', record, index)} disable={this.state.editDis}>
                            {specListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordNote') {//备注
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var ordNoteList = record.ordNoteList;
                      var ordNoteListOption = []
                      ordNoteList && ordNoteList.map((item, index) => {
                        ordNoteListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <AutoComplete style={{ width: '90%' }}
                            value={record.ordNote} dataSource={ordNoteListOption}
                            onChange={this.commonInput.bind(this, 'ordNote', index, record)} />
                          // <Select showSearch optionFilterProp="role" value={record.ordNote} style={{ width: "100%", textAlign: "center" }} allowClear
                          //   dropdownMatchSelectWidth={false}
                          //   onSelect={this.handleChangeSelect.bind(this, 'ordNote', record, index)} disable={this.state.editDis}>
                          //   {ordNoteListOption}
                          // </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordRecLocDesc') {//执行科室
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var recLocList = record.recLocList;
                      var recLocListOption = []
                      recLocList && recLocList.map((item, index) => {
                        recLocListOption.push(<Option key={index} value={item.recLocID}>{item.recLocDesc}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordRecLocID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordRecLocID', record, index)} disable={this.state.editDis}>
                            {recLocListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordPriorityExtDesc') {//附加说明
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var priorityExtList = record.priorityExtList;
                      var ordPriorityExtlistOption = []
                      priorityExtList && priorityExtList.map((item, index) => {
                        ordPriorityExtlistOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordPriorityExtID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordPriorityExtID', record, index)} disable={this.state.editDis}>
                            {ordPriorityExtlistOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'ordStageDesc') {//医嘱阶段
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    editable: true,
                    render: (text, record, index) => {
                      var stageList = record.stageList;
                      var stageListOption = []
                      stageList && stageList.map((item, index) => {
                        stageListOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
                      })
                      if (record.editable) {
                        return (
                          <Select showSearch optionFilterProp="role" value={record.ordStageID} style={{ width: "100%", textAlign: "center" }} allowClear
                            dropdownMatchSelectWidth={false}
                            onSelect={this.handleChangeSelect.bind(this, 'ordStageID', record, index)} disable={this.state.editDis}>
                            {stageListOption}
                          </Select>
                        )
                      } else {
                        if (!record.editable) {
                          return (
                            <Input style={{ textAlign: "center", border: "0" }}
                              readOnly
                              value={text} />
                          )
                        }
                      }
                      return text;
                    },
                  })
                }

                if (columns[i].dataIndex == 'operation') {//操作
                  dynColumns.push({
                    title: columns[i].title,
                    dataIndex: columns[i].dataIndex,
                    width: parseInt(columns[i].width),
                    align: columns[i].align || 'center',
                    fixed: 'right',
                    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>
                        )
                      }


                    }
                  })
                }
              }
            }
            this.setState({
              dynColumns: dynColumns,
            })
          }
        }
      });
    }

    //回车查找医嘱模板数据
    handleQuery = () => {
      // console.log("111111",this.props.form.getFieldValue('info'))
      let data = {}
      data = {
        params: [{
          templetTypeID: "1",
          status: this.state.checked == true ? "Y" : "N",
          input: this.props.form.getFieldValue('info'),
        }],
      }
      $http.post('urlS', this, {
        code: '03050011',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            let newOpen = []
            let arr = res.result && res.result.map((item, index) => {
              res.result[index].key = Number(index)
              newOpen.push(Number(index))
              return {
                id: item.ordTempletID,
                templetCatDesc: item.templetCatDesc,
                key: Number(index),
                children: item.data && item.data.map((childItem, childIndex) => {
                  this.setState({
                    // rowId:item.data[0].ordTempletID,

                  })
                  if (childItem.ordTempletStatus == "Y") {
                    childItem.ordTempletStatus = "生效"
                  } if (childItem.ordTempletStatus == "N") {
                    childItem.ordTempletStatus = "失效"
                  }
                  return {
                    key: childItem.ordTempletID,
                    ...childItem,
                  }
                })
              }
            })
            this.setState({
              newOpen: newOpen,
              leftData: arr,
              text: arr[0],
              findInfo: res.result && res.result.length == 0 ? '未查询到医嘱模板,请添加或者重新查找' : ''
            })
          } else {

          }
        }
      })
    }

    loadTableData(record) {
      var params = {
        params: [{
          indexID: this.state.tabIndex,
          orders: [{
            medID: record.medID && record.medID ? record.medID : (record.ordSetID && record.ordSetID ? record.ordSetID : ''),
            ordSetID: record.medID && record.medID ? record.medID : (record.ordSetID && record.ordSetID ? record.ordSetID : ''),
          }],
        }]
      }
      $http.post('urlDeault', this, {
        code: "03050020",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            if (!Util.isEmpty(res.data)) {
              if (Util.isEmpty(record.ordSetID)) {
                this.state.rightData[this.state.tabIndex - 1]['ordDoseUnitID'] = res.data[0].defaultData.ordDoseUnitID
                this.state.rightData[this.state.tabIndex - 1]['ordDoseUnitDesc'] = res.data[0].defaultData.ordDoseUnitDesc
                this.state.rightData[this.state.tabIndex - 1]['ordDose'] = res.data[0].defaultData.ordDose
                this.state.rightData[this.state.tabIndex - 1]['ordDurQty'] = res.data[0].defaultData.ordDurQty
                this.state.rightData[this.state.tabIndex - 1]['radioFlag'] = res.data[0].defaultData.radioFlag
                this.state.rightData[this.state.tabIndex - 1]['medID'] = res.data[0].defaultData.medID
                this.state.rightData[this.state.tabIndex - 1]['ordDurationDesc'] = res.data[0].defaultData.ordDurationDesc
                this.state.rightData[this.state.tabIndex - 1]['ordDurationID'] = res.data[0].defaultData.ordDurationID
                this.state.rightData[this.state.tabIndex - 1]['ordEMFlag'] = res.data[0].defaultData.ordEMFlag
                this.state.rightData[this.state.tabIndex - 1]['ordEMFlagValue'] = res.data[0].defaultData.ordEMFlagValue
                this.state.rightData[this.state.tabIndex - 1]['ordStageID'] = res.data[0].defaultData.ordStageID
                this.state.rightData[this.state.tabIndex - 1]['ordPriorityExtID'] = res.data[0].defaultData.ordPriorityExtID
                this.state.rightData[this.state.tabIndex - 1]['ordFreqDesc'] = res.data[0].defaultData.ordFreqDesc
                this.state.rightData[this.state.tabIndex - 1]['ordTempletDetailQtyUnitDr'] = res.data[0].defaultData.ordQtyUomID
                this.state.rightData[this.state.tabIndex - 1]['ordFreqID'] = res.data[0].defaultData.ordFreqID
                this.state.rightData[this.state.tabIndex - 1]['ordNote'] = res.data[0].defaultData.ordNote
                this.state.rightData[this.state.tabIndex - 1]['defaultStatus'] = true
                this.state.rightData[this.state.tabIndex - 1]['frequency'] = res.data[0].defaultData.frequency,
                  this.state.rightData[this.state.tabIndex - 1]['doseDenominator'] = res.data[0].defaultData.doseDenominator,
                  this.state.rightData[this.state.tabIndex - 1]['doseMolecule'] = res.data[0].defaultData.doseMolecule,
                  this.state.rightData[this.state.tabIndex - 1]['cycleDays'] = res.data[0].defaultData.cycleDays,
                  this.state.rightData[this.state.tabIndex - 1]['intervalDays'] = res.data[0].defaultData.intervalDays,
                  this.state.rightData[this.state.tabIndex - 1]['duraFactor'] = res.data[0].defaultData.duraFactor,
                  this.state.rightData[this.state.tabIndex - 1]['ordPrice'] = res.data[0].defaultData.ordPrice,
                  this.state.rightData[this.state.tabIndex - 1]['ordTempletDetailQty'] = res.data[0].defaultData.ordQty,
                  this.state.rightData[this.state.tabIndex - 1]['ordTempletDetailItemPrice'] = res.data[0].defaultData.ordPrice,
                  this.state.rightData[this.state.tabIndex - 1]['ordPriorityDesc'] = res.data[0].defaultData.ordPriorityDesc
                this.state.rightData[this.state.tabIndex - 1]['ordPriorityExtDesc'] = res.data[0].defaultData.ordPriorityExtDesc
                this.state.rightData[this.state.tabIndex - 1]['ordPriorityID'] = res.data[0].defaultData.ordPriorityID
                this.state.rightData[this.state.tabIndex - 1]['ordQtyUomID'] = res.data[0].defaultData.ordQtyUomID
                this.state.rightData[this.state.tabIndex - 1]['ordQty'] = res.data[0].defaultData.ordQty
                this.state.rightData[this.state.tabIndex - 1]['ordRecLocDesc'] = res.data[0].defaultData.ordRecLocDesc
                this.state.rightData[this.state.tabIndex - 1]['ordUsageDesc'] = res.data[0].defaultData.ordUsageDesc
                this.state.rightData[this.state.tabIndex - 1]['ordUsageID'] = res.data[0].defaultData.ordUsageID
                this.state.rightData[this.state.tabIndex - 1]['ordSpecID'] = res.data[0].defaultData.ordSpecID
                this.state.rightData[this.state.tabIndex - 1]['ordRecLocID'] = res.data[0].defaultData.ordRecLocID
                this.state.rightData[this.state.tabIndex - 1]['ordSkinTestUsageDesc'] = res.data[0].defaultData.ordSkinTestUsageDesc
                this.state.rightData[this.state.tabIndex - 1]['ordSkinTestUsageID'] = res.data[0].defaultData.ordSkinTestUsageID
                this.state.rightData[this.state.tabIndex - 1]['ordToalCountO'] = res.data[0].defaultData.ordToalCountO
                this.state.rightData[this.state.tabIndex - 1]['ordToalCountI'] = res.data[0].defaultData.ordToalCountI
                this.state.rightData[this.state.tabIndex - 1]['ordSpecDesc'] = res.data[0].defaultData.ordSpecDesc
                this.state.rightData[this.state.tabIndex - 1]['ordSkinTestFlagValue'] = res.data[0].defaultData.ordSkinTestFlagValue
                this.state.rightData[this.state.tabIndex - 1]['ordSkinTestFlag'] = res.data[0].defaultData.ordSkinTestFlag
                this.state.rightData[this.state.tabIndex - 1]['ordQtyUomDesc'] = res.data[0].defaultData.ordQtyUomDesc
                this.state.rightData[this.state.tabIndex - 1]['qtyUnitList'] = res.data[0].dataList.qtyUnitList
                this.state.rightData[this.state.tabIndex - 1]['doseUnitList'] = res.data[0].dataList.doseUnitList
                this.state.rightData[this.state.tabIndex - 1]['durationList'] = res.data[0].dataList.durationList
                this.state.rightData[this.state.tabIndex - 1]['priorityList'] = res.data[0].dataList.priorityList
                this.state.rightData[this.state.tabIndex - 1]['priorityExtList'] = res.data[0].dataList.priorityExtList
                this.state.rightData[this.state.tabIndex - 1]['eyePartList'] = res.data[0].dataList.eyePartList
                this.state.rightData[this.state.tabIndex - 1]['recLocList'] = res.data[0].dataList.recLocList
                this.state.rightData[this.state.tabIndex - 1]['stageList'] = res.data[0].dataList.stageList
                this.state.rightData[this.state.tabIndex - 1]['skinTestWayList'] = res.data[0].dataList.skinTestWayList
                this.state.rightData[this.state.tabIndex - 1]['degreesList'] = res.data[0].dataList.degreesList
                this.state.rightData[this.state.tabIndex - 1]['bodyPartList'] = res.data[0].dataList.bodyPartList
              }
            }
            this.setState({})
          }
        }
      });
    }

    //点击展开
    openExpand = (expanded, record) => {
      // console.log("expaned",expanded,"record",record)
      // let arr = this.state.newOpen
      const arr = this.state.newOpen.map(item => ({ ...item }));
      if (expanded) {
        arr.push(record.key)
        this.setState({
          newOpen: arr
        })
      } else {
        arr.splice(record.key, 1)
        this.setState({
          newOpen: arr
        })
      }

    }

    //添加医嘱模板弹出
    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: [{
              ordTempletID: this.state.isMod == 1 ? this.state.ordTempletID : '',
              ordTempletTypeID: "1",
              ordTempletDesc: this.props.form.getFieldValue('docMesName'),
              ordTempletCatID: this.props.form.getFieldValue('docMesType'),
              ordTempletAlias: this.props.form.getFieldValue('othName'),
              ordTempletStartDate: moment(this.props.form.getFieldValue('startTime')).format('YYYY-MM-DD') || '',
              ordTempletStopDate: this.props.form.getFieldValue('overTime') ? moment(this.props.form.getFieldValue('overTime')).format('YYYY-MM-DD') : '',
            }],
          }
          $http.post('urlS', this, {
            code: '03050012',
            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 {

              }
            }
          })
        }
      })
    }

    //获取右侧详细
    getDeatil = (record) => {
      this.setState({
        ordTempletCatID: record.ordTempletCatID,
        ordTempletDesc: record.ordTempletDesc,
        ordTempletAlias: record.ordTempletAlias,
        ordTempletCat: record.ordTempletCatDesc,
        ordShow: true,
        OrdCanType: record.ordTempletCatDesc,
        canSaveStatus: true,
        btnStatus: true,
        disAdd: false,
        selectedRowKeys_right: [],
        loading: true
      })
      //获取医嘱模板明细
      let data = {}
      data = {
        params: [{
          ordTempletID: record.ordTempletID,
        }],
      }
      $http.post('urlS', this, {
        code: '03050014',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            // console.log("获取医嘱模板明细信息",res)
            res.result.map((item, i) => {
              res.result[i].key = item.ordTempletDetailID
              res.result[i].keys == Number(i)
              this.setState({
                rightUnitDr: item.ordTempletDetailQtyUnitDr,
                selectedRowKeys_right: []
              })
            })
            // for (var i = 0; i < res.result.length; i++) {
            //   res.result[i].key = res.result[i].ordTempletDetailID

            // }
            this.setState({
              rightData: res.result,
              loading: false
            }, () => {
              var data = this.state.rightData;
              if (!Util.isEmpty(data)) {
                for (var i = 0; i < data.length; i++) {
                  this.state.rightData[i]['ordTempletDetailQty'] = data[i].ordTempletDetailQty
                  this.state.rightData[i]['qtyUnitList'] = data[i].dataList.qtyUnitList
                  this.state.rightData[i]['doseUnitList'] = data[i].dataList.doseUnitList
                  this.state.rightData[i]['durationList'] = data[i].dataList.durationList
                  this.state.rightData[i]['priorityList'] = data[i].dataList.priorityList
                  this.state.rightData[i]['priorityExtList'] = data[i].dataList.priorityExtList
                  this.state.rightData[i]['eyePartList'] = data[i].dataList.eyePartList
                  this.state.rightData[i]['recLocList'] = data[i].dataList.recLocList
                  this.state.rightData[i]['skinTestWayList'] = data[i].dataList.skinTestWayList
                  this.state.rightData[i]['stageList'] = data[i].dataList.stageList
                  this.state.rightData[i]['degreesList'] = data[i].dataList.degreesList
                  this.state.rightData[i]['bodyPartList'] = data[i].dataList.bodyPartList
                }
              }
            })

          } else {
            this.setState({
              loading: false
            })
          }
        }
      })
    }

    //点击Row 左侧表格
    onClickRow = (record) => {
      return {
        onClick: () => {
          if (record.ordTempletID) {
            if (this.state.rowId === '') {
              this.setState({
                rowId: record.ordTempletID,
              });
              this.getDeatil(record)
            } else {
              if (this.state.rowId !== record.ordTempletID) {
                this.setState({
                  rowId: record.ordTempletID,
                });
                this.getDeatil(record)
              } else {
                this.setState({
                  rowId: '',
                  ordShow: false
                });
              }
            }

          }
        },
        onDoubleClick: () => {
          this.setState({
            rowId: '',
            ordShow: false
          });
        }
      }
    }

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

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

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

    //编辑医嘱模板
    editDocMes = (data, num) => {
      // console.log(data)
      if (num == "1") {
        this.props.form.setFieldsValue({ docMesName: data.ordTempletDesc });
        this.props.form.setFieldsValue({ othName: data.ordTempletAlias });
        this.props.form.setFieldsValue({ docMesType: String(data.ordTempletCatID) });
        this.props.form.setFieldsValue({ startTime: moment(data.ordTempletStartDate) });
        this.props.form.setFieldsValue({ overTime: data.ordTempletStopDate ? moment(data.ordTempletStopDate) : undefined });
        this.setState({
          isMod: 1,
          visible: true,
          ordTempletID: data.ordTempletID
        })
        if (!data.ordTempletChildFlag == "Y") {
          this.setState({
            tempChildDis: true
          })
        }
      } else {
        //删除医嘱模板
        let datas = {}
        datas = {
          params: [{
            ordTempletID: data.ordTempletID,
          }],
        }
        $http.post('urlS', this, {
          code: '03050013',
          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
        }
        // console.log("data",data)
        // console.log("keys",keys)
        // console.log("[keys[i]",keys[i])
        // console.log("data[keys[i]",data[keys[i]-1])
        // if(data[keys[i]]==undefined){
        //   var nkeys = keys[i]-1
        //   var curRowData = data[nkeys]
        // }else{
        //   var curRowData = data[keys[i]]
        // }
        var curRowData = data[keys[i]]
        var curRowKey = curRowData.keys
        var upRowData = data[keys[i] - 1]
        var upRowKey = upRowData.keys
        upRowData.keys = curRowKey
        curRowData.keys = 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.keys
        var upRowKey = upRowData.keys
        upRowData.keys = curRowKey
        curRowData.keys = 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: [{
          ordTempletID: this.state.rowId,
        }],
      }
      $http.post('urlS', this, {
        code: '03050014',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            res.result.map((item, i) => {
              res.result[i].key = item.ordTempletDetailID
              res.result[i].keys == Number(i)
            })
            this.setState({
              rightData: res.result
            }, () => {
              var data = this.state.rightData;
              if (!Util.isEmpty(data)) {
                for (var i = 0; i < data.length; i++) {
                  this.state.rightData[i]['ordTempletDetailQty'] = data[i].ordTempletDetailQty
                  this.state.rightData[i]['radioFlag'] = data[i].radioFlag
                  this.state.rightData[i]['qtyUnitList'] = data[i].dataList.qtyUnitList
                  this.state.rightData[i]['doseUnitList'] = data[i].dataList.doseUnitList
                  this.state.rightData[i]['durationList'] = data[i].dataList.durationList
                  this.state.rightData[i]['priorityList'] = data[i].dataList.priorityList
                  this.state.rightData[i]['priorityExtList'] = data[i].dataList.priorityExtList
                  this.state.rightData[i]['eyePartList'] = data[i].dataList.eyePartList
                  this.state.rightData[i]['recLocList'] = data[i].dataList.recLocList
                  this.state.rightData[i]['skinTestWayList'] = data[i].dataList.skinTestWayList
                  this.state.rightData[i]['stageList'] = data[i].dataList.stageList
                  this.state.rightData[i]['degreesList'] = data[i].dataList.degreesList
                  this.state.rightData[i]['bodyPartList'] = data[i].dataList.bodyPartList
                }
              }
            })
          }
        }
      })
    }

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

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

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

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

    //文本框数据修改
    handleFieldChange = (e, fieldName, key) => {
      const { rightData, baseUnit } = 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
            for (var j = 0; j < baseUnit.length; j++) {
              if (newData[i].ordTempletDetailQtyUnitDr == baseUnit[j].id) {
                newData[i].ordTempletDetailQtyUnitDesc = baseUnit[j].descripts
              }
            }
          }
        }
        this.setState({
          rightData: newData,
          canSaveStatus: false,
        })
        return
      }
      if (target) {
        target[fieldName] = e.target.value;
        this.setState({
          rightData: newData,
          canSaveStatus: false,
          tabIndex: key
        })
        if (fieldName == "ordTemNumber") {
          this.props.form.setFieldsValue({ ordTemNumber: e.target.value });
          this.props.form.setFieldsValue({ ordTemToalPrice: e.target.value * this.state.ordTemPrice });
        }
        else {
          this.props.form.setFieldsValue({ ordTemName: e.target.value });
          this.setState({
            ordDetailValue: e.target.value
          });
        }
      }
    }

    //名称/规格信息明细
    openNameDetail = (e, fieldName, key, data) => {
      // console.log(this.state.ordDetailValue)
      const { ordTempId, ordDetailValue, page, pageSize, rightData } = this.state;
      if (!ordDetailValue) {
        message.warning("请输入检索名称")
        return
      }
      this.setState({
        searchLoading: true,
        // nowRowID:key
      })
      const newData = rightData.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      let targetValue = ''
      if (target) {
        targetValue = ordDetailValue;
      }
      if (ordDetailValue && ordDetailValue) {
        //获取医嘱项信息
        let data = {}
        data = {
          params: [{
            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : '',
            hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
            groupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : '',
            logonLocID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : '',
            searchCode: ordDetailValue ? ordDetailValue : targetValue,
            cmFlag: this.state.ordTempletCatID == "2" ? "Y" : ''
            // ordCatID:ordTempId,
            // detailFlag:1,
          }],
          pagination: [{
            pageSize: pageSize,
            currentPage: page,
          }]
        }
        $http.post('urlS', this, {
          code: '03050019',
          data: data,
          success: function (res) {
            // console.log("搜索",res)
            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({
                OrdDaRowId: res.result.data[0].medCode,
                searchLoading: false,
                OrdDaShow: true,
                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++) {
        rightData[i]['ordTempletID'] = rowId
        rightData[i].ordTempletDetailSeqNo = i + 1
        if (rightData[i].ordTempletDetailItemID == '') {
          message.warning("请回车检索")
          return
        } if (rightData[i].ordTempletDetailItemDesc == '') {
          message.warning("请回车检索")
          return
        }
        //  if (rightData[i].ordTempletDetailQty <= 0) {
        //   message.warning("请输入数量")
        //   return
        // }
        // if(rightData[i].ordTempletDetailQtyUnitDr==''){
        //   message.warning("请选择数量")
        //   return
        // }
      }
      // var tempData = []
      // if (!Util.isEmpty(this.state.rightData)) {
      //   var source = this.state.rightData;
      //   for (var i = 0; i < source.length; i++) {
      //     if (Util.isEmpty(source[i].ordTempletDetailID)) {
      //       tempData.push(source[i])
      //     }
      //   }
      // }
      var temp = []
      if (!Util.isEmpty(this.state.rightData)) {
        var source = this.state.rightData;
        console.dir(source)
        for (var i = 0; i < source.length; i++) {
          temp.push({
            ...source[i],
            bodyPart: source[i].ordbodyPartID,
            ordPrioID: source[i].ordPriorityID,//优先级
            dose: source[i].ordDose,//剂量
            doseUnitID: source[i].ordDoseUnitID,//剂量单位
            frequenceID: source[i].ordFreqID,//频次
            usageID: source[i].ordUsageID,//用法
            durQty: source[i].ordDurQty,//疗程
            durationID: source[i].ordDurationID,//疗程单位
            priorityExtID: source[i].ordPriorityExtID,//附加说明
            recLocID: source[i].ordRecLocID,//执行科室
            ordSpecID: source[i].ordSpecID,//标本
            emergencyFlag: source[i].ordEMFlag,//加急
            note: source[i].ordNote,//备注
            ordTempletDetailQty: Util.isEmpty(source[i].ordTempletDetailID) ? (source[i].ordNewQty ? source[i].ordNewQty : source[i].newQty) : source[i].ordTempletDetailQty,
            skinTestFlag: source[i].ordSkinTestFlag == 'N' ? source[i].ordSkinTestFlagValue : source[i].ordSkinTestFlag,
            skinTestWayID: source[i].ordSkinTestFlag == 'N' && source[i].ordSkinTestFlagValue == 'N' ? '' : source[i].ordSkinTestWayID,
            extvalue: [{
              code: 'eyePart',
              value: source[i].eyePartID,
              refDescripts: 'eyePartDesc',
            }],
            skinTestWayList: undefined,
            admReasonList: undefined,
            doseUnitList: undefined,
            durationList: undefined,
            frequenceList: undefined,
            priorityExtList: undefined,
            priorityList: undefined,
            qtyUnitList: undefined,
            recLocList: undefined,
            specList: undefined,
            usageList: undefined,
            causeList: undefined,
            stageList: undefined,
            infuseSpeedList: undefined,
            degreesList: undefined,
            eyePartList: undefined,
            bodyPartList: undefined,
          })
        }
      }
      data = {
        params: temp,
      }
      $http.post('urlS', this, {
        code: '03050015',
        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()
          }
        }
      })
    }

    //名称规格搜索 获取焦点
    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)
      })
    }

    //名称规格 失去焦点
    initRord = (e, record) => {
      const { rightData } = this.state
      // if(e.target.value!=this.state.ordTempletDetailItemDesc){
      //   rightData.map((item,index)=>{
      //     const ordTemDec = {}
      //     if(this.state.ordTempletDetailID==rightData[index].ordTempletDetailID){
      //       rightData[index].ordTempletDetailItemDesc = this.state.ordTempletDetailItemDesc;
      //       this.props.form.setFieldsValue({
      //         ordTempletDetailID:this.state.ordTempletDetailItemDesc
      //         });

      //     }
      //   })
      // }
      // if (e.target.value != this.state.ordTempletDetailItemDesc) {
      //   rightData.map((item, index) => {
      //       if(record.ordTempletDetailID&&record.ordTempletDetailID&&record.ordTempletDetailID == rightData[index].ordTempletDetailID){
      //       rightData[index].ordTempletDetailItemDesc = this.state.ordTempletDetailItemDesc
      //       }
      //   })
      // }
    }

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

    //选中当前行
    checkNowData = (record) => {
      const { rightData, nowRowID } = this.state;
      /**
       * @shizi: 不能添加医嘱套提醒
       * Create 2021-06-27
       */
      if (!(record && 'medID' in record && record.medID)) {
        message.error('暂不支持添加医嘱套，请重新选择需要添加的医嘱。');
        return;
      }
      if (!Util.isEmpty(rightData)) {
        for (var i = 0; i < rightData.length; i++) {
          if (rightData[i].medID == record.medID) {
            message.error('该医嘱已经存在，请重新选择！');
            return
          }
        }
      }
      // console.log("信息带回", record, "rightData", rightData, "nowRowID", nowRowID)
      this.setState({
        OrdDaRowId: record.medCode,
        // ordDetailValue:record.medDesc,
        isAdd: true,
        ordTempletDetailItemDesc: record.medDesc
      })
      for (var i = 0; i < rightData.length; i++) {
        if (nowRowID == rightData[i].key) {
          rightData[i].ordTempletDetailItemID = record.medID && record.medID ? record.medID : (record.ordSetID && record.ordSetID ? record.ordSetID : '');
          rightData[i].ordTempletDetailQty = record.medDurQty && record.medDurQty ? record.medDurQty : 1;
          rightData[i].ordTempletDetailQtyUnitDesc = record.medUnitDesc && record.medUnitDesc ? record.medUnitDesc : '';
          rightData[i].ordTempletDetailQtyUnitDr = record.medUnitID && record.medUnitID ? record.medUnitID : '';
          rightData[i].ordTempletDetailItemPrice = record.medPrice;
          rightData[i].ordTempletDetailTemplItemTypeCode = record.ordSetID && record.ordSetID ? "02" : "01",
            rightData[i].ordTempletDetailItemDesc = record.medDesc && record.medDesc ? record.medDesc : ''
          // rightData[i].ordTempletDetailQty
        }
      }
      this.setState({
        ordTemPrice: record.medPrice,
        editDis: false,
        addInfo: true
      }, () => {
        this.handleTemDaCancel()
        this.loadTableData(record)
      }
      )
    }

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

    //编辑 医嘱项表格行
    toggleEditable = (e, key, record) => {
      e.preventDefault();
      this.setState({
        ordTempletDetailItemDesc: record.ordTempletDetailItemDesc,
        ordTempletDetailQty: record.ordTempletDetailQty,
        ordTempletDetailQtyUnitDr: record.ordTempletDetailQtyUnitDr,
        ordTempletDetailID: record.ordTempletDetailID,
        disAdd: false
      })
      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.detailDeInput.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);
      // console.log("取消",target,"this.cacheOriginData",this.cacheOriginData)
      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 newData = rightData.filter(item => item.key !== key);
      let bs = false
      newData.map((item, i) => {
        if (item.ordTempletDetailSeqNo && 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,
      })
      this.props.form.setFieldsValue({ docMesName: undefined });
      this.props.form.setFieldsValue({ othName: undefined });
      this.props.form.setFieldsValue({ docMesType: "1" });
    }

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

    //详细信息页面上下移动
    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].medCode === this.state.OrdDaRowId) {
                obj = i > 0 ? oneArr[i] : oneArr[0];
                break;
              }
            }
            // console.log("当前",obj)
            this.setState({
              visible: false,
              OrdDaRowId: obj.medCode,
            })
            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].medCode === this.state.OrdDaRowId) {
                id = i > 0 ? oneArr[i - 1].medCode : oneArr[0].medCode;
                break;
              }
            }
            this.setState({ OrdDaRowId: id })
          } else {
            this.setState({ OrdDaRowId: oneArr[0].medCode })
          }
          break;
        case 40: //下
          if (this.state.OrdDaRowId) {
            for (let i = 0; i < oneArr.length; i++) {
              oneArr[i].disblock = false
              if (oneArr[i].medCode === this.state.OrdDaRowId) {
                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].medCode : oneArr[i + 1].medCode;
                break;
              }
            }
            this.setState({ OrdDaRowId: id })
          } else {
            this.setState({ OrdDaRowId: oneArr[0].medID })
          }
          break;
      }
    }

    //输入名车回车/失去焦点自动生成别名
    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)
          }
        }
      })
    }

    handleLoadUsage(name, index, data, e) {
      var params = {
        params: [{
          medID: data.medID,
          hospID: this.state.userData.hospID
        }]
      }
      $http.post('urlDeault', this, {
        code: "01040065",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            this.state.rightData[index]['usageList'] = res.data
            this.setState({})
          }
        }
      });
    }

    onBlurFreqSelect(name, index, data, e) {
      var params = {
        params: [{
          hospID: this.state.userData.hospID
        }]
      }
      $http.post('urlDeault', this, {
        code: "03050143",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            this.state.rightData[index]['frequenceList'] = res.result
            this.setState({})
          }
        }
      });
    }

    changeCheckBox(name, index, e) {
      this.state.rightData[index][name] = e.target.checked ? 'Y' : 'N'
      this.state.rightData[index]['defaultStatus'] = ''
      this.setState({})
    }

    //公共下拉事件
    handleChangeSelect(name, data, index, e, option) {
      this.state.rightData[index][name] = e
      this.state.rightData[index]['ordNewQty'] = ''
      this.state.rightData[index]['defaultStatus'] = ''
      this.state.rightData[index]['frequency'] = option.props.frequency ? option.props.frequency : this.state.rightData[index].frequency
      this.state.rightData[index]['cycleDays'] = option.props.cycleDays ? option.props.cycleDays : this.state.rightData[index].cycleDays
      this.state.rightData[index]['intervalDays'] = option.props.intervalDays ? option.props.intervalDays : this.state.rightData[index].intervalDays
      this.state.rightData[index]['duraFactor'] = option.props.duraFactor ? option.props.duraFactor : this.state.rightData[index].duraFactor
      this.state.rightData[index]['doseDenominator'] = option.props.doseDenominator ? option.props.doseDenominator : this.state.rightData[index].doseDenominator
      this.state.rightData[index]['doseMolecule'] = option.props.doseMolecule ? option.props.doseMolecule : this.state.rightData[index].doseMolecule
      this.state.rightData[index]['qtyMolecule'] = option.props.qtyMolecule ? option.props.qtyMolecule : this.state.rightData[index].qtyMolecule
      this.state.rightData[index]['qtyDenominator'] = option.props.qtyDenominator ? option.props.qtyDenominator : this.state.rightData[index].qtyDenominator
      this.setState({})
    }

    commonInput(name, index, data, e) {
      this.state.rightData[index][name] = e
      this.state.rightData[index]['ordNewQty'] = ''
      this.state.rightData[index]['defaultStatus'] = ''
      this.setState({})
    }

    changeBodyPartRadio(name, index, data, e, option) {
      var priceMsg = []
      this.state.rightData[index][name] = [e]
      priceMsg.push(option.props.ordprice)
      this.state.rightData[index]['ordTempletDetailItemPrice'] = option.props.ordprice
      this.setState({})
    }

    //部位
    changeBodyPartSelect(name, index, data, e, option) {
      var priceMsg = []
      var priceData = []
      if (!Util.isEmpty(option)) {
        for (var i = 0; i < option.length; i++) {
          //眼部互斥
          if (option[i].props.mutexflag == 'Y') {
            this.state.rightData[index]['ordbodyPartID'] = [option[i].props.value]
            if (data.ordbodyPartID[0] == option[i].props.value) {
              this.state.rightData[index]['ordbodyPartID'] = [option[i].props.partid]
              priceMsg.push(option[i].props.ordprice)
              this.state.rightData[index]['ordTempletDetailItemPrice'] = option[i].props.ordprice
              this.state.rightData[index]['defaultStatus'] = ''
              this.state.rightData[index]['ordNewQty'] = ''
            }
          } else {
            priceData.push(option[i].props.ordprice)
            this.state.rightData[index]['ordbodyPartID'] = e
            this.state.rightData[index]['priceData'] = priceData
            this.state.rightData[index]['defaultStatus'] = ''
            this.state.rightData[index]['ordNewQty'] = ''
          }
        }
      } else {
        this.state.rightData[index]['ordbodyPartID'] = e
        this.state.rightData[index]['defaultStatus'] = ''
        this.state.rightData[index]['ordNewQty'] = ''
      }
      this.setState({})
    }

    handleChangeInput(name, data, index, e) {
      this.state.rightData[index]['ordNewQty'] = e.target.value
      this.state.rightData[index][name] = e.target.value
      this.state.rightData[index]['defaultStatus'] = true
      this.setState({})
    }

    onColumnRef = (ref) => {
      this.columnRef = ref;
    }

    // 排序
    handleSort = (record, e) => {
      React.$stopPropagation(e);
      let columns = this.columns.slice(1, this.columns.length - 1);
      this.sortRef && this.sortRef.modifyVisible(true, {
        tableData: record?.children || [],
        columns,
        totalWidth: 630,
        saveCode: '03020074',
        recordIdIndex: 'ordTempletID',
        modalTitle: (record?.templetCatDesc || '') + '医嘱模板排序', // 弹窗title
        interfaceParams: {
          templetCatID: record?.templetCatID || '',
          type: 'M', // 医嘱套餐（西药及其他） 【 X-西药及其他 Z-中草药 M-医嘱模板 DM-诊断模板 】
        }
      })
    }

    render() {
      const { getFieldDecorator } = this.props.form;
      let { ordTempletDesc, ordTempletAlias, ordTempletCat, ordShow, baseOrdTepCat, baseTempType, baseUnit, tempChildDis, OrdDaShow, searchLoading } = this.state
      let ordtype = []
      baseOrdTepCat && baseOrdTepCat.map(item => {
        ordtype.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} 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} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
      })

      //右侧查询医嘱项明细表
      const OrdDaColumns = [
        {
          align: 'center',
          title: '编码',
          dataIndex: 'medCode',
          key: '1'
        },
        {
          align: 'center',
          title: '名称*规格',
          dataIndex: 'medDesc',
          key: '2'
        },
        {
          align: 'center',
          title: '大类',
          dataIndex: 'medCatDesc',
          key: '3'
        },
        {
          align: 'center',
          title: '子类',
          dataIndex: 'medSubCatDesc',
          key: '4'
        }, {
          align: 'center',
          title: '商品名',
          dataIndex: 'tradeName',
          key: '42'
        },
        // {
        //   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 (
        <Spin spinning={this.state.loading} tip='加载中...'>
          <div className='person-temp-body'>
            <ColumnAuthoritysModel
              clientWidth='800px'
              compontName="DepartmentTemplate"
              configType="C"
              onRef={this.onColumnRef}
              reloadData={this.initColumnData.bind(this)}
            />
            <Row gutter={60}>
              <Col span={8} >
                <Card title="医嘱模板列表" style={{ marginRight: '4px' }} className="moreInfoCard">
                  <Row>
                    <Col span={16} style={{ marginRight: '10px' }}>
                      <FormItem>
                        {getFieldDecorator('info', {
                          initialValue: undefined,
                        })(
                          <Input allowClear placeholder="输入模板或套餐名称/别名回车查询" onPressEnter={this.handleQuery} autoFocus />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={2}>
                      <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>
                  </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}
                      rowClassName={this.setRowClassName}
                      onRow={this.onClickRow}
                      rowKey={record => record.key}
                      locale={{ emptyText: this.state.findInfo }}
                      scroll={{ x: 710, y: store.getState().tableHeight.y - 24 }}
                      expandedRowKeys={this.state.newOpen}
                      onExpand={this.openExpand}
                      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}>
                <Card
                  title="医嘱模板及明细项维护"
                  className="moreInfoCard"
                >
                  <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" />新增</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 onClick={this.handleSave} size="small" type="primary" style={{ marginRight: '10px' }}><Icon type="printer" />保存</Button>
                    </Row>
                    <div className="table-body-height">
                      <Table
                        bordered
                        className="clearBackground"
                        columns={this.state.dynColumns}
                        pagination={false}
                        scroll={{ x: 1400, y: store.getState().tableHeight.y - 34 }}
                        rowClassName={this.setRowClassNames}
                        onRow={this.onClickRightRow}
                        rowKey={record => record.keys}
                        dataSource={this.state.rightData}
                        rowSelection={rowSelection_right}
                        onHeaderRow={column => {
                          return {
                            onDoubleClick: () => {
                              this.columnRef.onOpenModel();
                            },
                          };
                        }}
                      />
                    </div>
                  </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} maxLength={30} placeholder="不能超过30字" />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label='类型' wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                        {getFieldDecorator('docMesType', {
                          initialValue: undefined,
                          rules: [{ required: true, message: '' }],
                        })(
                          <Select showSearch optionFilterProp="role" 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>
                </Form>
              </div>
            </Modal>

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