/*
 * Create:      柿子
 * CreateDate:  2023/04/01
 * Describe：   住院收费/出院结算(医保平台)
 * 原型地址:     https://modao.cc/app/J53kOcDLrq1w9cvoe1gLP9#screen=slfvuz40we5hon4
 * */
import React, { Component } from 'react';
import { Row, Col, Button, Select, Input, Radio, Icon, Modal, Spin, message, Divider, Tooltip, Popconfirm } from 'antd';
import { Keup, INSUYBUtil, Util, dayFormat } from 'tools';
import { HISDll } from '../../../tools/index';
import { $loadTemplate, $loopPrint } from '../../lodop/Common/Print.js';
import store from 'store';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import PublicTableEditable from 'pages/common/PublicTableEditable';
import SplitBills from '../SplitBills';
import HopNumber from './component/HopNumber'
import ScanCodeModal from './component/ScanCodeModal';
import INSURegister from 'pages/Cashier/INSURegister';
import MessageModal from '../../../components/messageModal';
import PatientAccountManagement from './PatientAccountManagement';
import ListOfHospitalizationExpenses from './ListOfHospitalizationExpenses';
import IframeModal from 'pages/common/IframeModal';
import VerificationCodeLogin from 'pages/Cashier/charges/component/VerificationCodeLogin';
import './style/discharge-settlement-INSU.less';
import './style/index.less'

class DischargeSettlementINSU extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    let ipConfig = React.$getSessionData('ipConfig');
    this.state = {
      userData,
      ipConfig,
      typeBtnActive: '2',
      patTypeData: [{
        id: '',
        descripts: '不限'
      }, {
        id: '1',
        descripts: '在院'
      }, {
        id: '2',
        descripts: '出院'
      }],
      payReasonSelectData: [], // 费别
      locSelectData: [], // 科室下拉
      bedSelectData: [], // 床位
      userSelectData: [], // 操作员
      copyQueryParams: {},
      queryParams: {
        chargeStatus: 'B',
        payUserID: userData?.userID || undefined,
        startDate: moment().subtract(30, 'days').format(dayFormat),
        stopDate: moment().format(dayFormat),
        validFlag: '1'
      },
      loading: false,
      rowID: '',
      rowData: {},
      insuAdmObj: {}, // 医保相关数据
      page: 1,
      pageSize: 50,
      total: 0,
      tableData: [],
      columns: [],
      totalWidth: 0,
      queryHeight: 0,
      expenseListVisible: false,
      userInfo: {},
      spinningVisible: false, // 调用医保时全局遮罩
      splitBillVisible: false, // 拆分账单弹窗
      advancePaymentVisible: false, // 预交金
      insuSettleID: '', // 医保结算id
      insuPayID: '', // 医保预结算记录ID
      accDepositIDinfo: '',
      insuAdmID: '', // 医保登记ID
      recordID: '', // 支付记录ID
      confirmSettlementVisible: false, // 确认结算
      paywamtData: [], // 结算方式
      payWListData: [], // table数据 支付方式列表
      cashInCashVal: '0.00', // 实收现金
      payAccIPAmt: '0.00', // 住院结算参与账户的金额
      accpayBalance: '',
      accAmtBalance: '',
      zeroPay: '0.00', // 找零
      disXJ: false,
      otherPayData: [], // 其他支付方式
      userPayData: {}, // 用户支付数据
      subTypeFeeArr: [],
      paymentMethodColumns: [],
      admReasonArr: [], // 费别下拉数据
      admReasonID: undefined, // 修改费别
      contextMenuvisible: false,
      treatCode: '',
      icdAllNoEList: [],
      TreatCodeist: [], // 医保动态组件使用-治疗方式
      xnhtreatCodeist: [],
      invoice: '', // 发票号
      modalShow: false,
      digitalFlag: '', // 验证码登陆按钮显示标志
      codeFormData: [],
      verificationCodeLoading: false
    };
    this.queryRef = React.createRef();
  }

  componentDidMount() {
    this.handleInitJuris(); //权限
    this.getTableColumns();
    this.getLocSelectData();
    this.getUserSelectData();
    this.getPayReasonSelectData();
    this.getInsuReason();
    this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 125 });
    this.patientRef && this.patientRef.getCardSelectData();
    document.addEventListener('click', this.handleDocumentClick);
  }

  // 鼠标单击事件，当鼠标在任何地方单击时，设置菜单不显示
  handleDocumentClick = () => {
    const { contextMenuvisible } = this.state
    if (contextMenuvisible) {
      this.setState({ contextMenuvisible: false })
    }
  };

  // 获取权限数据
  handleInitJuris = async () => {
    try {
      let { userData, queryParams } = this.state;
      let data = {
        params: [{
          logonHospID: userData?.hospID || '', //医院id
          logonGroupID: userData?.groupID || '',  //角色id
          logonUserID: userData?.userID || '', //人员id
          invTypeCode: 'I'  // 类型
        }]
      }
      let res = await React.$asyncPost(this, '05210001', data);
      let otherPayData = res.groupConfig?.HBOPConfigPaymode[0]?.IPCharge || [];  // 其他付款方式
      let startDate = res?.startDate || '', stopDate = res?.stopDate || '';
      if (startDate) {
        queryParams.startDate = startDate;
      }
      if (stopDate) {
        queryParams.stopDate = stopDate;
      }
      for (let i = 0; i < otherPayData.length; i++) {
        otherPayData[i].descripts = otherPayData[i].paywDesc;
        otherPayData[i].id = otherPayData[i].paywID;
      }
      let paymentMethodColumns = [{
        title: '支付方式',
        dataIndex: 'payWDesc',
        editable: true,
        width: '150px',
        align: 'center',
        inputType: 'Select',
        detailitem: otherPayData,
        onSelect: this.handlePayWSelect
      },
      {
        title: '金额',
        dataIndex: 'payWamt',
        editable: true,
        width: '150px',
        align: 'center',
        inputType: 'Input',
        onBlur: this.handlePayMoneyChange,
      }];
      this.setState({
        queryParams,
        otherPayData,
        paymentMethodColumns,
        copyQueryParams: JSON.parse(JSON.stringify(queryParams)),
        payType: res.groupConfig?.HBOPConfigPaymode[0]?.IPCharge[0]?.paywID || '',
        otherPay: res.groupConfig?.HBOPConfigPaymode[0]?.IPCharge[1]?.paywID || '',
        invoice: res?.currentInvNoInfo || '', // 发票号
        digitalFlag: res?.digitalFlag || 'N', // 验证码登陆按钮显示标志
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 费别下拉
  getPayReasonSelectData = async () => {
    try {
      const { userData } = this.state;
      const data = {
        params: [{
          hospID: userData?.hospID || '', //医院id
        }]
      }
      let res = await React.$asyncPost(this, '05100129', data);
      this.setState({ payReasonSelectData: res?.data || [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取科室下拉数据
  getLocSelectData = async () => {
    try {
      const { userData } = this.state;
      const data = {
        params: [{
          type: 'W',
          status: '1',
          hospID: userData?.hospID || '', //医院id
        }]
      }
      let res = await React.$asyncPost(this, '04020008', data);
      this.setState({ locSelectData: res.result?.Data || [] }, () => {
        this.getTableData();
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取床位下拉数据
  getBedSelectData = async (locID) => {
    try {
      if (!locID) { // 科室ID为空的话床位查询报错【为空不查询床位】
        this.setState({ bedSelectData: [] });
        return
      }
      const data = {
        params: [{
          locID
        }]
      }
      let res = await React.$asyncPost(this, '01050021', data);
      this.setState({ bedSelectData: res.result?.Data || [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取操作员下拉数据
  getUserSelectData = async () => {
    try {
      const { userData } = this.state;
      const data = {
        params: [{
          hospID: userData?.hospID || '', //医院id
          locTypeCode: 'C'
        }]
      }
      let res = await React.$asyncPost(this, '05210023', data);
      this.setState({ userSelectData: res?.user || [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          reactCode: ['IPAdmList'],
          compontName: 'IPAdmList',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map((item, index) => {
          return {
            ...item,
            index,
            render: (text, record) => {
              if (item.dataIndex === 'registerFlag') {
                let config = {
                  '已登记': <span style={{ color: '#007AFF' }}>{text}</span>,
                  '未登记': <span>{text}</span>
                }
                return config[text];
              } else {
                return text;
              }
            }
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      this.setState({
        codeFormData: res?.result?.formData || [],
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 切换配镜中心
  handleSwitchTypeBtn = item => {
    this.patientRef && this.patientRef.setFieldsValue({ patNo: undefined });
    this.setState({ typeBtnActive: item.id }, () => {
      this.handleQuery();
    })
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      let dataIndexArr = ['stopDate', 'startDate', 'wardID', 'bedID', 'payUserID', 'jsType', 'payReasonID', 'chargeStatus', 'validFlag'];
      if (dataIndex === 'wardID') {
        this.getBedSelectData(e); // 选择科室科室获取床位数据
      }
      if (dataIndexArr.indexOf(dataIndex) > -1) {
        this.handleQuery();
      }
    })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      this.setState({ loading: true })
      let { queryParams, pageSize, page, userData, typeBtnActive } = this.state;
      let patInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...queryParams,
          condition: typeBtnActive,
          hospID: userData?.hospID || '',
          number: patInfo?.patNo || '',
          cardNo: patInfo?.cardNo || '',
          cardTypeID: patInfo?.cardType || '',
          // startDate: typeBtnActive === '2' ? queryParams?.startDate : undefined, // 类型为出院的时候才传出院时间
          // stopDate: typeBtnActive === '2' ? queryParams?.stopDate : undefined,
          // payUserID: typeBtnActive === '2' ? queryParams?.payUserID : undefined,
          // wardID: typeBtnActive ? queryParams?.wardID : undefined, // 患者类型为不限的时候不传
          // bedID: typeBtnActive === '1' ? queryParams?.bedID : undefined, // 类型为在院的时候传床号
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '05300028', data);
      let tableData = res?.data || []
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].key = i + 1;
        tableData[i].registerFlag = tableData[i].admReasonCode && tableData[i].admReasonCode === 'INSU' && tableData[i].insuAdmID ? '已登记' : '未登记';
      }
      this.setState({
        tableData,
        total: res.total,
        loading: false,
      }, () => {
        this.handleClearRowData();
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setRowData(record);
        } else {
          this.handleClearRowData();
        }
      },
      onContextMenu: (event) => {
        this.handleContextMenu(record, event); // 选中行右键
      },
    }
  }

  // 选中行数据赋值 - 提示：不要再一个一个字段取值，在哪个对象就取哪个对象！
  setRowData = (record) => {
    this.patientRef && this.patientRef.setFieldsValue({ patNo: record?.patNo || '' });
    this.setState({
      rowID: record.key,
      rowData: record,
      insuAdmObj: record?.insuAdmObj || {},
      insuPayID: '',
      insuAdmID: '', // 医保登记ID
      recordID: '',
      insuSettleID: ''
    }, () => {
      this.getUserPayData();
      this.getUserInfo();
    });
  }

  // 清除操作信息
  handleClearRowData = () => {
    this.setState({
      rowID: '',
      rowData: {},
      insuPayID: '',
      insuAdmObj: {},
      userInfo: {},
      userPayData: {},
      subTypeFeeArr: [],
      insuAdmID: '', // 医保登记ID
      recordID: '',
      insuSettleID: ''
    });
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 获取用户信息
  getUserInfo = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          number: rowData?.patNo || '', // 登记号/身份证号
          cardTypeID: '', // 卡类型id
          cardNo: '', // 卡号
        }]
      }
      let res = await React.$asyncPost(this, '03040004', data);
      this.setState({
        userInfo: res.data || {}, // 用户数据
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 重置
  handleReset = () => {
    const { copyQueryParams } = this.state;
    this.patientRef && this.patientRef.handleReset();
    this.setState({
      queryParams: copyQueryParams
    })
  }

  // 原号重打
  handleRetype = async () => {
    try {
      const { userData } = this.state;
      if (userData?.hospCode === 'H03') {
        var data = {
          fpzl: 2,
          fphm: this.state.fphm, // 金税发票号码
          fpdm: this.state.fpdm, // 金税发票代码
          showPrintDlg: 0
        }
        var source = encodeURIComponent(JSON.stringify(data))
        var dllInput = 'SID=2\&\&\&\SIDParam=' + source; // JSON.stringify({ "SID": "0", "SIDParam": source })
        let dllParams = JSON.stringify({ 'inputDir': 'JSInv/prykjsapplication.dll', 'clsName': 'prykjsapplication.JSHelper', 'funcName': 'GetJSData', 'dllInput': dllInput });
        if (typeof (CefSharp) != "undefined") { // 新元素定制浏览器
          CefSharp.BindObjectAsync("xysCefToJavaScripts");
          setTimeout(() => {
            xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
              var res = JSON.parse(returnVale);
              if (res.resultCode == '0') {
                message.success('打印成功！');
              }
            })
          }, 100);
        } else {
          const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
          if (frame) {
            frame.DynamicLoadingDLL(dllParams)
              .then(
                data => {
                  var res = JSON.parse(data);
                  if (res.resultCode == '0') {
                    message.success('打印成功！');
                  }
                },
                err => {
                  console.log('error', err);
                }
              )
          } else {
            $.getJSON("http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?JsonCallback=?", {
              input: dllParams
            },
              function (data) {
                var res = JSON.parse(data);
                if (res.resultCode == '0') {
                  message.success('打印成功！');
                }
              });
          }
        }
      } else {
        // 打印
        this.handlePrint()
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      const { userData, rowData, recordID } = this.state;
      let data = {
        params: [{
          recordID: recordID || rowData?.recordID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '', // 人员id
        }]
      }
      let res = await React.$asyncPost(this, '05100382', data);
      $loadTemplate(res.template, res.result);
    } catch (error) {
      console.log(error);
    }
  };

  // 医保打印
  handleINSUPrint = async (flag) => {
    try {
      const { userData, rowData, recordID } = this.state;
      let data = {
        params: [{
          recordID: recordID || rowData?.recordID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '', // 人员id
          flag: flag || ''
        }]
      }
      let res = await React.$asyncPost(this, '05100411', data);
      $loopPrint('', res.result);
    } catch (error) {
      console.log(error);
    }
  };

  // 结算单打印
  handleSettlementDocPrint = async () => {
    let openModal = Modal.info({
      title: '调用医保结算单打印，请稍后......',
      content: <Spin size="large" />,
      okText: 'OK',
      onOk() { },
    });
    const { userData, insuAdmObj } = this.state;
    let data = {
      params: [{
      }],
      hospID: userData?.hospID || '',
      businessType: 'Print',
      session: [userData],
      insuAdmObj
    }
    let rtn = await INSUYBUtil.insuNew('AgentFun', data);
    let res = JSON.parse(rtn);
    openModal.destroy();
    if (res.errorCode == '0') {
    }
    else {
      message.warn('调用医保结算单打印报错！' + res.errorMessage);
      Modal.warning({
        title: '调用医保结算单打印报错',
        content: res.errorMessage,
      });
    }
  };

  // 修改弹窗状态
  handleModifyVisible = (dataIndex, visible) => {
    this.state[dataIndex] = visible;
    this.setState({});
  };

  // 医保登记
  handleMedicalInsuranceRegistration = () => {
    const { insuAdmObj } = this.state;
    if (insuAdmObj?.status === 'N' || insuAdmObj?.status === 'D') {
      Modal.confirm({
        title: '取消医保登记',
        content: '是否确定取消医保登记？',
        okText: '是',
        cancelText: '否',
        onOk: this.handleHttpINSURegister,
        onCancel: () => { },
      });
    } else {
      this.handleHttpINSURegister()
    }
  };

  handleHttpINSURegister = async () => {
    const { userData, ipConfig, rowData, insuAdmObj, userInfo } = this.state;
    if (!(rowData?.admID)) {
      message.error('请先选择就诊信息');
      return false;
    }
    if (rowData?.payStatusCode !== 'OB') {
      message.error('此记录不是未结算状态，不能登记');
      return false;
    }
    this.setState({ spinningVisible: true });
    this.INSURegisterRef && this.INSURegisterRef.resetFields();
    if (insuAdmObj && insuAdmObj.status != 'N' && insuAdmObj.status != 'D') {
      // 登记
      await this.INSURegisterRef.readYBPatdataNew(rowData?.admID, userInfo, rowData?.patBillID);
    } else {
      // 取消登记
      let insupaydata = {
        params: [{
          admID: insuAdmObj.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', //医院id
          groupID: userData?.groupID || '',  //角色id
          ip: ipConfig?.ipv4 || '',
          patID: userInfo.patID,  //病人id
          reasonCode: rowData.admReasonCode,
          psn_no: insuAdmObj.psn_no,
          mdtrt_id: insuAdmObj.mdtrt_id
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z2C',
        hospID: userData?.hospID || '', //医院id
        interfaceDr: insuAdmObj.interfaceDr,
        session: [userData]
      }
      let YBPatDivdata = await INSUYBUtil.insuNew('Register', insupaydata);
      let res = JSON.parse(YBPatDivdata);
      if (res.errorCode == '0') {
        Keup.ModalMessage(3, this, '医保登记撤销成功!', '自动关闭', 'destroy', '确定', 'success')
      }
      else {
        Keup.ModalMessage(30, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
        Modal.warning({
          title: '医保登记撤销异常:',
          content: res.errorMessage,
        });
      }
    }
    this.setState({ spinningVisible: false }, () => {
      this.getTableData();
    });
  };

  // 预交金
  handleAdvancePayment = () => {
    const { rowData } = this.state;
    this.setState({ advancePaymentVisible: true }, () => {
      this.advancePaymentRef && this.advancePaymentRef.setState({
        patNo: rowData.patNo,
        admID: rowData.admID
      }, () => {
        this.advancePaymentRef && this.advancePaymentRef.searchUser()
      })
    })
  };

  // 取消结算
  handleCancelSettlement = () => {
    const { rowData } = this.state;
    Modal.confirm({
      title: '患者信息核对',
      content: (
        <div>
          <div>
            姓名：{rowData?.patName || ''}
          </div>
          <div>
            身份证号：{rowData?.IDCardNo || ''}
          </div>
          <div>
            登记号：{rowData?.patNo || ''}
          </div>
          <div>
            住院号：{rowData?.patMedicalNo || ''}
          </div>
        </div>
      ),
      cancelText: '取消 -> 返回界面',
      okText: '确认 -> 继续取消',
      onOk: this.handleConfirmCancelSettlement,
      onCancel() { }
    });
  };

  // 确认取消结算
  handleConfirmCancelSettlement = async () => {
    let openModal = Modal.info({
      title: "正在退费，请稍后......",
      content: <Spin size="large" />,
      onOk() { },
    });
    let errorCode = '0'
    const { userData, ipConfig, rowData, insuAdmObj, userInfo, insuSettleID } = this.state
    ///判断付款记录是否是医保记录
    var hisData = {
      params: [{
        billID: rowData?.patBillID || '', // 付款记录串
        invtype: 'PAY', //his交易流水
        userID: userData?.userID || '', //操作人
        ip: ipConfig?.ipv4 || '', //ip
        hospID: userData?.hospID || '', //医院
      }]
    }
    let hisDataObj = await INSUYBUtil.GoTOHISHttp(hisData, '05210047');    //调用his接口
    if (hisDataObj.errorCode != '0') {
      message.warn(res.errorMessage);
      openModal.destroy() //关闭等待界面
      return
    }
    var insuPayID = hisDataObj?.insuPayIDinfo || '';
    if (insuPayID != '') {
      ///医保退费
      let cancelSetlData = {
        params: [{
          admID: insuAdmObj.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', //医院id
          groupID: userData?.groupID || '',  //角色id
          ip: ipConfig?.ipv4 || '',
          patID: userInfo.patID || '',  //病人id
          reasonCode: rowData?.admReasonCode || '',
          psn_no: insuAdmObj?.psn_no || '',
          mdtrt_id: insuAdmObj?.mdtrt_id || '',
          insuplc_admdvs: insuAdmObj?.insuplc_admdvs || '',
          setl_id: insuSettleID
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z5C',
        hospID: userData?.hospID || '', //医院id
        interfaceDr: insuAdmObj?.interfaceDr || '',
        session: [userData]
      }
      let rtnData = await INSUYBUtil.insuNew('Settlement', cancelSetlData);
      let res = JSON.parse(rtnData);
      if (res.errorCode != '0') {
        Modal.warning({
          title: '医保退费调用异常：',
          content: res.errorMessage,
        });
        openModal.destroy() //关闭等待界面
        return
      }
    }
    if (errorCode === '0') {
      var data = {
        params: [{
          billID: rowData?.patBillID || '', // 就诊ID,
          userID: userData?.userID || '', // 人员id
          groupID: userData?.groupID || '',  // 角色id,
          locID: userData?.locID || '', // 登录科室,
          hospID: userData?.hospID || '', // 医院id
          ip: ipConfig?.ipv4 || '', // IP
        }]
      }
      let res = await React.$asyncPost(this, '05300023', data);
      if (res?.errorCode === '0') {
        this.getTableData();
        if (res.transactionPayflag && res.transactionPayflag === 'T') {
          //退款  线上退款无论成功是否都往下走 失败在补交易界面进行补交易
          let dllInputdata = {
            params: [{
              userID: userData?.userID || '', //收费员ID
              parkRecordDrinfo: res.parkRecordID || '', // 退费ID
              hospID: userData?.hospID || '', //医院id
              groupID: userData?.groupID || '',  //角色id
              paytype: 'I',
              newpayrecordinfo: '', // 新付款记录rowid串
            }],
            code: '99070022'
          }
          var dllPath = 'ReadYBCard/GZNYYHPay.dll';
          let className = 'GZNYYHPay.GZNYYHPay';
          var funcName = 'Refund';
          let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
          if (typeof (CefSharp) != 'undefined') {   // 定制浏览器
            CefSharp.BindObjectAsync('xysCefToJavaScripts');
            xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
              var res = JSON.parse(returnVale);
              if (res.errorCode == '0') {
                message.success('成功！' + res.errorMessage)
              } else {
                Modal.warning({
                  title: '扫码支付退款错误：',
                  content: returnVale,
                });
              }
            })
          } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
              frame.DynamicLoadingDLL(dllParams)
                .then(
                  data => {
                    var res = JSON.parse(data);
                    if (res.errorCode == '0') {
                      message.success('成功！' + res.errorMessage)
                    } else {
                      Modal.warning({
                        title: '扫码支付退款错误：',
                        content: returnVale,
                      });
                    }
                  },
                  err => {
                    console.log('error', err);
                  }
                )
            }
          }
        }
      }
    }
    openModal.destroy() //关闭等待界面
  };

  // 结算
  handleClickSettlement = Util.debounce(async () => {
    const { userData, ipConfig, rowData, insuAdmObj, insuPayID, accDepositIDinfo, userInfo } = this.state;
    if (insuAdmObj?.status === 'D') { // 已出院结算过了
      Modal.error({
        title: '异常提醒',
        content: '当前操作患者已进行医保出院登记，无法再次结算！如需再次结算，请右键撤销出院登记。',
        okText: '我知道了',
      })
      return;
    }
    let payopenModal = Modal.info({
      title: "正在his结算，请稍后......",
      content: <Spin size="large" />,
      onOk() { },
    });
    //先账单
    this.setState({
      recordID: '',
      ipInsuType: ''
    })
    let hisDataObj = await this.getHisBill('1');
    if (hisDataObj.errorCode === '0') {
      // 核验费用权限
      let data = {
        params: [{
          admID: rowData?.admID || '', // 就诊ID,
          billID: rowData?.patBillID || '', // 账单ID,
          insuPayID: insuPayID || rowData?.insuPayID || '',
          paytype: 'I',
          userID: userData?.userID, // 人员id
          accDepositIDinfo,
          groupID: userData?.groupID, // 角色id,
          locID: userData?.locID, // 登录科室,
          hospID: userData?.hospID, // 医院id
          ip: ipConfig?.ipv4, // IP
        }],
      }
      let hisprepayobj = await INSUYBUtil.GoTOHISHttp(data, "05300100");
      let errorCode = hisprepayobj.errorCode
      if (errorCode === '0') {
      } else {
        Keup.ModalMessage(30, this, hisprepayobj.errorMessage, '自动关闭', 'destroy', '确定', 'error');
        payopenModal.destroy(); // 关闭等待界面
        return
      }
    } else {
      Keup.ModalMessage(30, this, hisDataObj.errorMessage, '自动关闭', 'destroy', '确定', 'error');
      payopenModal.destroy(); // 关闭等待界面
      return
    }
    // 医保患者先进行医保结算流程
    let ipInsuType = rowData.ipInsuType
    if (insuAdmObj.status == 'N' && ipInsuType === 'Y') {
      this.setState({ spinningVisible: true })
      // 调用医保结算弹窗/组织结算入参
      let setlInpar = {
        params: [{
          admID: insuAdmObj.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', // 医院id
          groupID: userData?.groupID || '',  // 角色id
          ip: ipConfig?.ipv4 || '',
          patID: userInfo.patID || '',  // 病人id
          reasonCode: rowData?.admReasonCode || '',
          psn_no: insuAdmObj?.psn_no || '',
          mdtrt_id: insuAdmObj?.mdtrt_id || '',
          insuplc_admdvs: insuAdmObj?.insuplc_admdvs || ''
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z5',
        hospID: userData?.hospID || '', // 医院id
        interfaceDr: insuAdmObj?.interfaceDr || '',
        session: [userData]
      }
      let setlRtn = await INSUYBUtil.insuNew('Settlement', setlInpar);
      let res = JSON.parse(setlRtn);
      if (res.errorCode == '0') {
        let insuInfo = res.result?.hisInsuInfo || {};
        this.setState({ insuAdmID: insuInfo?.insuAdmID || '', insuPayID: insuInfo?.insuPayID || '', insuSettleID: insuInfo?.setl_id || '', spinningVisible: false });
        Keup.ModalMessage(3, this, '医保结算成功!', '自动关闭', 'destroy', '确定', 'success')
      }
      else {
        this.setState({ spinningVisible: false });
        message.warn(res.errorMessage);
        payopenModal.destroy(); // 关闭等待界面
        return;
      }
    }
    this.handleOpenSettlement()
    setTimeout(() => {
      payopenModal.destroy(); // 关闭等待界面
    }, 1000);
  })

  //账单
  getHisBill = async (flag) => {
    const { rowData, userData } = this.state;
    let data = {
      params: [{
        admID: rowData?.admID || '', // 就诊ID,
        billID: rowData?.patBillID || '', // 账单ID,
        userID: userData?.userID || '', // 人员id
        ordExecStr: ''
      }]
    }
    let hisDataObj = await INSUYBUtil.GoTOHISHttp(data, '05300012');    //his试算
    let errorCode = hisDataObj.errorCode
    if (errorCode === '0' && flag !== '1') {
      Keup.ModalMessage(3, this, hisDataObj.errorMessage, '关闭', 'destroy', '现在就去', 'success')
    }
    return hisDataObj
  }

  handleOpenSettlement = async () => {
    const { userData, ipConfig, rowData, accDepositIDinfo, insuPayID } = this.state;
    let advanceData = {
      params: [{
        admID: rowData?.admID || '', // 就诊ID,
        billID: rowData?.patBillID || '', // 账单ID,
        insuPayID: insuPayID || rowData?.insuPayID || '',
        paytype: 'I',
        userID: userData?.userID, // 人员id
        accDepositIDinfo,
        groupID: userData?.groupID, // 角色id,
        locID: userData?.locID, // 登录科室,
        hospID: userData?.hospID, // 医院id
        ip: ipConfig?.ipv4, // IP
      }],
    }
    let advanceRes = await INSUYBUtil.GoTOHISHttp(advanceData, '05300017'); // his预算
    let recordID = advanceRes?.recordID || '';
    if (advanceRes.errorCode === '0') {
      this.setState({
        recordID
      })
    } else {
      Keup.ModalMessage(15, this, advanceRes.errorMessage, '自动关闭', 'destroy', '确定', 'error');
      return;
    }
    let settleAccountsData = {
      params: [{
        recordID,
      }],
    }
    let settleAccountRes = await INSUYBUtil.GoTOHISHttp(settleAccountsData, '05300021'); // his结算数据
    let payAccIPAmt = 0
    if (settleAccountRes.errorCode === '0') {
      let settleAccountData = settleAccountRes && 'data' in settleAccountRes && Array.isArray(settleAccountRes.data) ? settleAccountRes.data : [];
      payAccIPAmt = parseFloat(settleAccountData[0].accAmtBalance)
      let payWListData = [{
        key: 1,
        payWID: this.state.otherPayData[0]?.paywID,
        payWCode: this.state.otherPayData[0]?.paywCode,
        payWDesc: this.state.otherPayData[0]?.paywDesc,
        payWamt: parseFloat(parseFloat(settleAccountData[0].leftAmt) - parseFloat(payAccIPAmt)).toFixed(2),
      }];
      this.setState({
        payAccIPAmt: parseFloat(payAccIPAmt).toFixed(2),
        accpayBalance: 0.00,
        payWListData,
        confirmSettlementVisible: true,
        leftAmt: settleAccountData[0]?.leftAmt,
        leftAmtSur: settleAccountData[0]?.leftAmt,
        accAmtBalance: settleAccountData[0]?.accAmtBalance,
        patAmt: settleAccountData[0]?.patAmt,
        paywamtData: settleAccountData[0]?.paywamtData
      }, () => {
        setTimeout(() => {
          this.paymentMethodRef && this.paymentMethodRef.getTableData(payWListData);
        }, 300)
        this.handleCheckCash();
        this.handleCheckpayMoneySurplus();
      });
    }
  }

  // 检查支付方式剩余金额
  handleCheckpayMoneySurplus = async () => {
    // let { leftAmt, payAccIPAmt } = this.state
    // let paywAmt = 0; // 支付方式金额
    // let surplusamt = 0; // 剩余没结算金额
    // for (var i = 0; i < this.state.payWListData.length; i++) {
    //   if ((parseFloat(this.state.payWListData[i].payWamt) !== 0) & (this.state.payWListData[i].payWamt !== '')) {
    //     paywAmt = paywAmt + parseFloat(this.state.payWListData[i].payWamt)
    //   }
    // }
    // surplusamt = (parseFloat(leftAmt) - parseFloat(payAccIPAmt)).toFixed(2) - parseFloat(paywAmt)
    // this.setState({ surplusamt: parseFloat(surplusamt) });
    let { leftAmt, payAccIPAmt } = this.state
    let paywAmt = 0; // 支付方式金额
    let surplusamt = 0; // 剩余没结算金额
    for (let i = 0; i < this.state.payWListData.length; i++) {
      if ((parseFloat(this.state.payWListData[i].payWamt) !== 0) & (this.state.payWListData[i].payWamt !== '')) {
        paywAmt = paywAmt + parseFloat(this.state.payWListData[i].payWamt)
      }
    }
    let data = {
      params: [{
        numberinfo: (leftAmt + '-' + payAccIPAmt + '-' + paywAmt)
      }]
    }
    let res = await React.$asyncPost(this, '05210090', data);
    if (res.errorCode == 0) {
      surplusamt = res?.number
    } else {
      surplusamt = ((parseFloat(leftAmt).toFixed(2) * 1000 - parseFloat(payAccIPAmt).toFixed(2) * 1000 - parseFloat(paywAmt).toFixed(2) * 1000) / 1000).toFixed(2)
    }
    this.setState({ surplusamt: surplusamt });
  }

  // 确认结算
  handleConfirmSettlementOK = Util.debounce(async () => {
    const { userData, ipConfig, cashInCashVal, zeroPay, leftAmt, payAccIPAmt, rowData, recordID } = this.state;
    let payWListVal = this.paymentMethodRef && this.paymentMethodRef.handleSave();
    if (('editingKey' in payWListVal) && payWListVal.editingKey) {
      message.error('存在列处于编辑状态，请先保存或取消该操作。');
      return;
    }
    let payWListData = payWListVal?.tableData || [];
    if ((cashInCashVal !== '') & (parseFloat(cashInCashVal) !== 0)) {
      if (parseFloat(zeroPay) < 0) {
        message.error('应找金额小于0，请核实实收金额是否正确');
        return false;
      }
    }
    let paywAmt = 0; // 支付方式金额
    let notpayleftAmt = 0; // 剩余没结算金额
    let payWIDinfo = '';
    let errormessage = '';
    for (var i = 0; i < payWListData.length; i++) {
      if ((parseFloat(payWListData[i].payWamt) !== 0) & (payWListData[i].payWamt !== '')) {
        if (payWListData[i].payWID === '') {
          errormessage = '支付方式列表存在支付方式为空，请选择支付方式'
        }
        paywAmt = paywAmt + parseFloat(payWListData[i].payWamt)
        if (payWIDinfo === '') {
          payWIDinfo = payWListData[i].payWID + '^' + parseFloat(payWListData[i].payWamt)
        }
        else {
          payWIDinfo = payWIDinfo + String.fromCharCode('2') + payWListData[i].payWID + '^' + parseFloat(payWListData[i].payWamt)
        }
      }
    }
    if (errormessage !== '') {
      message.error(errormessage)
      return false
    }
    // 前端计算存在数据偏差问题【走后台计算】
    let data = {
      params: [{
        numberinfo: (leftAmt + '-' + payAccIPAmt + '-' + paywAmt)
      }]
    }
    let res = await React.$asyncPost(this, '05210090', data);
    if (res.errorCode == 0) {
      notpayleftAmt = res?.number;
    } else {
      notpayleftAmt = ((this.handleToFixed(leftAmt) * 1000) - (this.handleToFixed(payAccIPAmt) * 1000) - (this.handleToFixed(paywAmt) * 1000)) / 1000;
    }
    // notpayleftAmt = (parseFloat(leftAmt) - parseFloat(payAccIPAmt)).toFixed(2) - parseFloat(paywAmt)
    if (parseFloat(notpayleftAmt) !== 0) {
      // message.error('结算金额不符，还存在金额：' + parseFloat(notpayleftAmt) + '没计算进支付方式')
      Keup.ErrorModal('结算金额不符，还存在金额：' + parseFloat(notpayleftAmt) + "没计算进支付方式。" + 'leftAmt=' + leftAmt + '; toFixed(leftAmt)=' + this.handleToFixed(leftAmt) + '; payAccIPAmt=' + payAccIPAmt + '; toFixed(payAccIPAmt)=' + this.handleToFixed(payAccIPAmt) + '; paywAmt=' + paywAmt + '; toFixed(paywAmt)=' + this.handleToFixed(paywAmt) + ',res.number:' + res?.number, '确定')
      return false
    }
    let openModalpay = Modal.info({
      title: "正在结算，请稍后......",
      content: <Spin size="large" />,
      onOk() { },
    });
    let nRecordID = recordID || rowData?.recordID || '';
    var paramsdata = {
      params: [{
        recordID: nRecordID,
        userID: userData?.userID, // 人员id
        payWIDinfo,
        groupID: userData?.groupID, // 角色id,
        locID: userData?.locID, // 登录科室,
        hospID: userData?.hospID, // 医院id
        ip: ipConfig?.ipv4, // IP
        patBillID: userData?.patBillID || '', // 账单ID
        payAccIPAmt: parseFloat(payAccIPAmt), // 参与结算的账户金额
      }]
    }
    let updataPaywObj = await INSUYBUtil.GoTOHISHttp(paramsdata, '05300018');    //his更新支付方式
    let errorCode = updataPaywObj.errorCode;
    if (errorCode === '0') {
      if (this.state.ipInsuType === 'Y') { }
      //扫码确认
      if (updataPaywObj.transactionflag && updataPaywObj.transactionflag === 'Y') {
        this.scanCodeChild && this.scanCodeChild.modifyVisible(true, nRecordID);
        openModalpay.destroy(); // 关闭等待界面
      } else {
        this.handleConfirmCompletion(openModalpay);
      }
    }
    else {
      message.error(updataPaywObj.errorMessage);
      openModalpay.destroy(); // 关闭等待界面
    }
  });

  // 保留两位小数 - 传入的数据有问题则返回0
  handleToFixed = (float) => {
    return float ? Number(float.toString().match(/^\d+(?:\.\d{0,2})?/)) : 0;
  };

  //住院收费确定
  handleConfirmCompletion = async (openModalpay) => {
    const { userData, ipConfig, rowData, recordID, accDepositIDinfo, queryParams } = this.state;
    let nRecordID = recordID || rowData?.recordID || '';
    var data = {
      params: [{
        recordID: nRecordID,
        admID: rowData?.admID || '', // 就诊ID,
        billID: rowData?.patBillID || '', // 账单ID
        paytype: 'I',
        userID: userData.userID, // 人员id
        accDepositIDinfo,
        groupID: userData.groupID, // 角色id,
        locID: userData.locID, // 登录科室,
        hospID: userData.hospID, // 医院id
        ip: ipConfig?.ipv4, // IP
      }]
    }
    let compaywObj = await INSUYBUtil.GoTOHISHttp(data, '05300019');    //his收费确认
    openModalpay && 'destroy' in openModalpay && openModalpay.destroy && openModalpay.destroy(); // 关闭等待界面
    let errorCode = compaywObj.errorCode;
    if (errorCode === '0') {
      this.scanCodeChild && this.scanCodeChild.modifyVisible(false, undefined, 'Y', 'Y'); // 关闭扫码弹窗
      message.success(compaywObj.errorMessage)
      this.setState({
        confirmSettlementVisible: false,
        compleRecordIDinfo: compaywObj.compleRecordIDinfo
      }, () => {
        queryParams.chargeStatus = '';
        this.getTableData();
        //长春医院打印凭证 
        if (userData?.hospCode === 'H19') {
          // 打印
          this.handlePrint()
        } else {
          if (compaywObj.invoiceFileUrl) {
            this.iframeRef && this.iframeRef.modifyVisible(true, compaywObj.invoiceFileUrl)
          } else {
            this.handlePrint()
            this.handleINSUPrint();
          }
        }
        //this.handleShowPrintModal();
        //this.handleRetype()
      })
    } else {
      this.scanCodeChild && this.scanCodeChild.modifyVisible(false, undefined, 'Y', 'Y'); // 关闭扫码弹窗
      message.error(compaywObj.errorMessage)
      //this.handleUnbudgetAndSettlement(); // 删除预结算记录
    }
  }

  handleShowPrintModal = () => {
    let _this = this;
    Modal.confirm({
      centered: true,
      title: '温馨提示',
      cancelText: '取消',
      content: '是否确认打印此收据?',
      okText: '继续打印',
      onOk() {
        Modal.destroyAll();
        // 打印
        _this.handleRetype()
      },
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  // 取消预结算
  handleUnbudgetAndSettlement = async () => {
    // 判断付款记录是否预结算状态
    const { userData, ipConfig, rowData, insuAdmObj, userInfo, recordID, insuSettleID } = this.state;
    let preSettleData = {
      params: [{
        billID: rowData?.patBillID || '', // 付款记录串
        invtype: 'PAY', // his交易流水
        userID: userData?.userID || '', // 操作人
        ip: ipConfig?.ipv4, // ip
        hospID: userData?.hospID || '', // 医院
      }]
    }
    let preSettleRes = await INSUYBUtil.GoTOHISHttp(preSettleData, '05210081'); // 调用his接口
    if (preSettleRes.errorCode != '0') {
      message.warn(preSettleRes.errorMessage);
      return
    }
    // 获取医保结算数据 判断付款记录是否是医保记录
    let paramsdata = {
      params: [{
        billID: rowData?.patBillID || '', // 付款记录串
        invtype: 'PAY', // his交易流水
        userID: userData?.userID || '', // 操作人
        ip: ipConfig?.ipv4, // ip
        hospID: userData?.hospID || '', // 医院
      }]
    }
    let hisDataObj = await INSUYBUtil.GoTOHISHttp(paramsdata, '05210047'); // 调用his接口
    if (hisDataObj.errorCode != '0') {
      message.warn(hisDataObj.errorMessage);
      return
    }
    let insuPayID = hisDataObj.insuPayIDinfo
    if (insuPayID) {
      // 医保退费 组织退费入参(HIS终止结算)
      let setlInpar = {
        params: [{
          admID: insuAdmObj.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID,
          hospID: userData?.hospID, //医院id
          groupID: userData?.groupID,  //角色id
          ip: ipConfig?.ipv4,
          patID: userInfo.patID,  //病人id
          reasonCode: rowData.admReasonCode,
          psn_no: insuAdmObj.psn_no,
          mdtrt_id: insuAdmObj.mdtrt_id,
          insuplc_admdvs: insuAdmObj.insuplc_admdvs,
          setl_id: insuSettleID
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z5C',
        hospID: userData?.hospID, //医院id
        interfaceDr: insuAdmObj.interfaceDr,
        session: [userData]
      }
      let setlRtn = await INSUYBUtil.insuNew('Settlement', setlInpar);
      let setlRtnRes = JSON.parse(setlRtn);
      if (setlRtnRes.errorCode == '0') {
        this.setState({ spinningVisible: false });
        Keup.ModalMessage(3, this, '医保结算成功!', '自动关闭', 'destroy', '确定', 'success')
      }
      else {
        this.setState({ spinningVisible: false });
        message.warn(setlRtnRes.errorMessage);
        return;
      }
    }
    let data = {
      params: [{
        patBillID: rowData?.patBillID || '', // 账单ID,
        recordID: recordID || rowData?.recordID || '', // 付款记录ID,
        userID: userData?.userID, // 人员id
        groupID: userData?.groupID, // 角色id,
        locID: userData?.locID, // 登录科室,
        hospID: userData?.hospID, // 医院id
        ip: ipConfig?.ipv4, // IP
      }],
    }
    let res = await React.$asyncPost(this, '05300022', data);
    if (res.errorCode !== '0') {
      message.error(res.errorMessage)
    }
    this.getTableData();
  }

  // 实收现金
  handleCashInCashChange = (val) => {
    let payWListVal = this.paymentMethodRef && this.paymentMethodRef.handleSave();
    if (('editingKey' in payWListVal) && payWListVal.editingKey) {
      message.error('存在列处于编辑状态，请先保存或取消该操作。');
      return;
    }
    let payWListData = payWListVal?.tableData || [];
    let cashInCashVal = Keup.MoneyReplace(val)
    if (cashInCashVal === '') { cashInCashVal = 0 }
    let payCashCodeamt = 0 	//现金金额
    for (var i = 0; i < payWListData.length; i++) {
      if (payWListData[i].payWCode === 'CASH') {
        if (parseFloat(payWListData[i].payWamt) !== 0) {
          payCashCodeamt = payCashCodeamt + parseFloat(payWListData[i].payWamt)
        }
      }
    }
    this.setState({
      cashInCashVal // 金额过滤
    })
    let zeroPay = parseFloat(parseFloat(cashInCashVal) - parseFloat(payCashCodeamt)).toFixed(2); // 找零
    this.setState({
      zeroPay, // 找零
    })
  }

  // 收取住院账户余额
  onChangepayAccIPAmt = (e) => {
    let val = e.target.value
    let newVal = Keup.inputMoneyReplace(val)
    if (newVal === '') { newVal = 0 }
    //判断账户余额
    if (parseFloat(newVal) > parseFloat(this.state.accAmtBalance)) {
      message.error('住院账户余额只有：' + this.state.accAmtBalance + ' 不能超出')
      this.setState({
        payAccIPAmt: this.state.payAccIPAmt
      })
      return
    }
    let accpayBalance = parseFloat(Keup.inputMoneyReplace(this.state.accAmtBalance)) - parseFloat(newVal)
    if (parseFloat(accpayBalance) < 0) {
      this.setState({
        accpayBalance: 0.00
      })
    } else {
      this.setState({
        accpayBalance: parseFloat(accpayBalance).toFixed(2),
      })
    }
    this.setState({
      payAccIPAmt: newVal
    })
    //先对支付方式列表初始化
    let payWListData = [
      {
        key: 1,
        payWID: this.state.otherPayData[0].paywID,
        payWCode: this.state.otherPayData[0].paywCode,
        payWDesc: this.state.otherPayData[0].paywDesc,
        payWamt: parseFloat(parseFloat(this.state.leftAmt) - parseFloat(newVal)).toFixed(2),
      }
    ]
    this.setState({
      payWListData,
    }, () => {
      this.paymentMethodRef && this.paymentMethodRef.getTableData(payWListData);
      this.handleCheckCash();
      this.handleCheckpayMoneySurplus();
    })
  }

  //检查现金支付
  handleCheckCash = () => {
    let { payWListData } = this.state;
    let payCashCodeamt = 0 	//现金金额
    for (var i = 0; i < payWListData.length; i++) {
      if (payWListData[i].payWCode === 'CASH') {
        if (parseFloat(payWListData[i].payWamt) !== 0) {
          payCashCodeamt = payCashCodeamt + parseFloat(payWListData[i].payWamt)
        }
      }
    }
    if (parseFloat(payCashCodeamt) < 0) {
      this.setState({ zeroPay: parseFloat(payCashCodeamt).toFixed(2), cashInCashVal: 0.00 })
    } else {
      this.setState({ disXJ: true, cashInCashVal: parseFloat(payCashCodeamt).toFixed(2), zeroPay: 0.00 })
    }
  }

  // 获取账户状态
  getUserPayData = async () => {
    try {
      const { rowData } = this.state;
      const data = {
        params: [{
          patBillID: rowData?.patBillID || '',
        }],
      }
      let res = await React.$asyncPost(this, '05300016', data);
      this.setState({
        userPayData: res.data[0] || {}, //账户状态
        subTypeFeeArr: res.subTypeFeeArr || [],
      });
    } catch (error) {
      console.log(error);
      this.setState({
        userPayData: {},
        subTypeFeeArr: [],
      })
    }
  }

  // 获取费别下拉数据
  getInsuReason = async () => {
    try {
      let res = await React.$asyncPost(this, '05100094');
      this.setState({
        admReasonArr: res.dataArr
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 修改费别
  handleInsuReasonUpdate = async () => {
    let { admReasonID, rowData } = this.state
    if (admReasonID == 'undefined' || admReasonID == '') {
      message.warn('费别不可为空!')
      return
    }
    try {
      let data = {
        params: [{
          admID: rowData?.admID,
          admReasonID
        }]
      }
      let res = await React.$asyncPost(this, '05100350', data);
      message.success(res?.errorMessage || '修改成功');
      this.setState({
        admReasonShow: false
      }, () => {
        this.getTableData()
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 右键菜单事件
  handleContextMenu = (record, event) => {
    if (this.root) {
      event.preventDefault();
      this.setRowData(record);
      this.setState({ contextMenuvisible: true });
      // clientX/Y 获取到的是触发点相对于浏览器可视区域左上角距离
      const clickX = event.clientX;
      const clickY = event.clientY;
      // window.innerWidth/innerHeight 获取的是当前浏览器窗口的视口宽度/高度
      const screenW = window.innerWidth;
      const screenH = window.innerHeight;
      // 获取自定义菜单的宽度/高度
      const rootW = this.root.offsetWidth;
      const rootH = this.root.offsetHeight;
      const right = (screenW - clickX) > rootW;
      const left = !right;
      const bottom = (screenH - clickY) > rootH;
      const top = !bottom;
      if (right) {
        this.root.style.left = `${clickX}px`;
      }
      if (left) {
        this.root.style.left = `${clickX - rootW}px`;
      }
      if (bottom) {
        this.root.style.top = `${clickY}px`;
      }
      if (top) {
        this.root.style.top = `${clickY - rootH}px`;
      }
    }
  }

  //医保费用上传
  handleInsuUPloadItem = async () => {
    const { rowData, userData, insuAdmObj, userInfo, ipConfig } = this.state;
    if (rowData?.payStatusCode != 'OB') {
      message.error('此记录不是未结算状态，不能医保费用上传');
      return false
    }
    if (rowData?.payFlag === 'Y') {
      message.error('已存在付款记录，无需医保费用上传!');
      return;
    }
    let openModal = Modal.info({
      title: '正在医保费用上传，请稍后......',
      content: <Spin size="large" />,
      onOk() { },
    });

    let insupayData = {
      params: [{
        admID: insuAdmObj?.admID || '',
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo?.patID || '',  //病人id
        reasonCode: rowData?.admReasonCode || '',
        psn_no: insuAdmObj?.psn_no || '',
        mdtrt_id: insuAdmObj?.mdtrt_id || ''

      }],
      insuAdmObj: insuAdmObj,
      businessType: 'Z3',
      hospID: userData?.hospID || '', //医院id
      interfaceDr: insuAdmObj?.interfaceDr || '',
      session: [userData]
    }
    let YBPatDivdata = await INSUYBUtil.insuNew("FeeUpload", insupayData);
    let res = JSON.parse(YBPatDivdata);
    let errorCode = res.errorCode
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '医保费用上传成功!', '自动关闭', 'destroy', '确定', 'success')
    } else if (res.errorCode == 'Insu-1') {
      this.childMessageExamineRef.showModal(res.errorMessage)
    } else {
      Keup.ModalMessage(30, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    return errorCode
  }

  //取消医保费用上传
  handleCancleInsuUPloadItem = async () => {
    const { rowData, userData, insuAdmObj, userInfo, ipConfig } = this.state;
    if (rowData?.payStatusCode != 'OB') {
      message.error('此记录不是未结算状态，不能取消医保费用上传')
      return false
    }
    let openModal = Modal.info({
      title: '正在取消医保费用上传，请稍后......',
      content: <Spin size="large" />,
      onOk() { },
    });
    let cancleFeeUploadData = {
      params: [{
        admID: insuAdmObj.admID || '',
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo.patID || '',  //病人id
        reasonCode: rowData?.admReasonCode || '',
        psn_no: insuAdmObj.psn_no || '',
        mdtrt_id: insuAdmObj.mdtrt_id || ''
      }],
      insuAdmObj: insuAdmObj,
      businessType: 'Z3C',
      hospID: userData?.hospID || '', //医院id
      interfaceDr: insuAdmObj?.interfaceDr || '',
      session: [userData]
    }
    let rtndata = await INSUYBUtil.insuNew('FeeUpload', cancleFeeUploadData);
    let res = JSON.parse(rtndata);
    let errorCode = res.errorCode
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '医保费用取消成功!', '自动关闭', 'destroy', '确定', 'success')
    }
    else {
      this.handleCancellationoftrialcalculation()
      Keup.ModalMessage(30, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    return errorCode
  }

  // 取消试算
  handleCancellationoftrialcalculation = async () => {
    try {
      const { rowData, userData } = this.state;
      var data = {
        params: [{
          billID: rowData?.patBillID || '', // 就诊ID,
          userID: userData?.userID || '', //人员id
        }],
      }
      let res = await React.$asyncPost(this, '05300025', data);
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 医保预结算界面
  handleInsuIPPayModal = async () => {
    const { rowData, userData, insuAdmObj, userInfo, ipConfig } = this.state;
    if (rowData?.payStatusCode != 'OB') {
      message.error('此记录不是未结算状态，不能医保费用预结算');
      return;
    }
    if (rowData?.payFlag === 'Y') {
      message.error('已存在付款记录，无需医保费用预结算!');
      return;
    }
    let openModal = Modal.info({
      title: '正在医保费用预结算，请稍后......',
      content: <Spin size="large" />,
      onOk() { },
    });
    if (insuAdmObj.status && insuAdmObj.status == 'N') {
      //组织入参
      let data = {
        params: [{
          admID: insuAdmObj?.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', //医院id
          groupID: userData?.groupID || '',  //角色id
          ip: ipConfig?.ipv4 || '',
          patID: userInfo?.patID || '',  //病人id
          reasonCode: rowData?.admReasonCode || '',
          psn_no: insuAdmObj?.psn_no || '',
          mdtrt_id: insuAdmObj?.mdtrt_id || ''
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z4',
        hospID: userData?.hospID, //医院id
        interfaceDr: insuAdmObj.interfaceDr,
        session: [userData]
      }
      let rtnData = await INSUYBUtil.insuNew('Settlement', data);
      let res = JSON.parse(rtnData);
      openModal.destroy();
      if (res.errorCode == '0') {
        Keup.ModalMessage(3, this, '预结算成功!', '自动关闭', 'destroy', '确定', 'success')
      } else {
        Keup.ErrorModal(res.errorMessage, '确定')
      }
    } else {
      message.error('该患者不是医保病人，请进行医保登记！');
    }
    return
  }

  // 取消出院登记
  handleUnbudgetAndLevRegistra = async () => {
    const { userData, insuAdmObj, rowData, ipConfig, userInfo } = this.state;
    if (insuAdmObj && !insuAdmObj.status) {
      message.error('此记录不是医保登记状态，不能取消出院登记');
      return;
    }
    let openModal = Modal.info({
      title: '正在取消出院登记，请稍后......',
      content: <Spin size="large" />,
      okText: 'OK',
      onOk() { },
    });
    try {
      let data = {
        params: [{
          admID: insuAdmObj.admID || '',
          billID: rowData?.patBillID || '',
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', // 医院id
          groupID: userData?.groupID || '', // 角色id
          ip: ipConfig?.ipv4 || '',
          patID: userInfo?.patID || '', // 病人id
          reasonCode: rowData?.admReasonCode || '',
          psn_no: insuAdmObj?.psn_no || '',
          mdtrt_id: insuAdmObj?.mdtrt_id || ''
        }],
        insuAdmObj: insuAdmObj,
        businessType: 'Z6C',
        hospID: userData?.hospID, // 医院id
        interfaceDr: insuAdmObj?.interfaceDr || '',
        session: [{ ...userData }]
      }
      let rtnData = await INSUYBUtil.insuNew('Register', data);
      let res = JSON.parse(rtnData);
      let errorCode = res.errorCode
      if (errorCode != '0') {
        Modal.warning({
          title: '医保出院登记异常：',
          content: res.errorMessage,
        });
      }
      else {
        Keup.ModalMessage(10, this, '医医保出院登记成功!', '自动关闭', 'destroy', '确定', 'success')
      }
      openModal.destroy();
    } catch (error) {
      message.warning('异常')
      openModal.destroy();
      console.error(error);
    }
    this.handleModifyHospRegStatus(); // 修改登记状态
  }

  // 合并拆分账单
  handleUnionBill = async () => {
    try {
      const { userData, rowData } = this.state;
      const data = {
        params: [{
          admID: rowData?.admID || '', // 就诊ID,
          updateUserID: userData?.userID || '', // 人员id
        }],
      }
      let res = await React.$asyncPost(this, '05300011', data);
      message.success(res?.errorMessage || '取消成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 新增
  handleAddTableData = () => {
    this.paymentMethodRef && this.paymentMethodRef.handleAddTableData();
  }

  // 支付方式选择
  handlePayWSelect = (e) => {
    const { otherPayData } = this.state;
    let payWListVal = this.paymentMethodRef && this.paymentMethodRef.handleSave();
    let editingKey = payWListVal?.editingKey || ''
    let payWListData = payWListVal?.tableData || [];
    const index = payWListData.findIndex(item => editingKey === item.key);
    if (index > -1) {
      for (var i = 0; i < otherPayData.length; i++) {
        if (otherPayData[i].paywDesc === e) {
          payWListData[index].payWCode = otherPayData[i].paywCode;
          payWListData[index].payWDesc = otherPayData[i].paywDesc;
          payWListData[index].payWID = otherPayData[i].paywID;
        }
      }
    }
    this.handleUpdataPayWListData(payWListData, 'Y');
  }

  // 列表支付方式金额输入
  handlePayMoneyChange = (e) => {
    let val = e.target.value
    let payWListVal = this.paymentMethodRef && this.paymentMethodRef.handleSave();
    let editingKey = payWListVal?.editingKey || ''
    let payWListData = payWListVal?.tableData || [];
    let newVal = Keup.inputMoneyReplace(val)
    if (newVal === '') { newVal = 0 }
    const index = payWListData.findIndex(item => editingKey === item.key);
    if (index > -1) {
      payWListData[index].payWamt = newVal
    }
    this.handleUpdataPayWListData(payWListData);
  }

  // 更新支付方式列表数据
  handleUpdataPayWListData = (tableData, isUpdataChild) => {
    this.setState({ payWListData: tableData }, () => {
      isUpdataChild === 'Y' && this.paymentMethodRef && this.paymentMethodRef.getTableData(tableData, 'N');
      this.handleCheckCash();
      this.handleCheckpayMoneySurplus();
    });
  }

  ///后端电子发票生成交易
  electronicInvoice(source) {
    //修文百信医院 走电子发票
    this.electronicInvoice52012301(source, '');
  }

  electronicInvoice52012301 = async (source, writeOffFlaf) => {
    this.setState({ loading: true });
    let { userData } = this.state;
    try {
      //修文百信医院 走电子发票 
      //获取token信息获取地址：
      let data = {
        params: [{
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', //医院id
          groupID: userData?.groupID || '',  //角色id
          payMentRecordID: source?.recordID || '',
        }]
      }
      let res = await React.$asyncPost(this, '05100418', data);
      var errorCode = res.errorCode;
      var token = res.token;
      if (token == '') {
        //获取token信息
        let headers = '';
        let paramdata = {
          data: res.tokendata,
          ip: res.ip,
          url: res.url,
          headers: headers
        }
        let dllreturndata = await HISDll.hisDll('OperationElectronic52012301', paramdata, 'Electronic/Electronic.dll', 'Electronic.Electronic');
        let dllreturnjson = JSON.parse(dllreturndata);
        if (dllreturnjson.errcode === '0000') {
          //保存token
          token = dllreturnjson.access_token;
          let data = {
            params: [{
              userID: userData?.userID || '',
              locID: userData?.locID || '',
              hospID: userData?.hospID || '', //医院id
              groupID: userData?.groupID || '',  //角色id
              tokenjson: dllreturnjson,
            }]
          }
          let hisres = await React.$asyncPost(this, '05100419', data);
          var errorCode = hisres.errorCode;

          if (errorCode != '0') {
            message.error(hisres.errorMessage);
            return
          }
        } else {
          message.error(dllreturnjson);
          return
        }
      }
      let data2 = {
        params: [{
          userID: userData?.userID || '',
          locID: userData?.locID || '',
          hospID: userData?.hospID || '', //医院id
          groupID: userData?.groupID || '',  //角色id
          payMentRecordID: source?.recordID || '',
          writeOffFlaf: writeOffFlaf
        }]
      }
      //生成电子发票
      let getRESTElectronicBill = await React.$asyncPost(this, '05100417', data2);
      if (getRESTElectronicBill.errorCode == '0') {
        let invEScarletID = getRESTElectronicBill.invEScarletID;
        let dllReturnHeaders = '';
        let dllReturnParams = {
          data: getRESTElectronicBill?.data || '',
          ip: getRESTElectronicBill?.ip || '',
          url: getRESTElectronicBill?.url || '',
          headers: dllReturnHeaders
        }
        let dllreturndata = await HISDll.hisDll('OperationElectronic52012301', dllReturnParams, 'Electronic/Electronic.dll', 'Electronic.Electronic');
        let dllreturnjson = JSON.parse(dllreturndata);
        let hisdata = {
          params: [{
            invEScarletID: invEScarletID,
            dllData: dllreturnjson,
            hospID: userData?.hospID || '', //医院id
            groupID: userData?.groupID || '',  //角色id
          }]
        }
        //保存电子发票
        let saveRESTElectronicBill = await React.$asyncPost(this, '05100420', hisdata);
        console.log('getRESTElectronicBill', saveRESTElectronicBill)
        if ((saveRESTElectronicBill.errorCode == '0000') || (saveRESTElectronicBill.errorCode == '0')) {
          message.success(saveRESTElectronicBill.errorMessage);
        } else {
          message.error(saveRESTElectronicBill);
        }
        this.handleQuery();
      }
    } catch (error) {
      console.log(error);
      // message.warning('异常:' + JSON.stringify(error))
    }
    this.setState({ loading: false });
  }

  printElectronicInvoice = (source) => {
    //修文百信医院 打印电子发票
    let pictureUrl = source?.pictureUrl || '';
    pictureUrl && window.open(pictureUrl)
  }

  ///修文百信医院电子发票红冲交易  
  writeOffElectronicInvoice52012301(source) {
    //发票红冲交易  
    Modal.confirm({
      title: '发票红冲交易提醒',
      content: '发票红冲交易，是否确认进行发票红冲交易?',
      onOk: () => {
        this.electronicInvoice52012301(source, 'S');
      },
    })
  }

  // 退院
  handleCancelRegister = () => {
    Modal.confirm({
      title: '退院确定',
      content: '退院后数据不可恢复，确认退院吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.handleHttpCancelRegister();
      },
    })
  }

  // 调用接口退院
  handleHttpCancelRegister = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          admID: rowData?.admID || '', // 就诊ID
          patID: rowData?.patID || '',
        }]
      }
      let res = await React.$asyncPost(this, '03060026', data);
      message.success(res?.errorMessage || '退院成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  //异地医保签到
  handleInsuSignin = async () => {
    let openModal = Modal.info({
      title: '正在异地医保签到，请稍后......',
      content: <Spin size="large" />,
      onOk() { },
    });
    const { rowData, userData, ipConfig, userInfo } = this.state;
    let insupaydata = {
      params: [{
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo?.patID || '',  //病人id
        reasonCode: rowData?.admReasonCode || ''

      }],
      code: '05210072'
    }
    let YBPatDivdata = await INSUYBUtil.insuYBAHSYB('InsuSignin', insupaydata);
    let res = JSON.parse(YBPatDivdata);
    let errorCode = res.errorCode;
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '异地医保签到成功!', '自动关闭', 'destroy', '确定', 'success');
    }
    else {
      Keup.ErrorModal(res.errorMessage, '确定');
      // Keup.ModalMessage(15, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    return errorCode;
  }

  // 异地医保签退
  handleInsuSignout = async () => {
    let openModal = Modal.info({
      title: '正在异地医保签退，请稍后......',
      content: <Spin size="large" />,
      onOk() { },
    });
    const { rowData, ipConfig, userData, userInfo } = this.state;
    let insupaydata = {
      params: [{
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo?.patID || '',  //病人id
        reasonCode: rowData?.admReasonCode || ''

      }],
      code: '05210072'
    }
    let YBPatDivdata = await INSUYBUtil.insuYBAHSYB('InsuSignout', insupaydata);
    let res = JSON.parse(YBPatDivdata);
    let errorCode = res.errorCode;
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '异地医保签退成功!', '自动关闭', 'destroy', '确定', 'success');
    }
    else {
      Keup.ErrorModal(res.errorMessage, '确定');
      // Keup.ModalMessage(15, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    return errorCode;
  }

  // 医保登记信息变更
  handleUpdateInsuRegInfo = async () => {
    const { rowData, ipConfig, userData, insuAdmObj, userInfo } = this.state;
    console.log('insuAdmObj', insuAdmObj)
    if (insuAdmObj && !(insuAdmObj.status)) {
      message.error('此记录不是医保登记状态，不能变更！')
      return;
    }
    let openModal = Modal.info({
      title: "正在变更登记，请稍后......",
      content: <Spin size="large" />,
      onOk() { },
    });
    //组织入参
    let insuRegdata = {
      params: [{
        admID: insuAdmObj.admID || '',
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo?.patID || '',  //病人id
        reasonCode: rowData?.admReasonCode || '',
        psn_no: insuAdmObj.psn_no,
        mdtrt_id: insuAdmObj.mdtrt_id
      }],
      insuAdmObj: insuAdmObj,
      businessType: 'Z0',
      hospID: userData?.hospID || '', //医院id
      interfaceDr: insuAdmObj.interfaceDr,
      session: [{ ...userData }]
    }
    let rtndata = await INSUYBUtil.insuNew('Register', insuRegdata);
    let res = JSON.parse(rtndata);
    let errorCode = res.errorCode
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '变更医保登记信息成功!', '自动关闭', 'destroy', '确定', 'success')
    }
    else {
      Keup.ErrorModal(res.errorMessage, '确定')
      // message.warn(res.errorMessage);
      // Keup.ModalMessage(15, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    return errorCode;
  }

  // 撤销异常医保登记
  handleCancelInsuRegInfo = async () => {
    try {
      const { insuAdmObj } = this.state;
      if (insuAdmObj && !insuAdmObj.status) {
        message.error('此记录不是医保登记状态，不能撤销异常医保登记');
        return;
      }
      let data = {
        params: [{
          admID: insuAdmObj.admID || '', //就诊ID
        }],
      }
      let res = await React.$asyncPost(this, '05110004', data);
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  }

  // 取消出院登记
  handleCancelOutHospReg = async () => {
    const { rowData, ipConfig, userData, insuAdmObj, userInfo } = this.state;
    if (insuAdmObj && !insuAdmObj.status) {
      message.error('此记录不是医保登记状态，不能取消出院登记')
      return false
    }
    let openModal = Modal.info({
      title: "正在取消医保出院登记，请稍后......",
      content: <Spin size="large" />,
      onOk() { },
    });
    //组织入参
    let cancleDisRegdata = {
      params: [{
        admID: insuAdmObj.admID || '',
        billID: rowData?.patBillID || '',
        userID: userData?.userID || '',
        locID: userData?.locID || '',
        hospID: userData?.hospID || '', //医院id
        groupID: userData?.groupID || '',  //角色id
        ip: ipConfig?.ipv4 || '',
        patID: userInfo.patID,  //病人id
        reasonCode: rowData?.admReasonCode || '',
        psn_no: insuAdmObj.psn_no,
        mdtrt_id: insuAdmObj.mdtrt_id
      }],
      insuAdmObj: insuAdmObj,
      businessType: 'Z6C',
      hospID: userData?.hospID || '', //医院id
      interfaceDr: insuAdmObj.interfaceDr,
      session: [{ ...userData }]
    }
    let rtndata = await INSUYBUtil.insuNew('Register', cancleDisRegdata);
    let res = JSON.parse(rtndata);
    let errorCode = res.errorCode
    openModal.destroy();
    if (res.errorCode == '0') {
      Keup.ModalMessage(3, this, '出院登记取消成功!', '自动关闭', 'destroy', '确定', 'success');
    }
    else {
      Keup.ErrorModal(res.errorMessage, '确定');
      // message.warn(res.errorMessage);
      // Keup.ModalMessage(15, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
    }
    this.handleModifyHospRegStatus();
    return errorCode;
  }

  // 医保信息查询
  getYBPatientInfo = async () => {
    const { userData, ipConfig } = this.state;
    let openYBModal = Modal.info({
      title: '正在进行医保信息查询,请稍等...',
      content: <Spin size="large" />,
      okText: "",
      onOk() { },
    });
    try {
      let insupaydata = {
        params: [{
          userID: userData?.userID || '',
          locID: userData?.locID,
          hospID: userData?.hospID, //医院id
          groupID: userData?.groupID,  //角色id
          ip: ipConfig?.ipv4 || ''
        }],
        businessType: 'Z1',
        hospID: userData?.hospID, //医院id
        session: [{ ...userData }]
      }
      let patientInfo = await INSUYBUtil.insuNew('GetPatientInfo', insupaydata);
      let patientInfoRet = JSON.parse(patientInfo);
      console.log('patientInfoRet', patientInfoRet);
    } catch (error) {
      Modal.warning({
        title: '医保信息查询异常：',
        content: error,
      });
      message.warning('异常:' + error);
      console.error(error);
    }
    openYBModal.destroy(); // 弹框等待提示
  }

  historyModal = () => {
    this.setState({
      modalShow: true,
    });
  }

  // 关闭发票号设置
  handleInvoiceCancel = () => {
    this.setState({
      modalShow: false,
    }, () => {
      this.getTableData();
    });
  }

  // 复制身份证号
  handleCopyToClipboard = () => {
    const { rowData } = this.state;
    React.$copyToClipboard(rowData?.IDCardNo, '身份证号复制成功');
    this.handleDocumentClick();
  }

  // 修改登记状态
  handleModifyHospRegStatus = async () => {
    try {
      const { rowData } = this.state;
      const data = {
        params: [{
          admID: rowData?.admID || '', // 就诊ID
        }]
      }
      let res = await React.$asyncPost(this, '05110024', data);
      console.log('res', res);
      this.getTableData();
    } catch (error) {
      console.log('error', error)
    }
  };

  // 取消结算
  handleCancelMoney = () => {
    this.setState({
      leftAmt: '',
      patAmt: '',
      payWListData: [],
      paywamtData: '',
      leftAmtSur: '',
      accAmtBalance: '',
      accpayBalance: '',
      zeroPay: '0.00', // 找零
      otherPayMoney: '0.00', // 其他支付金额
      cashInCashVal: '0.00', // 实收现金
      disXJ: false,
      payAccIPAmt: '0.00', //住院结算参与账户的金额
      confirmSettlementVisible: false,
    }, () => {
      // this.getTableData();
      this.handleUnbudgetAndSettlement();
    });
  };

  // 验证码登录
  handleVerificationCodeLogin = () => {
    const { codeFormData } = this.state;
    this.setState({ verificationCodeLoading: true }, () => {
      this.codeLoginRef && this.codeLoginRef.handleInit(codeFormData);
    })
  };

  // 修改验证码登录按钮状态
  modifyVerificationCodeLoading = () => {
    this.setState({ verificationCodeLoading: false });
  };

  render() {
    const { spinningVisible, typeBtnActive, patTypeData, queryParams, page, total, loading, tableData, totalWidth, queryHeight, columns, payReasonSelectData, locSelectData, bedSelectData, userSelectData, expenseListVisible,
      rowID, rowData, userInfo, splitBillVisible, advancePaymentVisible, confirmSettlementVisible, paywamtData, paymentMethodColumns, userPayData, contextMenuvisible, insuAdmObj, invoice, modalShow, digitalFlag, verificationCodeLoading
    } = this.state;
    return (
      <Spin spinning={spinningVisible}>
        <div className="hospital-zation-express discharge-settlement-new-INSU">
          <div ref={this.queryRef} className="dsm-insu-header">
            <div className="flex-between-center">
              <div className="dsm-insu-btn-item flex-wrap-align-items">
                患者类型：
                {patTypeData && patTypeData.map((item, index) => {
                  return (
                    <Button
                      size="small"
                      key={index}
                      type={typeBtnActive === item.id ? 'primary' : 'link'}
                      onClick={() => this.handleSwitchTypeBtn(item)}
                    >
                      {item.descripts}
                    </Button>
                  )
                })}
              </div>
              <Tooltip title={`【当前操作的患者信息：医保登记状态：${rowData?.registerFlag || ''} 身份证号：${rowData?.IDCardNo || ''} 姓名：${rowData?.patName || ''} 登记号：${rowData?.patNo || ''} 科室：${rowData?.admLocDesc || ''}】`}>
                <div className="ellipsis" style={{ display: rowID ? 'block' : 'none', color: '#ff5a5a', maxWidth: '70%' }}>
                  【当前操作的患者信息：医保登记状态：{rowData?.registerFlag || ''} 身份证号：{rowData?.IDCardNo || ''} 姓名：{rowData?.patName || ''} 登记号：{rowData?.patNo || ''} 科室：{rowData?.admLocDesc || ''}】
                </div>
              </Tooltip>
              <span>
                {invoice && typeof (invoice) === 'string' && invoice.indexOf('^') > -1 && invoice.split('^')[2] ? (
                  <span style={{ color: '#999', fontWeight: 'normal' }} className="curP" onClick={this.historyModal} >
                    当前发票号：
                    <span style={{ color: '#1890FF', fontWeight: 700 }}>
                      {invoice && typeof (invoice) === 'string' && invoice.indexOf('^') > -1 ? invoice.split('^')[2] : ''}
                    </span>
                  </span>
                ) : ''}
              </span>
            </div>
            <div className="common-query-split-line" style={{ height: '2px' }}></div>
            <div className="flex-align-items" style={{ margin: '12px 0' }}>
              <div style={{ marginRight: 15 }}>
                <RangeDatePicker
                  width="280px"
                  label="出院时间："
                  isChange={true}
                  format={dayFormat}
                  endDate={queryParams?.stopDate || undefined}
                  startDate={queryParams?.startDate || undefined}
                  disabled={!(typeBtnActive === '2')}
                  endChange={(e) => this.handleModifyInputValue(e, 'stopDate')}
                  startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                />
              </div>
              科室：<Select
                allowClear
                showSearch
                placeholder="请选择"
                optionFilterProp="seachprop"
                className="common-query-input"
                disabled={!typeBtnActive}
                value={queryParams?.wardID}
                onChange={(e) => this.handleModifyInputValue(e, 'wardID')}
              >
                {React.$SelectOptions(locSelectData)}
              </Select>
              床号：<Select
                allowClear
                showSearch
                style={{ width: '100px' }}
                placeholder="请选择"
                optionFilterProp="seachprop"
                className="common-query-input"
                disabled={!(typeBtnActive === '1')}
                value={queryParams?.bedID || undefined}
                onChange={(e) => this.handleModifyInputValue(e, 'bedID')}
              >
                {React.$SelectOptions(bedSelectData, 'bedID', 'bedDesc')}
              </Select>
              <GetPatientInformation queryType="fuzzySearch" onRef={ref => this.patientRef = ref} handleQuery={this.handleQuery} />
              住院号：<Input
                title="输入内容后可回车检索"
                placeholder="请输入住院号"
                className="common-query-input"
                style={{ marginRight: '24px' }}
                value={queryParams?.medicalNo || undefined}
                onChange={(e) => this.handleModifyInputValue(e.target.value, 'medicalNo')}
                onPressEnter={this.handleQuery}
              />
              <Button onClick={this.handleReset}>
                清空
              </Button>
              <Button style={{ marginLeft: '12px' }} type="primary" onClick={this.handleQuery}>
                查询
              </Button>
            </div>
            <div className="flex-align-items" style={{ marginBottom: '12px' }}>
              操作员：<Select
                allowClear
                showSearch
                placeholder="请选择"
                optionFilterProp="seachprop"
                className="common-query-input"
                disabled={!(typeBtnActive === '2')}
                value={queryParams?.payUserID || undefined}
                onChange={(e) => this.handleModifyInputValue(e, 'payUserID')}
              >
                {React.$SelectOptions(userSelectData)}
              </Select>
              <Radio.Group value={queryParams?.payReasonID || ''} onChange={(e) => this.handleModifyInputValue(e.target.value, 'payReasonID')}>
                <Radio.Button value="">全部</Radio.Button>
                {payReasonSelectData && payReasonSelectData.map(item => {
                  return (
                    <Radio.Button key={item.id} value={item.id}>{item.descripts}</Radio.Button>
                  )
                })}
              </Radio.Group>
              <Radio.Group style={{ marginLeft: '12px' }} value={queryParams?.chargeStatus || ''} onChange={(e) => this.handleModifyInputValue(e.target.value, 'chargeStatus')}>
                <Radio.Button value="">全部</Radio.Button>
                <Radio.Button value="P">已结算</Radio.Button>
                <Radio.Button value="B">未结算</Radio.Button>
              </Radio.Group>
              <Radio.Group style={{ marginLeft: '12px' }} value={queryParams?.validFlag || '1'} onChange={(e) => this.handleModifyInputValue(e.target.value, 'validFlag')}>
                <Radio.Button value="2">全部</Radio.Button>
                <Radio.Button value="1">有效</Radio.Button>
              </Radio.Group>
            </div>
          </div>
          <div className="common-query-split-line" style={{ height: '6px' }}></div>
          <div className="table-body-height" style={{ padding: '12px' }}>
            <Row style={{ marginBottom: '8px' }}>
              <Col span={12}>
                <Button
                  onClick={this.handleRetype}
                  // disabled={((!(rowData?.recordID)) || (rowData.invFlagCode != 'P'))}
                  disabled={!(rowData?.recordID)}
                >
                  <Icon type="printer" />
                  原号重打
                </Button>
                <Button
                  style={{ marginLeft: '12px' }}
                  disabled={rowData?.ipInsuType !== 'Y' || !rowData?.insuPayID}
                  onClick={this.handleSettlementDocPrint}
                >
                  <Icon type="printer" />
                  结算单
                </Button>
                <Button
                  style={{ marginLeft: '12px' }}
                  disabled={!(rowData?.payStatusCode === 'TP' || rowData?.payStatusCode === 'OB' || rowData?.payStatusCode === 'P')}
                  onClick={() => this.handleModifyVisible('expenseListVisible', true)}
                >
                  <Icon type="printer" />
                  费用清单
                </Button>
                {/*
                <Button
                  style={{ marginLeft: '12px' }}
                  disabled={rowData?.invFlagCode != 'P'}
                  onClick={() => this.electronicInvoice(rowData)}
                >
                  <Icon type="printer" />
                  生成电子发票
                </Button>
                <Button
                  style={{ marginLeft: '12px' }}
                  disabled={rowData?.invFlagCode != 'E'}
                  onClick={() => this.writeOffElectronicInvoice52012301(rowData)}
                >
                  <Icon type="printer" />
                  红冲电子发票
                </Button>
                <Button
                  style={{ marginLeft: '12px' }}
                  disabled={rowData?.invFlagCode != 'E'}
                  onClick={() => this.printElectronicInvoice(rowData)}
                >
                  <Icon type="printer" />
                  打印电子发票
                </Button>
              */}
                {digitalFlag === 'Y' && (
                  <Button style={{ marginLeft: '12px' }} loading={verificationCodeLoading} onClick={this.handleVerificationCodeLogin}>验证码登陆</Button>
                )}
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                <Button
                  ghost
                  type="primary"
                  style={{ marginRight: '12px' }}
                  onClick={this.getYBPatientInfo}
                >
                  医保信息查询
                </Button>
                <Button
                  style={{ color: rowID ? '#fff' : '#ccc', backgroundColor: rowID ? '#80e8cd' : '', borderColor: rowID ? '#80e8cd' : '' }}
                  disabled={!rowID}
                  onClick={this.handleMedicalInsuranceRegistration}
                >
                  <Icon type="tags" style={{ color: rowID ? '#fff' : '#ccc', backgroundColor: rowID ? '#80e8cd' : '' }} />
                  {insuAdmObj && insuAdmObj.status !== 'N' && insuAdmObj.status !== 'D' ? '医保登记' : '取消登记'}
                </Button>
                <Button
                  style={{ margin: '0 12px' }}
                  disabled={!(rowData?.payStatusCode === 'OB')}
                  onClick={() => this.handleModifyVisible('splitBillVisible', true)}
                >
                  <Icon type="account-book" style={{ color: rowData?.payStatusCode === 'OB' ? '#13C2C2' : '#ccc' }} />
                  拆分账单
                </Button>
                <Button
                  style={{ color: rowID ? '#fff' : '#ccc', backgroundColor: rowID ? '#fa8c17' : '', borderColor: rowID ? '#fa8c17' : '' }}
                  disabled={!rowID}
                  onClick={this.handleAdvancePayment}>
                  <Icon type="transaction" style={{ color: rowID ? '#fff' : '#ccc', backgroundColor: rowID ? '#fa8c17' : '' }} />
                  预交金
                </Button>
                <Popconfirm
                  title="取消后不可恢复，确认取消结算吗?"
                  disabled={!(rowData?.payStatusCode === 'P')}
                  onConfirm={this.handleCancelSettlement}
                >
                  <Button
                    style={{ margin: '0 12px' }}
                    disabled={!(rowData?.payStatusCode === 'P')}
                  >
                    <Icon type="close-circle" style={{ color: rowData?.payStatusCode === 'P' ? 'red' : '#ccc' }} />
                    取消结算
                  </Button>
                </Popconfirm>
                <Button
                  type={rowData?.payStatusCode === 'TP' || rowData?.payStatusCode === 'OB' ? 'primary' : 'default'}
                  disabled={!(rowData?.payStatusCode === 'TP' || rowData?.payStatusCode === 'OB')}
                  onClick={this.handleClickSettlement}
                >
                  <Icon type="file-done" style={{ color: rowData?.payStatusCode === 'TP' || rowData?.payStatusCode === 'OB' ? '#fff' : '#ccc' }} />
                  结算
                </Button>
              </Col>
            </Row>
            <PublicTablePagination
              param={{
                page,
                total,
                loading,
                size: 'large',
                columns, // 表头配置
                data: tableData, // 表格数据
                x: totalWidth, // 表格的宽度
                y: store.getState().tableHeight.y + 68 - queryHeight,
                height: store.getState().tableHeight.y + 118 - queryHeight + 'px',
                componentName: 'IPAdmList',
              }}
              compilePage={this.compilePage}
              getColumns={this.getTableColumns}
              onClickRowPublic={this.onClickRowPublic}
              setRowClassNamePublic={this.setRowClassNamePublic}
            />
          </div>

          {/** 公共组件 消息提示框 */}
          <MessageModal onRef={ref => this.childMessageExamineRef = ref} />

          {/* 外链地址弹窗 */}
          <IframeModal onRef={ref => this.iframeRef = ref} />

          {/* 右键菜单 */}
          <div ref={(ref) => { this.root = ref }} className="common-right-menu-wrap" style={{ visibility: contextMenuvisible ? 'visible' : 'hidden', color: '#333' }}>
            <div className="common-right-menu-option" onClick={this.getHisBill}>账单</div>
            <div className="common-right-menu-option" onClick={this.handleInsuUPloadItem}>医保费用上传</div>
            <div className="common-right-menu-option" onClick={this.handleCancleInsuUPloadItem}>撤销上传的医保费用</div>
            <div className="common-right-menu-option" onClick={this.handleInsuIPPayModal}>医保试算</div>
            <div className="common-right-menu-option" onClick={this.handleUnbudgetAndLevRegistra}>取消出院登记</div>
            <div className="common-right-menu-option" onClick={this.handleUnbudgetAndSettlement}>取消预结算</div>
            <div className="common-right-menu-option" onClick={this.handleUnionBill}>取消拆分账单</div>
            <div className="common-right-menu-option" onClick={this.handleCopyToClipboard}>复制身份证号</div>
            <div className="common-right-menu-option" onClick={this.handleCancelRegister}>退院</div>
            <div className="common-right-menu-option" onClick={this.handleInsuSignin}>异地医保签到</div>
            <div className="common-right-menu-option" onClick={this.handleInsuSignout}>异地医保签退</div>
            <div className="common-right-menu-option" onClick={this.handleUpdateInsuRegInfo}>医保信息变更</div>
            <div className="common-right-menu-option" onClick={this.handleCancelInsuRegInfo}>撤销异常医保登记</div>
            {/* <div className="common-right-menu-option" onClick={this.handleCancelOutHospReg}>取消出院登记</div> */}
          </div>

          {/* 医保登记 */}
          <INSURegister
            size="small"
            onRef={ref => this.INSURegisterRef = ref}
            admID={rowData?.admID || ''}
            admReasonCode={rowData?.admReasonCode || ''}
          />

          {/* 拆分账单 */}
          <Modal
            visible={splitBillVisible}
            width="1500px"
            title="拆分账单"
            footer={null}
            onCancel={() => this.handleModifyVisible('splitBillVisible', false)}
          >
            <SplitBills tableHeight={300} key={rowData?.patBillID || ''} paras={{ userInfo, patBillID: rowData?.patBillID || '' }} />
          </Modal>

          {/* 费用清单 */}
          <Modal
            visible={expenseListVisible}
            width="1300px"
            title="费用清单"
            footer={null}
            onCancel={() => this.handleModifyVisible('expenseListVisible', false)}
          >
            <ListOfHospitalizationExpenses tableHeight={400} key={rowData?.patBillID || ''} patBillID={rowData?.patBillID || ''} userInfo={userInfo} />
          </Modal>

          {/* 预交金 */}
          <Modal
            visible={advancePaymentVisible}
            width="1500px"
            title="预交金"
            footer={null}
            bodyStyle={{ height: '690px', padding: '12px' }}
            onCancel={() => this.handleModifyVisible('advancePaymentVisible', false)}
          >
            <PatientAccountManagement
              typeCinFlage="I"
              tableHeight={400}
              key={rowData?.patNo}
              number={rowData?.patNo}
              onRef={ref => this.advancePaymentRef = ref}
            />
          </Modal>

          {/* 扫码 */}
          <ScanCodeModal onRef={ref => this.scanCodeChild = ref} handleConfirm={this.handleConfirmCompletion} type="I" />

          {/* 结算最后一步，确认弹框 */}
          <Modal
            visible={confirmSettlementVisible}
            width="1300px"
            title={
              <div>
                结算
                <span className="greenSpan">
                  {' ' + userPayData.patName + ' ( ' + userPayData.patNo + ' ) 结算类型:' + userPayData.payReasonDesc + '  入院日期:' + ' ' + userPayData.admDate + ' ' + userPayData.admTime + '  出院日期:' + userPayData.nurseChargeDate + ' ' + userPayData.nurseChargeTime}
                </span>
              </div>
            }
            closable={false}
            maskClosable={false}
            footer={
              <div>
                <Button onClick={this.handleCancelMoney}>取消</Button>
                <Button ref={this.refHandleOK} type="primary" onClick={this.handleConfirmSettlementOK}>确认</Button>
              </div>
            }
            onCancel={this.handleCancelMoney}
          >
            <div>
              {paywamtData && paywamtData.length > 0 ? <Row>
                已支付方式信息：
                <Row className="ybpat-row">
                  {paywamtData.map((item, index) => {
                    return <Row><Col className="ybpat-col" span={8} key={index} offset={4}>
                      <p><i className="f1"></i>{item.desc}：</p><p className='p2'>￥<span>{item.value}</span></p>
                    </Col></Row>
                  })}
                </Row>
              </Row> : ''}
              <Row style={{ borderTop: '1px solid #ccc' }}>
                <Col span={8} offset={4}>
                  <div className="payBox">
                    <p><i className="f1"></i>本次医疗费用</p>
                    <p className="p2">￥<span>{this.state.patAmt || '0.00'}</span></p>
                  </div>
                </Col>
                <Col span={8} offset={2}>
                  <div className="payBox">
                    <p><i className="f1"></i>剩余应收</p>
                    <p className="p2">￥<span>{this.state.leftAmt || '0.00'}</span></p>
                  </div>
                </Col>
              </Row>
              <Row className="mT10">
                <Col span={12}>
                  <Row className="mT10">
                    <Col span={8} className='modalLabel ' style={{ textAlign: 'right' }}>住院账户余额：</Col>
                    <Col span={16} >
                      <Input disabled className='input' addonBefore="￥" value={this.state.accAmtBalance} onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } }} />
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row className="mT10">
                    <Col span={8} className="modalLabel" style={{ textAlign: 'right' }}>对冲金额：</Col>
                    <Col span={16} >
                      <Input
                        disabled
                        addonBefore="￥"
                        style={{ width: '50%' }}
                        onChange={(e) => { this.onChangepayAccIPAmt(e); }}
                        value={this.state.payAccIPAmt}
                        onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } this.setState({ payAccIPAmt: parseFloat(event.target.value).toFixed(2) }) }}
                        onFocus={(event) => { if (event.target.value === '0.00') { event.target.value = '' } }}
                      />
                      <Input
                        style={{ width: '50%' }}
                        addonBefore="余"
                        value={this.state.accpayBalance}
                        onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } this.setState({ payAccIPAmt: parseFloat(event.target.value).toFixed(2) }) }}
                        onFocus={(event) => { if (event.target.value === '0.00') { event.target.value = '' } }}
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
              <Divider dashed style={{ margin: '12px' }} />
              <Row>
                <PublicTableEditable
                  columns={paymentMethodColumns}
                  handleSave={this.handleUpdataPayWListData}
                  onRef={ref => this.paymentMethodRef = ref}
                />
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                  <div style={{ textAlign: 'right', marginRight: '80px' }}>
                    <p style={{ color: 'rgba(240,65,52,1)' }}><span>剩余余额：￥{parseFloat(this.state.surplusamt) === 0 || isNaN(parseFloat(this.state.surplusamt)) ? 0 : parseFloat(this.state.surplusamt)}</span></p>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <Button icon="plus" onClick={this.handleAddTableData} style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>新增</Button>
                  </div>
                </div>
              </Row>
              <Row className="mT10" style={{ display: this.state.disXJ ? 'block' : 'none', borderTop: '1px solid #ccc' }} >
                <Divider dashed={true}>实收现金</Divider>
                <Col span={24}>
                  <Row className="mT5">
                    <Col span={5} className="modalLabel">实收现金：</Col>
                    <Col span={7} >
                      <Input
                        value={this.state.cashInCashVal}
                        onChange={(e) => { this.handleCashInCashChange(e.target.value) }}
                        className="input"
                        addonBefore="￥"
                        onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } this.setState({ cashInCashVal: parseFloat(event.target.value).toFixed(2) }) }}
                        onFocus={(event) => { if ((event.target.value === '0.00') || (event.target.value === '0')) { event.target.value = '' } }}
                        onPressEnter={() => { setTimeout(() => { this.refHandleOK.current.focus(); }, 1); }}
                      />
                    </Col>
                    <Col span={5} className="modalLabel" ></Col>
                    <Col span={7} >
                      <p style={{ color: parseFloat(this.state.zeroPay) < 0 ? 'rgba(240,65,52,1)' : '' }}><span>找零（元）：￥{this.state.zeroPay}</span></p>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </div>
          </Modal>

          {/** 右键修改费别 */}
          <Modal
            title="修改费别"
            visible={this.state.admReasonShow}
            onCancel={() => this.setState({
              admReasonShow: false,
              admReasonID: ''
            })}
            onOk={this.handleInsuReasonUpdate}
          >
            结算费别：<Select
              style={{ width: '150px', margin: '12px 15px 0 0' }}
              value={this.state.admReasonID}
              onChange={(val) => {
                if (val) {
                  this.setState({ admReasonID: val })
                }
              }}
              placeholder="请选择费别"
            >
              {this.state.admReasonArr.map((item, index) => <Option title={item.descripts} key={index} value={item.id} >{item.descripts}</Option>)}
            </Select>
          </Modal>
          <Modal
            title="设置发票号"
            width="600px"
            footer={null}
            destroyOnClose={true}
            visible={modalShow}
            onCancel={this.handleInvoiceCancel}
          >
            <HopNumber invTypeCode="I" key={invoice} handleCancel={this.handleInvoiceCancel} initJuris={this.handleInitJuris} />
          </Modal>
        </div>

        {/* 输入验证码 */}
        <VerificationCodeLogin onRef={ref => this.codeLoginRef = ref} closeLoading={this.modifyVerificationCodeLoading} />
      </Spin>
    )
  }
};

export default DischargeSettlementINSU;