/*
 * Create:      柿子
 * CreateDate:  2023/12/27
 * Describe：   出院
 * */
import React, { Component } from 'react';
import { Modal, message, Row, Col, Card, Button } from 'antd';
import { Util } from 'tools';
import PatientInfo from './PatientInfo'; // 患者信息展示
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import './style/index.less';

class HandlingDischargeProcedures extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      visible: false,
      selectData: {},
      rowData: {},
      orderList: [],
      handleOrderBtn: [],
      totalWidth: 0,
      columns: [],
      orderLoading: false,
      selectedRowKeys: [],
      selectedRows: [],
      formData: [],
      disType: '1', // disType 1 医疗结算 2 撤销医疗结算 3 护士办理出院 4 护士撤销出院
    }
  };

  componentDidMount() {
    this.props && 'onRef' in this.props && this.props.onRef(this);
  };

  modifyVisible = (visible, rowData = {}) => {
    const { columns, selectData } = this.state;
    if (visible) {
      !(columns && columns.length > 0) && this.getTableColumns();
      selectData?.isFirstCall !== 'N' && this.getSelectData();
    }
    this.setState({ visible, rowData }, () => {
      visible && this.getOrderList();
    });
  };

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      const { userData } = this.state;
      let data = {
        params: [{
          type: 'C',
          compontName: 'HandlingDischargeProcedures',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'ordStatusDesc' && text.indexOf('停') > -1) { // 状态
                return (
                  <span className="common-record-delete-span">{text}</span>
                );
              } else {
                return text;
              }
            }
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      let formData = res?.result?.formData || [];
      for (let i = 0; i < formData.length; i++) {
        let docDisabledArr = ['admDocChargeDate', 'admDocChargeTime', 'discharge', 'selCondition', 'patDeceasedDate', 'patDeceasedTime'];
        if (docDisabledArr.indexOf(formData[i]?.dataIndex) > -1 && userData?.groupDesc?.indexOf('护士') > -1) {
          formData[i].disabled = 'Y';
        }
        let nurseDisabledArr = ['admNurChargeDate', 'admNurChargeTime'];
        if (nurseDisabledArr.indexOf(formData[i]?.dataIndex) > -1 && userData?.groupDesc?.indexOf('护士') < 0) {
          formData[i].disabled = 'Y';
        }
        if (formData[i]?.dataIndex === 'selCondition') { // 离院原因
          formData[i].callBackResult = 'Fn';
          formData[i].changeCallBack = this.handleSelConditionChange;
        }
      }
      this.setState({ formData });
    } catch (error) {
      console.log(error)
    }
  };

  // 离院原因change事件
  handleSelConditionChange = (e, dataIndex, record) => {
    let { formData } = this.state;
    let detailItem = record?.detailItem || [];
    let selectRecord = Util.returnDataCccordingToAttributes(detailItem, e);
    for (let i = 0; i < formData.length; i++) {
      if (formData[i]?.dataIndex === 'patDeceasedDate' || formData[i]?.dataIndex === 'patDeceasedTime') { // 死亡日期 |死亡时间
        formData[i].display = selectRecord?.dieFlag === 'Y' ? 'Y' : 'N';
      }
    }
    this.setState({ formData });
  }

  getSelectData = async () => {
    try {
      let data = {
        params: [{
          typeCode: 'recall'
        }]
      };
      let res = await React.$asyncPost(this, '04050012', data);
      let selectData = res?.result || {};
      this.setState({
        selectData: { ...selectData, isFirstCall: 'N' }
      });
    } catch (error) {
      console.log(error);
    }
  };

  // 获取患者信息
  getPatientInfo = async () => {
    try {
      const { rowData, userData } = this.state;
      let data = {
        params: [{
          admID: rowData?.admID || '',
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, '04020007', data);
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  }

  // 获取需关注医嘱列表(护士办出院)
  getOrderList = async () => {
    try {
      this.setState({ orderLoading: true });
      const { rowData, userData } = this.state;
      let data = {
        params: [{
          power: 'discharge',
          deptType: userData?.groupDesc?.indexOf('护士') < 0 ? 'D' : 'N',
          admID: rowData?.admID || '',
        }]
      }
      let res = await React.$asyncPost(this, '04060026', data);
      let orderList = Util.addKeyValueToDataSource(res?.result || []);
      let okDisable = orderList && orderList.length > 0 ? true : false;
      this.setState({ orderList, okDisable, orderLoading: false, selectedRows: [], selectedRowKeys: [], handleOrderBtn: [], ordCheckData: [] });
    } catch (error) {
      console.log(error);
      this.setState({ orderLoading: false });
    }
  };

  handleCheckChange = (record, selected) => {
    let currentKey = record?.key || '';
    let { orderList, selectedRowKeys, selectedRows } = this.state;
    let pSelectedRowKeys = [];
    if (!(selectedRows && selectedRows.length > 0)) {
      if (selected) {
        pSelectedRowKeys.push(record?.abnorCode);
      }
      for (let i = 0; i < orderList.length; i++) {
        if (pSelectedRowKeys.indexOf(orderList[i]?.abnorCode) > -1) {
          selectedRowKeys.push(orderList[i].key);
          selectedRows.push(orderList[i]);
        }
      }
    } else {
      if (selected) {
        let typeFlag = true;
        for (let i = 0; i < selectedRows.length; i++) {
          if (selectedRows[i].abnorCode !== record?.abnorCode) {
            typeFlag = false;
            break;
          }
        }
        if (!typeFlag) {
          message.error('请先勾选同类型的医嘱进行处理！')
          return;
        }
        selectedRowKeys.push(currentKey);
        selectedRows.push(record)
      } else {
        selectedRowKeys = selectedRowKeys.filter(item => item !== currentKey);
        selectedRows = selectedRows.filter(item => item.key !== currentKey);
      }
    }
    this.setState({
      selectedRowKeys,
      selectedRows
    }, () => {
      this.getHandleOrderBtn();
    })
  };

  // 全选
  handleCheckAllChange = (selected) => {
    let { orderList } = this.state;
    let selectedRowKeys = [], selectedRows = [];
    if (!(this.state.selectedRows && this.state.selectedRows.length > 0)) {
      if (selected && orderList && orderList.length > 0) {
        let firstAbnorCode = orderList[0]?.abnorCode || '';
        for (let i = 0; i < orderList.length; i++) {
          if (orderList[i].abnorCode === firstAbnorCode) {
            selectedRowKeys.push(orderList[i].key);
            selectedRows.push(orderList[i]);
          }
        }
      }
    }
    this.setState({ selectedRows, selectedRowKeys }, () => {
      this.getHandleOrderBtn();
    });
  };

  // 获取选中数据操作按钮
  getHandleOrderBtn = () => {
    let { selectedRows } = this.state;
    let handleOrderBtn = [];
    let ordCheckData = [];
    if (selectedRows && selectedRows.length > 0) {
      let firstUsedMethod = selectedRows[0]?.usedMethod || '';
      handleOrderBtn = firstUsedMethod && firstUsedMethod.split('^');
      for (let i = 0; i < selectedRows.length; i++) {
        ordCheckData.push(selectedRows[i].ordID);
      }
    }
    this.setState({ handleOrderBtn, ordCheckData })
  };

  // 处理医嘱
  handleProcessingMedicalOrders = async () => {
    try {
      let res = await React.$asyncPost(this, '04030004');
      this.setState({ signVisible: true, date: res?.date || '', time: res?.time || '', typeCode: 'A' });
    } catch (error) {
      console.log(error);
    }
  };

  // 停止执行
  handleStopExecution = async () => {
    try {
      const { selectedRows, userData } = this.state;
      let execIDArr = [];
      for (let i = 0; i < selectedRows.length; i++) {
        let currentExecIDArr = selectedRows[i]?.execIDArr || [];
        execIDArr = [...execIDArr, ...currentExecIDArr];
      }
      let data = {
        params: [{
          code: 'DE',
          ordIDs: execIDArr, // 执行记录
          userID: userData?.userID || '',
          locID: userData?.locID || '',
        }]
      }
      let res = await React.$asyncPost(this, '04030003', data);
      message.success(res?.errorMessage || '操作成功');
      this.getOrderList();
    } catch (error) {
      console.log(error);
    }
  }

  // 领药审核
  handleDrugReceivingReview = async () => {
    try {
      const { selectedRows, userData } = this.state;
      let medIDAry = [];
      for (let i = 0; i < selectedRows.length; i++) {
        medIDAry.push(selectedRows[i].medID)
      }
      let data = {
        params: [{
          medIDAry,
          userID: userData?.userID || '',
          process: selectedRows[0]?.process || '',
          auditFlag: 'Y'
        }]
      }
      let res = await React.$asyncPost(this, '04060013', data);
      message.success(res?.errorMessage || '审核成功');
      this.getOrderList();
    } catch (error) {
      console.log(error);
    }
  };

  // 确认
  handleOk = () => {

  };

  render() {
    const { visible, rowData, orderList, handleOrderBtn, totalWidth, columns, orderLoading, selectedRowKeys, selectedRows, selectData, formData } = this.state;
    return (
      <Modal
        title="出院"
        okText="出院"
        width="60vw"
        bodyStyle={{ padding: '12px', paddingTop: '6px' }}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="handling-discharge-procedures">
          <PatientInfo patInfo={rowData} />
          <Row style={{ paddingTop: '10px' }}>
            <Col span={12} style={{ paddingRight: '8px' }}>
              <Card
                size="small"
                className="hdp-card"
                title={<div className="card-title-left-icon"><div></div>未处理医嘱</div>}
                extra={(
                  handleOrderBtn && Array.isArray(handleOrderBtn) && handleOrderBtn.length > 0 ? handleOrderBtn.map((item, index) => {
                    return (
                      <Button
                        key={index}
                        size="small"
                        style={{ marginLeft: index > 0 ? '12px' : '0' }}
                        type={item === 'stop' ? 'danger' : 'primary'}
                        onClick={item === 'audit' ? this.handleDrugReceivingReview : (item === 'stop' ? this.handleStopExecution : this.handleProcessingMedicalOrders)}
                      >
                        {item === 'audit' ? '领药审核' : (item === 'stop' ? '停止执行' : '处理')}
                      </Button>
                    )
                  }) : <span style={{ color: '#999', fontSize: '13px' }}>提示：可勾选医嘱进行处理！</span>
                )}
              >
                <PublicTablePagination
                  param={{
                    y: 350,
                    height: '400px',
                    data: orderList, // 表格数据
                    x: totalWidth, // 表格的宽度
                    columns, // 表头配置
                    loading: orderLoading,
                    componentName: 'HandlingDischargeProcedures',
                  }}
                  getColumns={this.getTableColumns}
                  rowSelectionPublic={{
                    selectedRowKeys,
                    selectedRows,
                    onSelect: this.handleCheckChange,
                    onSelectAll: this.handleCheckAllChange,
                  }}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card
                size="small"
                bodyStyle={{ height: '424px' }}
                title={<div className="card-title-left-icon"><div></div>其他信息</div>}
              >
                <DynamicRenderingForm
                  rowData={{}}
                  selectData={selectData}
                  formData={formData}
                  onRef={ref => this.formRef = ref}
                />
              </Card>
            </Col>
          </Row>
        </div>
      </Modal>
    )
  }
};

export default HandlingDischargeProcedures;