/*
 * Creater:     柿子
 * CreateDate:  2022/06/02
 * Describe：   发药（新）
 * */
import React from 'react';
import { Card, Row, Col, Select, Button, Input, DatePicker, Switch, Modal, Table, Checkbox, Icon, Form, message, Spin, Progress } from 'antd';
import store from 'store';
import Moment from 'moment';
import { Util } from 'tools';
import { $http } from 'containers/config/https';
import { $PrintPresc, $PrintLabel, $PrintPYD } from './common/Print';
import PubilcTablePagination from './../../common/PubilcTablePagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import RejectPrescription from './RejectPrescription.jsx'; // 审核拒绝
import FaceRecognitionAuto from 'pages/common/FaceRecognitionAuto';
import ReadCard from 'components/readcard/ReadCard';
import iconMedicine from 'assets/images/icon_medicine.png';
import iconListvisits from 'assets/images/icon_listvisits.png';
import './style/outpha.less';

const { Option } = Select;
let buttonStatus = true;

let timer = null;
let voiceTimer = null;

class NewDispensing extends React.Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      statusSelectData: [], // 审核状态下拉框数据
      startDate: Moment(), // 开始日期
      endDate: Moment(), // 截止日期
      fyFlag: undefined, // 发药标志
      patID: '', // 病人Id
      pat: '', // 回车保存的病人id
      patNo: undefined, // 病人
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 100,
      rowId: '', // 选中行标识 --- 发药列表
      rowData: {}, // 选中行对象 --- 发药列表
      basicHeight: 0,
      detailData: [],
      pharmacistVisible: false, // 选中配药师弹窗
      dispensingChecked: false, // 直接发药
      windowVisible: false, // 选中窗口
      windowDomData: [],
      LTrowId: '', // 左侧列表选中标识 --- 待发药
      LTrowData: {}, // 选中行对象 --- 待发药
      usageTableData: [], // 选药列表数据
      selectedRowKeys: [],
      selectedRows: [],
      unfoldTableData: {}, // 点击显示table的行数据
      radioWindowData: {}, // 选中一条发药窗口数据
      parameterSetting: {}, // 3.2.1.6.10.取发药参数设置
      PharmacistSelectData: [], // 配药师下拉框数据
      pharmacistValue: undefined, // 配药师
      defaultValue: '', // 默认卡类型
      cardSlectData: [], // 卡类型下拉框数据
      cardType: undefined, // 卡类型
      cardNo: undefined, // 卡号
      LTpatID: '', // 选中行病人id
      // checkedObj: {}, // 选中窗口
      loading: false,
      columns: [],
      widthTotal: 0,
      detailColumns: [], // 待发药
      detailWidthTotal: 0,
      authorityStatus: false,
      FRAVisible: false,
      audioUrl: "",
      voiceTimer: false,
      dispDetailColumns: [], // 药品明细表头数据
      dispDetailTableData: [], // 药品明细列表
      dispDetailLoading: false,
      disDetailWidthTotal: 2600,
      fullLoading: false,
      detailRowID: '',
      percentCount: 0
    };
    this.columns = [
      { title: '病人ID', dataIndex: 'patNo', key: '1', width: '100px', align: "center" },
      { title: '患者', dataIndex: 'patName', key: '2', width: '100px', align: "center" },
      { title: '处方号', dataIndex: 'ordPrescNo', key: '3', width: '150px', align: "center" },
      { title: '收费日期', dataIndex: 'dateTime', key: '4', width: '150px', align: "center" },
    ];
    this.detailColumns = [
      { title: '序号', dataIndex: 'key', key: '1', width: '80px', align: "center" },
      { title: '性名', dataIndex: 'patName', key: '2', align: "center" },
    ];
    this.usageColumns = [
      { title: '执行时间', dataIndex: 'time', key: '1', width: '50%', align: "center" },
      { title: '数量', dataIndex: 'num', key: '2', align: "center" },
    ];
    this.dispDetailColumns = [{
      title: '药品代码', dataIndex: 'stockCode', key: '1', width: '100px', align: "center"
    }, {
      title: '药品名称', dataIndex: 'stockDesc', key: '2', width: '300px', align: "center"
    }, {
      title: '药品规格', dataIndex: 'stockSpec', key: '3', width: '200px', align: "center"
    }, {
      title: '用法', dataIndex: 'ordUsageDesc', key: '4', width: '100px', align: "center"
    }, {
      title: '频次', dataIndex: 'ordFreqDesc', key: '5', width: '100px', align: "center"
    }, {
      title: '剂量', dataIndex: 'ordDoseUnitDesc', key: '6', width: '100px', align: "center"
    }, {
      title: '疗程', dataIndex: 'ordDurationDesc', key: '7', width: '100px', align: "center"
    }, {
      title: '医嘱备注', dataIndex: 'ordNote', key: '8', width: '100px', align: "center"
    }, {
      title: '数量', dataIndex: 'qty', key: '9', width: '100px', align: "center"
    }, {
      title: '单位', dataIndex: 'baseUnitDesc', key: '10', width: '100px', align: "center"
    }, {
      title: '单价', dataIndex: 'sp', key: '11', width: '100px', align: "center"
    }, {
      title: '金额', dataIndex: 'spAmt', key: '12', width: '100px', align: "center"
    }, {
      title: '批号', dataIndex: 'batchNo', key: '13', width: '100px', align: "center"
    }, {
      title: '有效期', dataIndex: 'expDate', key: '14', width: '100px', align: "center"
    }, {
      title: '厂家', dataIndex: 'manfDesc', key: '15', width: '300px', align: "center"
    }, {
      title: '批准文号', dataIndex: 'approvalNo', key: '16', width: '100px', align: "center"
    }, {
      title: '供应商', dataIndex: 'vendorDesc', key: '17', width: '300px', align: "center"
    }, {
      title: '医生', dataIndex: 'ordDoctor', key: '18', width: '100px', align: "center"
    }, {
      title: '医嘱状态', dataIndex: 'ordStatus', key: '19', width: '100px', align: "center"
    }]
    this.myRef1 = React.createRef();
    this.percentTimer = null;
    this.processTimer = null;
  }

  componentDidMount() {
    this.getPharmacyWindowData("start");
    this.getSelectData();
    this.getCardSelectData();
    this.getParameterSetting();
    this.getOutpatientWaitingList(); // 获取待发药表头数据
    this.getMainTableColumns(); // 获取发药列表表头数据
    this.getDispDetailColumns();
    this.getPharmacistSelectData();
    this.setState({ basicHeight: document.getElementById("outpha-dispensing-basic").clientHeight });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    clearInterval(timer);
    clearInterval(voiceTimer);
    clearInterval(this.percentTimer);
    clearInterval(this.processTimer);
    this.setState = (state, callback) => { return; }
  }

  //判断医生有没有审核权限
  authorityManagement = () => {
    let data = {
      params: [{
        userID: this.state.userData.userID,
        locID: this.state.userData.locID,
        authDesc: 'DispAuth'
      }]
    }
    $http.post('urlS', this, {
      code: "02030082",
      data: data,
      success: function (res) {
        if (+res.errorCode == '02010015') {
          // message.error(res.errorMessage);
          this.setState({ authorityStatus: true })
        } else {
          this.setState({ authorityStatus: false })
        }
      }
    })
  };

  // 获取数据列表columns
  getMainTableColumns = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: "DrugDistribution",
        reactCode: ['DrugDistribution'],
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
            return {
              ...item,
              key: index + 1,
              title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({
            columns: filterArr, widthTotal: res.totalWidth,
            localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          })
        }
      }
    })
  }

  // 获取药品明细表头数据
  getDispDetailColumns = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: "NewDispensingDetail",
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
            return {
              ...item,
              key: index + 1,
              title: <div onDoubleClick={() => this.dispDetailRef?.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({
            dispDetailColumns: filterArr,
            disDetailWidthTotal: res.totalWidth
          })
        }
      }
    })
  }

  onMainColumnRef = (ref) => {
    this.mainColumnRef = ref;
  }

  //国际化
  setMessage = (name, message, defaultTitle) => {
    return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
  }

  // 获取门诊发药待发药列头
  getOutpatientWaitingList = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: "OutpatientWaitingList",
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
            return {
              ...item,
              key: index + 1,
              title: <div onDoubleClick={() => this.detailColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({ detailColumns: filterArr, detailWidthTotal: res.totalWidth })
        }
      }
    })
  }

  onDetailColumnRef = (ref) => {
    this.detailColumnRef = ref;
  }

  // 3.2.1.6.10.取发药 参数设置
  getParameterSetting = () => {
    let { userData } = this.state;
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02030044",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let directDispFlag = res.result && res.result.length ? res.result[0].directDispFlag : 0;
          this.setState({
            parameterSetting: res.result[0],
            startDate: res.result[0].startDate ? Moment(res.result[0].startDate) : Moment(),
            endDate: res.result[0].endDate ? Moment(res.result[0].endDate) : Moment(),
            dispensingChecked: +directDispFlag === 1 ? true : false,
            mode: +directDispFlag === 1 ? 2 : 1,
            pharmacistValue: +directDispFlag === 1 ? (userData && userData.userID ? userData.userID : undefined) : undefined,
          })
        }
      }
    })
  }

  // 获取取药窗口信息
  getPharmacyWindowData = (flag) => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02030035",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result[0] && res.result[0].rows && JSON.parse(JSON.stringify(res.result[0].rows)).map((item, index) => {
            return {
              key: index + 1,
              checked: false,
              disabled: false,
              dispWinDesc: item.dispWinDesc, // 发药窗口描述
              dispWinID: item.dispWinID, // 发药窗口ID
              statusID: item.statusID, // 状态ID
              statusDesc: item.statusDesc, // 状态描述
              prescNum: item.prescNum, // 窗口数量
            }
          })
          if (this.state.radioWindowData && this.state.radioWindowData.dispWinID) {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].dispWinID === this.state.radioWindowData.dispWinID) {
                arr[i].checked = this.state.radioWindowData.checked;
              }
            }
          }
          this.setState({ windowDomData: arr }, () => {
            if (flag === "start") {
              this.showModal("window")
            }
          })
        }
      }
    })
  }

  filterDspInfo = (data) => {
    let rowsData = data[0].rows;
    let obj = {};
    let batInfo = [];
    let filterBatInfo = [];
    for (var i = 0; i < rowsData.length; i++) {
      batInfo = batInfo.concat(rowsData[i].batInfo)
    }
    for (var i = 0; i < batInfo.length; i++) {
      if (!obj[batInfo[i].batNo]) {
        obj[batInfo[i].batNo] = batInfo[i].batNo;
        filterBatInfo.push(batInfo[i]);
      } else {
        for (var j = 0; j < filterBatInfo.length; j++) {
          if (filterBatInfo[j].batNo === batInfo[i].batNo) {
            filterBatInfo[j].qty += batInfo[i].qty;
          }
        }
      }
    }
    let dspInfo = [];
    rowsData[0].batInfo = filterBatInfo
    let batInfoObj = {
      rows: rowsData
    }
    dspInfo.push(batInfoObj);
    return dspInfo
  }

  // 3.2.1.6.6.获取发药明细信息
  getDetailInformation = (record) => {
    this.setState({ dispDetailLoading: true })
    let data = {
      params: [{
        dispID: record.dispID ? record.dispID : '', // 发药表ID
        ordPrescNo: record.ordPrescNo ? record.ordPrescNo : '', // 处方号
      }]
    }
    $http.post('urlS', this, {
      code: "02030072",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let dispDetailTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
          this.setState({
            dispDetailTableData,
            detailRowID: '',
            dispDetailLoading: false
          })
        } else {
          this.setState({ dispDetailTableData: [], dispDetailLoading: false, detailRowID: '' })
        }
      }
    })
  }

  // 3.2.1.6.4.获取发药 等候队列
  getMedicationWaitingQueue = () => {
    let { mode, startDate, endDate, radioWindowData, fyFlag } = this.state;
    let data = {
      params: [
        {
          mode: mode ? mode : 1, // 发药模式
          fyFlag: fyFlag, // 发药标志
          dispWinID: radioWindowData && radioWindowData.dispWinID ? radioWindowData.dispWinID : undefined, // 发药窗口ID
          startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 开始日期
          endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 截止日期
        }
      ]
    }
    $http.post('urlS', this, {
      code: "02030038",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          for (var i = 0; i < res.result[0].rows.length; i++) {
            res.result[0].rows[i].key = res.result[0].rows[i].patID
          }
          let arr = res.result[0].rows;
          if (JSON.stringify(arr) !== JSON.stringify(this.state.detailData)) {
            this.setState({ detailData: arr }, () => {
              // this.handleFYClick("dfy-list");
            })
          }
        }
      }
    })
  }

  getTableData = (mode, startDate, endDate, fyFlag, patID, isVoice) => {
    this.setState({ loading: true });
    let { pageSize, page, radioWindowData, LTpatID, patNo } = this.state;
    let data = {
      params: [{
        mode: mode ? mode : 1, // 发药模式
        dispWinID: radioWindowData && radioWindowData.dispWinID ? radioWindowData.dispWinID : undefined, // 发药窗口ID
        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 开始日期
        endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 截止日期
        fyFlag: fyFlag, // 发药标志
        patID: LTpatID ? LTpatID : (this.isNumber(patNo) ? patID : ""), // 病人ID
        patName: patNo,
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page
      }]
    }
    setTimeout(() => {
      var gundong = document.querySelector("#fy-list .ant-table-body");
      gundong.scrollTop = 0;
    }, 100)
    $http.post('urlS', this, {
      code: "02030039",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          let arr = res.result[0].rows ? res.result[0].rows : []
          for (var i = 0; i < arr.length; i++) {
            arr[i].key = i + 1;
            arr[i].dateTime = arr[i].date + ' ' + arr[i].time
          }
          let rowData = arr && arr.length > 0 ? arr[0] : {};
          let audioUrl = isVoice === 'voice' && fyFlag === "0" && arr && arr.length > 0 ? "https://chis.e24health.com/images/Voice/dispWarnning.mp3" : ""; // 是否为语言播报查询
          this.setState({ tableData: arr, total: res.result[0].total, rowId: rowData && rowData.key ? rowData.key : "", rowData, audioUrl, loading: false }, () => {
            if (this.state.rowId) {
              this.getDetailInformation(this.state.rowData);
              // this.handleFYClick("fy-list");
            }
            if (this.state.audioUrl) {
              var myAuto = document.getElementById('a_player_audio');
              myAuto.play();
            }
            setTimeout(() => {
              this.myRef1 && this.myRef1.current && this.myRef1.current.focus();
            }, 300)
          })
        } else {
          this.setState({ tableData: [], total: 0, rowId: "", rowData: {}, audioUrl: '', loading: false })
          setTimeout(() => {
            this.myRef1 && this.myRef1.current && this.myRef1.current.focus();
          }, 300)
        }
      },
      error: function (error) {
        this.setState({ tableData: [], total: 0, rowId: "", rowData: {}, audioUrl: '', loading: false }, () => {
          setTimeout(() => {
            this.myRef1 && this.myRef1.current && this.myRef1.current.focus();
          }, 300)
        })
      }
    })
  }

  // 重置操作数据
  resetData = () => {
    this.setState({ rowId: '', rowData: {}, dispDetailTableData: [], detailRowID: '' });
    this.getMedicationWaitingQueue(); // 重新查询待发药列表
  }

  // 获取表格数据
  handleQuery = () => {
    setTimeout(() => {
      this.setState({ page: 1, rowId: '', rowData: {}, LTrowId: '', LTpatID: '', dispDetailTableData: [], detailRowID: '' }, () => {
        this.refreshTableData();
        this.getMedicationWaitingQueue();
      })
    }, 300)
  }

  // 按照输入条件重新查询数据
  refreshTableData = (isVoice) => {
    let { mode, startDate, endDate, fyFlag, patID } = this.state;
    this.getTableData(mode, startDate, endDate, fyFlag, patID, isVoice)
  }


  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    // 修改page，或者pageSize
    this.setState({ page: page, pageSize: pageSize }, () => {
      // 重新调用查询方法
      this.refreshTableData();
    })
  }

  onModalRef = (ref) => {
    this.modalChild = ref;
  }

  // 操作行 --- 左侧列表待发药
  onClickRowLeftTable = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.LTrowId === '') {
          // 保存行数据以及ID
          this.setState({ LTrowId: record.key, LTpatID: record.patID, page: 1, rowId: '', rowData: {}, dispDetailTableData: [], detailRowID: '', patNo: undefined }, () => {
            this.refreshTableData();
          })
        } else {
          if (this.state.LTrowId !== record.key) {
            this.setState({ LTrowId: record.key, LTpatID: record.patID, page: 1, rowId: '', rowData: {}, dispDetailTableData: [], detailRowID: '', patNo: undefined }, () => {
              this.refreshTableData();
            })
          }
        }
      }
    }
  }

  // 选中行操作 --- 左侧列表
  setRowClassNameLeftTable = (record) => {
    return record.key === this.state.LTrowId ? 'clickRowStyle' : '';
  }

  // 操作行 --- 发药列表
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowId === '') {
          // 保存行数据以及ID
          this.setState({ rowId: record.key, rowData: record }, () => {
            this.getDetailInformation(this.state.rowData)
          })
        } else {
          if (this.state.rowId !== record.key) {
            this.setState({ rowId: record.key, rowData: record }, () => {
              this.getDetailInformation(this.state.rowData)
            })
          }
        }
      }
    }
  }

  // 选中行操作 --- 发药列表
  setRowClassNamePublic = (record) => {
    return (record.dispStatus === "Y") && (record.key === this.state.rowId) ? "select-and-row" : (record.dispStatus === "Y" ? "select-color" : (record.key === this.state.rowId ? 'clickRowStyle' : ""));
  }

  // 直接发药模式
  onClickSwitch = () => {
    if (!this.state.dispensingChecked) {
      this.showModal('pharmacist')
    } else {
      this.setState({ dispensingChecked: false, pharmacistValue: undefined, mode: 1 }, () => {
        this.refreshTableData(); // 发药列表
        this.resetData(); // 重置操作数据以及刷新待发药列表
      })
    }
  }

  // 切换窗口
  switchingWindow = () => {
    this.setState({
      windowVisible: true,
    }, () => {
      this.getPharmacyWindowData();
    });
  }

  // 打开弹窗
  showModal = (flag) => {
    if (flag === 'pharmacist') {
      this.setState({
        pharmacistVisible: true,
      });
    } else if (flag === 'window') {
      let { windowDomData } = this.state;
      if (windowDomData && windowDomData.length === 1) { // 如果窗口数等于1的话直接默认为当前窗口
        let arr = JSON.parse(JSON.stringify(windowDomData));
        arr[0].checked = true;
        this.setState({ windowDomData: arr }, () => {
          this.windowHandleOk();
        })
      } else {
        this.setState({
          windowVisible: true,
        });
      }
    }

  };

  // 选择配药师弹窗 --- 确定
  pharmacistHandleOk = () => {
    // 当选择配药师之后直接发药模式变成是并且关闭选择模态框
    if (this.state.pharmacistValue) {
      // 点击确定并且成功之后将开关切换为是并且关闭弹窗
      this.setState({ dispensingChecked: true, mode: 2 }, () => {
        this.handleCancel('pharmacist');
        this.handleQuery();
      })
    } else {
      message.info(this.setMessage("DrugDistributionpleaseSelectPharmacist", "descripts", "请选择配药师"), this.state.userData && this.state.userData.messageTime)
    }
  };

  // 切换窗口 --- 确定
  windowHandleOk = () => {
    let messageTrue = true;
    let obj = {};
    let windowDomData = JSON.parse(JSON.stringify(this.state.windowDomData));
    if (windowDomData && windowDomData.length > 0) {
      for (let i = 0; i < windowDomData.length; i++) {
        if (windowDomData[i].checked == true) {
          messageTrue = true
          obj = windowDomData[i];
          break;
        } else {
          messageTrue = false
        }
      }
    }
    // console.log(arr)
    if (messageTrue === false) {
      message.error(this.setMessage("DrugDistributionpleaseSelectDrugDispensingWin", "descripts", "请选择发药窗口"))
    } else {
      this.authorityManagement();
      this.setState({ radioWindowData: obj }, () => {
        let date = this.state.parameterSetting.refreshTime ? this.state.parameterSetting.refreshTime * 1000 : 10 * 1000; // 将秒转为毫秒
        // console.log(date)
        timer = setInterval(() => {
          this.getMedicationWaitingQueue();
        }, date);
        this.handleQuery();
        this.handleCancel('window');
      })
    }
  }

  // 关闭弹窗
  handleCancel = (flag) => {
    if (flag === 'pharmacist') {// 关闭直接发药模式刷新待发药、发药列表、处方笺三栏的数据
      this.setState({
        pharmacistVisible: false,
      });
    } else if (flag === 'window') {
      if (this.state.radioWindowData && this.state.radioWindowData.dispWinID) {
        let windowDomData = JSON.parse(JSON.stringify(this.state.windowDomData));
        let index;
        for (var i = 0; i < windowDomData.length; i++) {
          windowDomData[i].checked = false;
          if (windowDomData[i].dispWinID === this.state.radioWindowData.dispWinID) {
            index = i;
          }
        }
        windowDomData[index].checked = this.state.radioWindowData.checked;
        this.setState({
          windowVisible: false,
          windowDomData
        }, () => {
          setTimeout(() => {
            this.myRef1.current.focus();
          }, 300)
        });
      } else {
        message.error(this.setMessage("DrugDistributionpleaseSelectDrugDispensingWin", "descripts", "请选择发药窗口"), this.state.userData && this.state.userData.messageTime)
      }
    }
  };

  // Checkbox的onChange事件
  compileChecked = (item, index) => {
    let windowDomData = [...this.state.windowDomData];
    for (var i = 0; i < windowDomData.length; i++) {
      let indexChecked = windowDomData[index].checked;
      windowDomData[i].checked = false;
      windowDomData[index].checked = indexChecked;
      if (windowDomData[i] === item) {
        windowDomData[i].checked = !windowDomData[i].checked;
      }
    }
    this.setState({ windowDomData: windowDomData })
  }

  // 修改发药窗口状态
  compileWindowStatus = (item, status) => {
    let data = {
      params: [
        {
          dispWinID: item.dispWinID,
          statusID: status,
        }
      ]
    }
    $http.post('urlS', this, {
      code: "02030036",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage, this.state.userData && this.state.userData.messageTime)
        } else {
          message.error(res.errorMessage, this.state.userData && this.state.userData.messageTime)
        }
      }
    })
  }

  // 修改弹窗中的有人无人
  handleSwitch = (item, e) => {
    let windowDomData = [...this.state.windowDomData];
    let status = e ? 'O' : 'C';
    for (var i = 0; i < windowDomData.length; i++) {
      if (windowDomData[i] === item) {
        windowDomData[i].statusID = status;
      }
    }
    this.setState({ windowDomData: windowDomData }, () => {
      this.compileWindowStatus(item, status)
    });
  }

  // 查询条件 --- 开始日期
  handleStartDate = (e) => {
    this.setState({ startDate: e });
  }

  // 查询条件 --- 截止日期
  handleEndDate = (e) => {
    this.setState({ endDate: e });
  }

  // 查询条件 --- 审核状态
  handlestatusID = (e) => {
    this.setState({ fyFlag: e });
  }

  // 选择配药师
  handlePharmacistValue = (e, flag) => {
    if (flag) {
      if (this.state.dispensingChecked) {
        this.setState({ pharmacistValue: e });
      } else {
        message.info("直接发药模式下才支持选择配药师。", this.state.userData && this.state.userData.messageTime)
      }
    } else {
      this.setState({ pharmacistValue: e });
    }
  }

  // 3.2.1.6.3.取发药状态下拉框数据集
  getSelectData = () => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02030037",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          this.setState({ statusSelectData: res.result, fyFlag: res.result[0].id })
        } else {
          this.setState({ statusSelectData: [] })
        }
      }
    })
  }

  // 病人id
  handlePatientOnChange = (e) => {
    if (!e.target.value) {
      setTimeout(() => {
        this.setState({ patID: '' })
      }, 500);
    }
    this.setState({ patNo: e.target.value })
  }

  // 病人id失去焦点事件
  handlePatientOnBlur = (e) => {
    if (e.target.value !== this.state.pat) {
      this.setState({ patNo: undefined, patID: '', pat: '' })
    }
  }

  isNumber = (val) => {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
      return true;
    } else {
      return false;
    }
  }

  // 查询病人id
  handlePatient = (e, name) => {
    if (!e.target.value) {
      this.setState({ patID: '' })
      return;
    }
    if (this.isNumber(e.target.value)) {
      this.setState({ cardNo: undefined, cardType: this.state.defaultValue }, () => {
        this.getPatientInformation('patient', name);
      })
    } else {
      this.setState({ LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '', patID: "" }, () => {
        this.refreshTableData();
      })
    }
  }

  // 修改该条已发药数据的状态
  modifyDispStatus = (rowData) => {
    let tableData = JSON.parse(JSON.stringify(this.state.tableData));
    for (var i = 0; i < tableData.length; i++) {
      if (tableData[i].key === rowData.key) {
        tableData[i].dispStatus = "Y";
        break;
      }
    }
    this.setState({ tableData, rowData: {}, rowId: "" })
  }

  // 获取配药师下拉框数据
  getPharmacistSelectData = () => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02030119",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ PharmacistSelectData: res.result })
        } else {
          this.setState({ PharmacistSelectData: [] })
        }
      }
    })
  }

  // 卡号
  handleCardNoChange = (e) => {
    if (!e.target.value) {
      setTimeout(() => {
        this.setState({ patID: '' })
      }, 500);
    }
    this.setState({ cardNo: e.target.value })
  }

  // 卡类型
  handleCardTypeOnChange = (e) => {
    this.setState({ cardType: e })
  }

  // 读卡 --- 根据卡号取病人信息
  handleReadCard = () => {
    if (!buttonStatus) {
      return;
    }
    let { cardType } = this.state;
    this.readCard.ReadCard(cardType, "R", (json) => {
      this.setState({ patID: json && json.patInfo ? json.patInfo.patID : 'aaaaa', patNo: json && json.patInfo ? json.patInfo.patNo : '', cardNo: json.cardNo }, () => {
        this.refreshTableData(); // 调取查询接口
      })
    })
  }

  handleReadCardOnBlur = (e, name) => {
    if (!e.target.value) {
      this.setState({ patID: '' })
      return;
    }
    if (name === 'blur') {
      buttonStatus = false;
      this.setState({ patNo: undefined }, () => {
        this.getPatientInformation('readCard', name);
      })
    } else {
      this.setState({ patNo: undefined, LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '' }, () => {
        this.getPatientInformation('readCard', name);
      })
    }
  }

  // 获取卡类型下拉框数据
  getCardSelectData = () => {
    let data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: '02030052',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let defaultValue = '';
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].defaultFlag === 'Y') {
              defaultValue = res.result[i].id;
            }
          }
          this.setState({ cardSlectData: res.result, cardType: defaultValue, defaultValue: defaultValue })
        }
      }
    })
  }

  // 3.2.1.3.13.根据卡号取病人信息
  getPatientInformation = (flag, name) => {
    let data = {
      params: [{
        number: this.state.patNo, // 病人登记号/证件号
        cardTypeID: flag === 'readCard' ? this.state.cardType : undefined, // 卡类型id
        cardNo: this.state.cardNo, // 卡号
      }]
    }
    setTimeout(() => {
      buttonStatus = true;
    }, 500)
    $http.post('urlS', this, {
      code: '03040004',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let cardNo = flag === "readCard" && res.data && res.data.patCardNo ? res.data.patCardNo : undefined; // 给卡号赋值
          // patNo: res.data && res.data.patNo ? res.data.patNo : '', 病人ID赋值-自动补零
          this.setState({ patID: res.data && res.data.patID ? res.data.patID : '', patNo: res.data && res.data.patNo ? res.data.patNo : '', cardNo }, () => {
            if (name === 'enter') {
              this.refreshTableData()
            }
          })
        } else if (res.errorFlag === 'N') {
          this.setState({ tableData: [], total: 0, patID: 'aaaaa', LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '', patNo: undefined })
          message.error(res.errorMessage, this.state.userData && this.state.userData.messageTime)
        } else {
          this.setState({ LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '', patNo: undefined });
        }
      },
      error: function () {
        this.setState({ LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '', patNo: undefined });
      }
    })
  }

  //打印处方
  handlePrintPresc = () => {
    let { rowData } = this.state;
    let params;
    params = {
      dispID: rowData.dispID,
      prescno: rowData.ordPrescNo,
      phFlag: 1,
    }
    $PrintPresc(params);
  }

  //打印标签
  handlePrintLabel = () => {
    let { rowData } = this.state;
    let params;
    params = {
      dispID: rowData.dispID,
      prescno: rowData.ordPrescNo,
      phFlag: 1,
    }
    $PrintLabel(params);
  }

  //打印配药单
  handlePrintPYD = () => {
    let { rowData } = this.state;
    let params;
    params = {
      dispID: rowData.dispID,
      prescno: rowData.ordPrescNo,
      phFlag: 1,
    }
    $PrintPYD(params);
  }

  // 发药公共方法
  dispensingCommon = (rowData, dispDetailTableData, selectedRows, type, index, resolve, rejeck) => {
    let { pharmacistValue, fyFlag, tableData } = this.state;
    let arr = selectedRows && JSON.parse(JSON.stringify(selectedRows)).map(item => {
      return {
        dspID: item.dspID
      }
    })
    let ordInfo = dispDetailTableData && dispDetailTableData.length > 0 && dispDetailTableData.map(item => {
      return {
        ordID: item.ordID,
        dspInfo: arr
      }
    });
    let data = {
      params: [
        {
          dispID: rowData.dispID, // 发药表ID
          ordPrescNo: rowData.ordPrescNo, // 处方号
          PDFlag: fyFlag, // 部分发药标志
          prepUserID: pharmacistValue, // 配药师
          ordInfo: ordInfo, // 医嘱记录
        }
      ]
    }
    $http.post('urlS', this, {
      code: "02030043",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          if (type === "all") {
            resolve && resolve(res, index);
            if (tableData.length - 1 === index) {
              clearInterval(this.percentTimer);
              this.setState({ percentCount: 100, fullLoading: false });
              message.success('一键发药成功', this.state.userData && this.state.userData.messageTime);
            }
          } else {
            message.success('发药成功', this.state.userData && this.state.userData.messageTime);
            this.handleFYClick("fy-list");
          }
          if (tableData.length - 1 === index || type !== "all") { // 发药完触发
            // this.modifyDispStatus(rowData); // 修改当条发药状态
            this.setState({ dispDetailTableData: [], detailRowID: '' }, () => {
              this.getMedicationWaitingQueue(); // 刷新代发药列表
              this.refreshTableData(); // 获取发药列表重新
              setTimeout(() => {
                this.myRef1.current.focus();
              }, 300)
            })
          }
        } else {
          resolve && resolve(res);
          if (type === 'all' && tableData.length - 1 === index) {
            this.setState({ fullLoading: false });
          }
        }
      },
      error: function (error) {
        resolve && resolve(error);
        if (type === 'all' && tableData.length - 1 === index) {
          this.setState({ fullLoading: false });
        }
        message.error(error, this.state.userData && this.state.userData.messageTime);
      }
    })
  }

  // 发药
  handleDispensing = () => {
    let { rowData, dispDetailTableData, selectedRows } = this.state;
    this.dispensingCommon(rowData, dispDetailTableData, selectedRows, 'noneAll')
  }

  // 一键发药
  getDetailInformationAll = async (record, index) => {
    await Promise.resolve(record, index);
    return await new Promise((resolve, rejeck) => {
      setTimeout(async () => {
        try {
          let { selectedRows } = this.state;
          let data = {
            params: [{
              dispID: record.dispID ? record.dispID : '',
              ordPrescNo: record.ordPrescNo ? record.ordPrescNo : '', // 处方号
            }]
          };
          let res = await React.$asyncPost(this, '02030072', data);
          let dispDetailTableData = res.result && 'rows' in res.result ? res.result.rows : [];
          this.dispensingCommon(record, dispDetailTableData, selectedRows, 'all', index, () => resolve(), () => rejeck());
        } catch (error) {
          rejeck(error);
        }
      }, 300)
    });
  }

  // 全发
  // handleFullDose = () => {
  //   let _this = this;
  //   let { tableData } = this.state;
  //   this.setState({ fullLoading: true, percentCount: 0 }, () => {
  //     this.percentTimer = setInterval(() => {
  //       this.setState({ percentCount: this.state.percentCount + 1 });
  //     }, 100);
  //   });
  //   async function run() {
  //     for (let i = 0; i < tableData.length; i++) {
  //       if (tableData[i].ordPrescNo) {
  //         await _this.getDetailInformationAll(tableData[i], i)
  //       }
  //     }
  //   }
  //   run().then((res) => {
  //     console.log(res, '执行完成')
  //   })
  // }

  // 全发
  handleFullDose = async () => {
    try {
      let { tableData, pharmacistValue } = this.state;
      this.setState({ fullLoading: true, percentCount: 0 }, () => {
        this.percentTimer = setInterval(() => {
          let percentCount = this.state.percentCount + 1;
          this.setState({ percentCount: percentCount > 99 ? 99 : percentCount });
        }, 300);
      });
      let ordPrescNoArr = [];
      for (let i = 0; i < tableData.length; i++) {
        if (tableData[i] && 'ordPrescNo' in tableData[i] && tableData[i].ordPrescNo) {
          ordPrescNoArr.push(tableData[i].ordPrescNo)
        }
      }
      let data = {
        params: [{
          prepUserID: pharmacistValue,
          ordPrescNoArr, // 处方号
        }]
      };
      let res = await React.$asyncPost(this, '02020408', data);
      let process = res?.result || ''; // 进程号
      this.processTimer = setInterval(() => {
        this.obtainTheDispensingStatus(process);
      }, 1000 * 2);
    } catch (error) {
      console.log(error);
    }
  }

  // 根据进程号获取发药状态
  obtainTheDispensingStatus = async (process) => {
    try {
      let data = {
        params: [{
          process
        }]
      };
      let res = await React.$asyncPost(this, '02020409', data);
      if (res?.errorCode === '0') {
        let result = res?.result || {};
        if (result?.status === 'Y') { // 一键发药成功
          let errorMsg = result?.message || '';
          this.setState({ percentCount: errorMsg ? 99 : 100 }, () => {
            this.handleClearData();
            errorMsg ? message.error(errorMsg) : message.success(res?.errorMessage || '一键发药成功');
          });
        } else {
          let percentCount = ((result?.rate || 0) * 100) || (this.state.percentCount + 1);
          this.setState({ percentCount: percentCount > 99 ? 99 : percentCount });
        }
      } else {
        this.handleClearData();
      }
    } catch (error) {
      this.handleClearData();
    }
  }

  // 发药成功/失败更新界面数据
  handleClearData = () => {
    this.setState({ dispDetailTableData: [], detailRowID: '', fullLoading: false });
    clearInterval(this.percentTimer);
    clearInterval(this.processTimer);
    this.getMedicationWaitingQueue(); // 刷新代发药列表
    this.refreshTableData(); // 获取发药列表重新
    setTimeout(() => {
      this.myRef1.current.focus();
    }, 300)
  }

  handleDFYOnKeydown = (e) => {
    var e = window.event || e;
    let id = '';
    let obj = {};
    let scroll_height = 32;
    let oneArr = this.state.detailData && this.state.detailData.length > 0 ? this.state.detailData : [];
    switch (e.keyCode) {
      case 38: //上
        if (this.state.LTrowId) {
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.LTrowId) {
              id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
              obj = i > 0 ? oneArr[i - 1] : oneArr[0];
              break;
            }
          }
          this.setState({ LTrowId: id, LTpatID: obj.patID, page: 1, rowId: '', rowData: {} }, () => {
            this.refreshTableData();
          })
          setTimeout(() => {
            var gundong = document.querySelector("#dfy-list .ant-table-body");
            gundong.scrollTop = gundong.scrollTop - scroll_height;
          }, 100)
        } else {
          this.setState({ LTrowId: oneArr[0].key, LTpatID: oneArr[0].patID, page: 1, rowId: '', rowData: {} }, () => {
            this.refreshTableData();
          })
        }
        break;
      case 39: //  右
        if (this.state.tableData && this.state.tableData.length > 0) {
          this.handleFYClick("fy-list")
          this.setState({ rowId: this.state.tableData[0].key, rowData: this.state.tableData[0] }, () => {
            this.getDetailInformation(this.state.rowData)
          })
        }
        break;
      case 40: //下
        if (this.state.LTrowId) {
          for (let i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.LTrowId) {
              id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
              obj = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1] : oneArr[i + 1];
              break;
            }
          }
          this.setState({ LTrowId: id, LTpatID: obj.patID, page: 1, rowId: '', rowData: {} }, () => {
            this.refreshTableData();
          })
          setTimeout(() => {
            var gundong = document.querySelector("#dfy-list .ant-table-body");
            gundong.scrollTop = gundong.scrollTop + scroll_height;
          }, 100)
        } else {
          this.setState({ LTrowId: oneArr[0].key, LTpatID: oneArr[0].patID, page: 1, rowId: '', rowData: {} }, () => {
            this.refreshTableData();
          })
        }
        break;
    }
  }

  handleFYLBOnKeydown = (e) => {
    var e = window.event || e;
    let id = '';
    let obj = {};
    let scroll_height = 32;
    let oneArr = this.state.tableData && this.state.tableData.length > 0 ? this.state.tableData : [];
    switch (e.keyCode) {
      case 13: //  回车发药
        this.handleDispensing();
        break;
      case 37: //  左
        if (this.state.detailData && this.state.detailData.length > 0) {
          this.handleFYClick("dfy-list")
          this.setState({ LTrowId: this.state.LTrowId, LTpatID: this.state.LTpatID, page: 1, rowId: '', rowData: {} })
        }
        break;
      case 38: //上
        if (this.state.rowId) {
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.rowId) {
              id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
              obj = i > 0 ? oneArr[i - 1] : oneArr[0];
              break;
            }
          }
          this.setState({ rowId: id, rowData: obj }, () => {
            this.getDetailInformation(this.state.rowData)
          })
          setTimeout(() => {
            var gundong = document.querySelector("#fy-list .ant-table-body");
            gundong.scrollTop = gundong.scrollTop - scroll_height;
          }, 100)
        } else {
          this.setState({ rowId: oneArr[0].key, rowData: oneArr[0] }, () => {
            this.getDetailInformation(this.state.rowData)
          })
        }
        break;
      case 40: //下
        if (this.state.rowId) {
          for (let i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.rowId) {
              id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
              obj = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1] : oneArr[i + 1];
              break;
            }
          }
          this.setState({ rowId: id, rowData: obj }, () => {
            this.getDetailInformation(this.state.rowData)
          })
          setTimeout(() => {
            var gundong = document.querySelector("#fy-list .ant-table-body");
            // console.log(gundong)
            gundong.scrollTop = gundong.scrollTop + scroll_height;
          }, 100)
        } else {
          this.setState({ rowId: oneArr[0].key, rowData: oneArr[0] }, () => {
            this.getDetailInformation(this.state.rowData)
          })
        }
        break;
    }
  }

  handleFYClick = (id) => {
    let dom = document.getElementById(id);
    dom.focus();
  }

  onFaceRecognitionAutoRefs = ref => {
    this.faceRecognitionAutoChild = ref;
  }

  handleFRAClose = () => {
    this.setState({ FRAVisible: false });
    if (this.faceRecognitionAutoChild) {
      this.faceRecognitionAutoChild.clearVideo()
    }
  }

  handleFRAShowModal = () => {
    this.setState({ FRAVisible: true })
  }

  onSubmit = (data) => {
    this.handleFRAClose();
    console.log(data)
    if (data && data.length > 0) {
      this.setState({ patNo: data[0].patNo, patID: data[0].patID, LTrowId: '', LTpatID: '', page: 1, rowData: {}, rowId: '' }, () => {
        this.refreshTableData();
      })
    }
  }

  // 语音提醒切换
  handleVoiceReminderSwitch = e => {
    this.setState({ voiceReminder: e }, () => {
      if (this.state.voiceReminder) {
        this.timingQueryTableData();
      } else {
        clearInterval(voiceTimer); // 取消语言播报
      }
    })
  }

  // 语音播报 -- 定时查询下拉列表
  timingQueryTableData = () => {
    if (voiceTimer) {
      clearInterval(voiceTimer);
    }
    this.refreshTableData("voice");
    voiceTimer = setInterval(() => {
      this.refreshTableData("voice");
    }, 30000)
  }

  handleDetailClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.ordID))) {
          this.setState({ detailRowID: record.ordID });
        } else {
          this.setState({ detailRowID: '' });
        }
      }
    }
  }

  // 选中行操作 --- 发药列表
  handleDetailSetClassName = (record) => {
    return record.ordID === this.state.detailRowID ? 'clickRowStyle' : '';
  }

  render() {
    let {
      tableData, total, page, basicHeight, windowDomData, fyFlag, startDate, endDate, patNo, PharmacistSelectData, voiceReminder, rowId, rowData, windowVisible, pharmacistVisible, fullLoading,
      dispensingChecked, statusSelectData, detailData, pharmacistValue, radioWindowData, loading, detailWidthTotal, detailColumns, columns, widthTotal, userData, FRAVisible, percentCount,
      dispDetailColumns, dispDetailTableData, dispDetailLoading, disDetailWidthTotal
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? columns : this.columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total: total,
      // 当前页数
      size: 'large',
      page: page,
      pageSize: '100',
      // 表格的宽度
      x: columns && columns.length > 0 ? widthTotal : 500,
      y: (store.getState().tableHeight.y - basicHeight) / 2 - 125,
      height: (store.getState().tableHeight.y - basicHeight) / 2 - 80 + 'px',
      isOnRow: true,
      rowClassName: true,
      loading,
    };

    let detailParam = {
      // 表头配置
      columns: dispDetailColumns && dispDetailColumns.length > 0 ? dispDetailColumns : this.dispDetailColumns,
      // 表格数据
      data: dispDetailTableData,
      // 表格的宽度
      x: disDetailWidthTotal,
      y: (store.getState().tableHeight.y - basicHeight) / 2 + 42,
      height: (store.getState().tableHeight.y - basicHeight) / 2 + 102 + 'px',
      loading: dispDetailLoading
    }

    let windowDom = (
      windowDomData && windowDomData.map((item, index) => {
        return (
          <div key={index} style={{ margin: (index + 1) % 5 == 0 ? '0 0 20px 0' : '0 20px 20px 0' }}>
            <div className="check-box">
              <div className="prep-win-desc" style={{ background: item.checked ? '#1890FF' : '#69C0FF' }}>{item.dispWinDesc}</div>
              <div className="presc-num" style={{ color: item.checked ? '#1890FF' : '#69C0FF' }}>{item.prescNum}</div>
              <span>
                <Checkbox checked={item.checked} onChange={() => this.compileChecked(item, index)} />
              </span>
            </div>
            <Row className="check-row">
              <Switch checkedChildren={this.setMessage("DrugDistributionsomeone", "descripts", "有人")} unCheckedChildren={this.setMessage("DrugDistributionnobody", "descripts", "无人")} checked={item.statusID === 'O' ? true : false} onChange={(e) => this.handleSwitch(item, e)} />
            </Row>
          </div>
        )
      })
    )

    // 审核状态
    let auditStatus = statusSelectData && statusSelectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    // 卡类型
    let cardTypeOption = this.state.cardSlectData && this.state.cardSlectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    let pharmacistSelect = PharmacistSelectData && PharmacistSelectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 提供给拒绝窗口的行数据
    let modalRowData = {
      statusID: 'Before',
      ...rowData
    }

    return (
      <Spin
        tip={(
          <div style={{ textAlign: 'ceter' }}>
            <Progress style={{ width: '240px' }} percent={percentCount} />
            <div>
              {percentCount === 100 ? '发药完成' : '一键发药中…'}
            </div>
          </div>
        )}
        indicator={null}
        spinning={fullLoading}
      >
        <div className="dispensing">
          {/* 语音播报插件 */}
          <div style={{ display: 'node' }}>
            <audio id="a_player_audio" src={this.state.audioUrl}></audio>
          </div>
          <Row
            id="outpha-dispensing-basic"
            className='flex-align-items'
            style={{ padding: '0 12px', height: '66px' }}
          >
            <Col xs={12} sm={12} md={12} lg={12} xl={16} className="input-padding-right">
              <div className='flex-align-items'>
                <Select
                  showSearch
                  allowClear
                  optionFilterProp="seatchprop"
                  style={{ width: '109px', marginRight: '10px' }}
                  value={this.state.cardType}
                  onChange={this.handleCardTypeOnChange}
                  placeholder={this.setMessage("DrugDistributionperHealthCard", "descripts", "居民健康卡")}
                >
                  {cardTypeOption}
                </Select>
                <Input
                  allowClear
                  style={{ width: '142px', borderRight: '0' }}
                  value={this.state.cardNo}
                  onChange={this.handleCardNoChange}
                  onBlur={(e) => this.handleReadCardOnBlur(e, 'blur')}
                  onPressEnter={(e) => this.handleReadCardOnBlur(e, 'enter')}
                  placeholder={this.setMessage("DrugDistributioncardNumTips", "descripts", "卡号(Enter)")}
                />
                <Button
                  style={{ margin: '0 10px', background: '#007AFF', color: '#fff' }}
                  onClick={this.handleReadCard}
                >
                  {this.setMessage("DrugDistributionCardReading", "descripts", "读卡")}
                </Button>
                <Input
                  allowClear
                  value={patNo}
                  ref={this.myRef1}
                  style={{ width: '160px', marginRight: '10px' }}
                  title={this.setMessage("DrugDistributionenterToSeachPatID", "descripts", "回车触发病人ID查询")}
                  placeholder={this.setMessage("DrugDistributionpatId/CardNum", "descripts", "人员标识(Enter)")}
                  // onBlur={(e) => this.handlePatient(e, 'blur')}
                  onChange={this.handlePatientOnChange}
                  // onPressEnter={(e) => this.handlePatient(e, 'enter')}
                  onPressEnter={this.handleQuery}
                />
                <div className='flex-align-items'>
                  <span className="d-form-label" style={{ marginTop: 0 }}>{this.setMessage("DrugDistributionchargeDate", "descripts", "收费日期：")}</span>
                  <DatePicker
                    className="d-start-date"
                    style={{ width: '125px' }}
                    value={startDate}
                    onChange={this.handleStartDate}
                    placeholder={this.setMessage("DrugDistributionstartDate", "descripts", "开始日期")}
                  />
                  <span className="d-form-label form-label-date" style={{ marginTop: 0 }}>{this.setMessage("DrugDistributionto", "descripts", "到")}</span>
                  <DatePicker
                    className="d-end-date"
                    style={{ width: '125px', marginRight: '8px' }}
                    value={endDate}
                    onChange={this.handleEndDate}
                    placeholder={this.setMessage("DrugDistributiondeadline", "descripts", "结束日期")}
                  />
                  <Select
                    showSearch
                    allowClear
                    optionFilterProp="seatchprop"
                    style={{ width: '120px', marginRight: '10px' }}
                    placeholder={this.setMessage("DrugDistributionstate", "descripts", "状态")}
                    value={fyFlag}
                    onChange={this.handlestatusID}
                  >
                    {auditStatus}
                  </Select>
                  <Button type="primary" style={{ marginRight: '10px' }} onClick={this.handleQuery}>{this.setMessage("DrugDistributionsearch", "descripts", "查询")}</Button>
                  <Button onClick={this.handleFRAShowModal}>人脸识别</Button>
                </div>
              </div>
            </Col>
            <Col xs={12} sm={12} md={12} lg={12} xl={8} className="d-operation-right" style={{ flexWrap: 'nowrap' }}>
              <span style={{ marginRight: '24px', display: dispensingChecked ? "flex" : "none", alignItems: "center" }}>
                <span className="d-form-label" style={{ width: "72px", marginTop: 0 }}>{this.setMessage("DrugDistributionpharmacist", "descripts", "配药师：")}</span>
                <Select placeholder="请选择" style={{ width: '120px' }} showSearch optionFilterProp="seatchprop" allowClear value={pharmacistValue} onChange={(e) => this.handlePharmacistValue(e, true)}>
                  {pharmacistSelect}
                </Select>
              </span>
              <span>
                {this.setMessage("DrugDistributiondirectModel", "descripts", "直接发药：")}<Switch checkedChildren="是" unCheckedChildren="否" checked={dispensingChecked} onClick={this.onClickSwitch} />
              </span>
              <div className="dor-switch-win" style={{ height: '66px' }}>
                <span>{this.setMessage("DrugDistributioncurrentWin", "descripts", "当前窗口：")}{radioWindowData && radioWindowData.dispWinDesc ? radioWindowData.dispWinDesc : this.setMessage("DrugDistributionNonSelectedWin", "descripts", "未选择窗口")}</span>
                <span onClick={this.switchingWindow} style={{ color: "#007AFF", marginTop: "12px", cursor: 'pointer' }}>
                  <Icon type="swap" />
                  {this.setMessage("DrugDistributionswitchWin", "descripts", "切换窗口")}
                </span>
              </div>
            </Col>
          </Row>
          <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
          <Row>
            <Col
              span={5}
              tabIndex={1}
              onKeyDown={this.handleDFYOnKeydown}
              style={{ outline: 'none' }}
              id="dfy-list"
            >
              <div style={{ paddingRight: '6px', position: 'relative' }}>
                <Card
                  size="small"
                  title={<div className="card-title-left-img">
                    <img src={iconMedicine} alt=""></img>{this.setMessage("DrugDistributionwaitForDelivery", "descripts", "待发药")}
                  </div>}
                >
                  <div style={{ height: store.getState().tableHeight.y + 174 - basicHeight + 'px' }}>
                    <Table
                      columns={detailColumns && detailColumns.length > 0 ? detailColumns : this.detailColumns}
                      dataSource={detailData}
                      bordered
                      pagination={false}
                      scroll={{ x: detailColumns && detailColumns.length > 0 ? detailWidthTotal : '200', y: store.getState().tableHeight.y + 112 - basicHeight }}
                      onRow={this.onClickRowLeftTable}
                      rowClassName={this.setRowClassNameLeftTable}
                      className="table-scroll-height"
                    />
                  </div>
                </Card>
                <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
              </div>
            </Col>
            <Col span={19}>
              <div
                tabIndex={1}
                onKeyDown={this.handleFYLBOnKeydown}
                style={{ outline: 'none' }}
                id="fy-list"
              >
                <Card
                  size="small"
                  title={<div className="card-title-left-img" style={{ position: "relative" }}>
                    <div>
                      <img src={iconListvisits} alt="" />{this.setMessage("DrugDistributiondistributingDrugList", "descripts", "发药列表")}
                    </div>
                    <div style={{ position: "absolute", top: "-8px", right: "12px", height: "38px", display: "flex", alignItems: "center" }}>
                      语音提醒：
                      <Switch checkedChildren="是" unCheckedChildren="否" checked={voiceReminder} onChange={this.handleVoiceReminderSwitch} />
                    </div>
                  </div>}
                  className="dispensing-list"
                >
                  <div style={{ paddingBottom: '12px', textAlign: 'right' }}>
                    <Button
                      type="danger"
                      onClick={this.handlePrintLabel}
                      style={{ marginRight: '30px', color: !rowId ? '#d9d9d9' : '#1890FF', borderColor: !rowId ? '#d9d9d9' : '#1890FF' }}
                      disabled={!rowId}
                      ghost
                    >{this.setMessage("DrugDistributionprintLabel", "descripts", "打印标签")}</Button>
                    <Button
                      type="danger"
                      onClick={this.handlePrintPresc}
                      style={{ marginRight: '30px', color: !rowId ? '#d9d9d9' : '#1890FF', borderColor: !rowId ? '#d9d9d9' : '#1890FF' }}
                      disabled={!rowId}
                      ghost
                    >{this.setMessage("DrugDistributionprintPre", "descripts", "打印处方")}</Button>
                    <Button
                      type="danger"
                      onClick={this.handlePrintPYD}
                      style={{ marginRight: '30px', color: !rowId ? '#d9d9d9' : '#1890FF', borderColor: !rowId ? '#d9d9d9' : '#1890FF' }}
                      disabled={!rowId}
                      ghost
                    >{this.setMessage("DrugDistributionprintPYD", "descripts", "打印配药单")}</Button>
                    <Button
                      type="danger"
                      onClick={() => this.modalChild.showModal(modalRowData, dispDetailTableData)}
                      style={{ marginRight: '30px' }}
                      disabled={!rowId || rowData.dispStatus === 'Y' || this.state.authorityStatus}
                      ghost
                    >{this.setMessage("DrugDistributionrefusingToDistribute", "descripts", "拒绝发药")}</Button>
                    <Button
                      type="primary"
                      onClick={this.handleDispensing}
                      style={{ marginRight: '30px' }}
                      disabled={!rowId || rowData.dispStatus === 'Y' || this.state.authorityStatus}
                    >{this.setMessage("DrugDistributiondrugDelibery", "descripts", "发药")}</Button>
                    <Button
                      type="primary"
                      onClick={this.handleFullDose}
                      disabled={tableData && tableData.length > 0 ? this.state.authorityStatus ? true : false : true}
                    >一键发药</Button>
                  </div>
                  <PubilcTablePagination param={param} handelThis={this} onClickRowPublic={this.onClickRowPublic} setRowClassNamePublic={this.setRowClassNamePublic} />
                </Card>
              </div>
              <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
              <Card
                size="small"
                className="table-scroll-height"
                title={
                  <div className="card-title-left-img">
                    <div>
                      <img src={iconListvisits} alt="" />药品明细
                    </div>
                  </div>
                }
              >
                <PubilcTablePagination param={detailParam} onClickRowPublic={this.handleDetailClickRow} setRowClassNamePublic={this.handleDetailSetClassName} />
              </Card>
            </Col>
          </Row>
          <Modal
            title={<div><div className="modal-title-top"></div>{this.setMessage("DrugDistributionselectPharmacist", "descripts", "选择配药师")}</div>}
            visible={pharmacistVisible}
            onOk={this.pharmacistHandleOk}
            onCancel={() => this.handleCancel("pharmacist")}
            className="modal-header-line"
          >
            <div style={{ minHeight: '100px' }}>
              {this.setMessage("DrugDistributionpharmacist", "descripts", "配药师：")}<Select style={{ width: '200px' }} showSearch optionFilterProp="seatchprop" allowClear value={pharmacistValue} onChange={(e) => this.handlePharmacistValue(e, false)}>
                {pharmacistSelect}
              </Select>
            </div>
          </Modal>
          <Modal
            title={<div><div className="modal-title-top"></div>{this.setMessage("DrugDistributionselectWin", "descripts", "选择窗口")}</div>}
            visible={windowVisible}
            style={{ minWidth: '680px' }}
            closable={radioWindowData && radioWindowData.dispWinID ? true : false}
            className="modal-header-line modal-body-padding"
            maskClosable={radioWindowData && radioWindowData.dispWinID ? true : false}
            onCancel={() => this.handleCancel("window")}
            footer={
              <div>
                {radioWindowData && radioWindowData.dispWinID ? <Button style={{ marginRight: '8px' }} onClick={() => this.handleCancel("window")}>{this.setMessage("DrugDistributioncancel", "descripts", "取消")}</Button> : ''}
                <Button onClick={this.windowHandleOk} style={{ backgroundColor: '#1890ff', borderColor: '#1890ff', color: '#fff' }}>{this.setMessage("DrugDistributiondetermine", "descripts", "确认")}</Button>
              </div>
            }
          >
            <div style={{ color: '#F5222D', fontSize: '4px', background: '#FFF1F0', height: '32px', lineHeight: '32px', paddingLeft: '24px' }}>
              <Icon type="exclamation-circle" style={{ marginRight: '4px' }} />{this.setMessage("DrugDistributionswitchingWinTips", "descripts", "切换窗口时请选择需要切换的窗口并点击确定按钮。")}
            </div>
            <Form style={{ padding: '0 24px' }}>
              <Form.Item label={this.setMessage("DrugDistributionPleaseSelectWin", "descripts", "请选择窗口：")}>
                {getFieldDecorator('window', {
                  rules: [{ required: true }],
                })(
                  <Row className="ad-window li-window" style={{ padding: '0 20px' }}>
                    {windowDom}
                  </Row>
                )}
              </Form.Item>
            </Form>
          </Modal>
          <RejectPrescription onRef={this.onModalRef} handleThis={this} modalTitle={this.setMessage("DrugDistributionrefusingToDistribute", "descripts", "拒绝发药")} />
          <ReadCard ref={r => this.readCard = r} />
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='DrugDistribution'
            configType="C"
            onRef={this.onMainColumnRef}
            reloadData={this.getMainTableColumns}
          />
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='OutpatientWaitingList'
            configType="C"
            onRef={this.onDetailColumnRef}
            reloadData={this.getOutpatientWaitingList}
          />
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='NewDispensingDetail'
            configType="C"
            onRef={ref => this.dispDetailRef = ref}
            reloadData={this.getDispDetailColumns}
          />
          <Modal className='face-recognition-modal'
            title={'人脸识别'}
            maskClosable={false}
            footer={null}
            visible={FRAVisible}
            onCancel={this.handleFRAClose}
            onOk={this.onSubmit}>
            <div style={{ display: "flex", justifyContent: "center", marginTop: "-36px" }}>
              {FRAVisible ? <FaceRecognitionAuto businessCode={'001'} faceType='patient' loadDara={this.onSubmit}
                hospID={userData.hospID}
                locID={userData.locID}
                doctorID={userData.userID}
                closeModal={this.handleFRAClose}
                ref={this.onFaceRecognitionAutoRefs} /> : null}
            </div>
          </Modal>
        </div>
      </Spin>
    )
  }
};

const NewDispensingForm = Form.create()(NewDispensing);
export default NewDispensingForm;
