/*
 * Create:      柿子
 * CreateDate:  2023/09/14
 * Describe：   手术清点
 * */
import React from 'react';
import { Modal, Button, Input, Card, Row, Col, Popconfirm, Icon, message } from 'antd';
import { Util } from 'tools';
import { $fastReportTemplate } from '../../lodop/Common/FastReportPrint.js';
import store from 'store';
import PatientInfo from '../Patient/PatientInfo.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
class OperativeCount extends React.Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    let patientData = React.$getSessionData('patientData');
    this.state = {
      userData,
      patientData,
      visible: false,
      rowData: {},
      selectData: {},
      columns: [],
      totalWidth: 0,
      formData: [],
      loading: false,
      tableData: [],
      rowID: '',
      scanningCode: undefined, // 扫码框
      printLoading: false,
      saveLoading: false
    };
    this.scanningRef = React.createRef();
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  modifyVisible = (visible, rowData = {}) => {
    if (visible) { // 打开弹窗
      const { columns, formData, selectData } = this.state;
      if (!(columns && columns.length > 0) || !(formData && formData.length > 0)) {
        this.getTableColumns();
      }
      if (!(selectData && selectData?.optionFlag === 'Y')) {
        this.getInitData();
      }
      this.setState({ visible, rowData }, () => {
        this.getTableData();
        setTimeout(() => {
          this.scanningRef?.current?.focus();
        }, 300)
      });
    } else { // 关闭弹窗
      const { tableData } = this.state;
      let modifyData = tableData.filter(item => item.modifyFlag === 'Y');
      if (modifyData && modifyData.length > 0) {
        Modal.confirm({
          title: '数据变动提醒',
          content: '存在修改未保存的数据，是否需要保存?',
          okText: '保存',
          cancelText: '不保存',
          onOk: () => {
            this.handleSave(this.handleCancel);
          },
          onCancel: () => {
            this.handleCancel();
          },
        });
      } else {
        this.handleCancel();
      }
    }
  }

  // 关闭弹窗
  handleCancel = () => {
    this.state.rowID = '';
    this.state.visible = false;
    this.state.rowData = {};
    this.state.tableData = [];
    this.state.scanningCode = undefined;
    this.formRef?.resetFields();
    this.setState({});
  }

  getInitData = async () => {
    try {
      let data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '03055012', data);
      let itemBagOptions = res?.result || [];
      for (let i = 0; i < itemBagOptions.length; i++) {
        itemBagOptions[i].id = itemBagOptions[i].sID;
        itemBagOptions[i].descripts = itemBagOptions[i].sName;
      }
      this.setState({ selectData: { itemBag: itemBagOptions, optionFlag: 'Y' } });
    } catch (error) {
      console.log(error);
    }
  }

  getTableData = async () => {
    try {
      const { rowData } = this.state;
      this.setState({ loading: true });
      let data = {
        params: [{
          ...rowData
        }]
      }
      let res = await React.$asyncPost(this, '03055014', data);
      let tableData = res?.result || [];
      for (let i = 0; i < tableData.length; i++) {
        tableData[i].key = i + 1;
        tableData[i].modifyFlag = 'N';
      }
      this.setState({ tableData, loading: false });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  }

  // 获取术前表单数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OperativeCount',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        }, () => {
          this.handleFilterColumns();
        })
      }
      let formData = res.result?.formData || [];
      if (formData && formData.length > 0) {
        formData.push({
          col: 2,
          typeCode: 'Button',
          type: 'primary',
          title: '添加',
          marginTop: 4,
          marginBottom: 0,
          onClick: this.handleAdd
        })
        this.setState({ formData });
      }
    } catch (error) {
      console.log(error);
    }
  }

  handleFilterColumns = () => {
    let { columns, userData } = this.state;
    columns = columns && columns.map((item, index) => {
      let dataIndex = item?.dataIndex || ';'
      return {
        ...item,
        inputType: item?.linkMethod || '',
        title: () => {
          return (
            <div>
              {userData?.language == 'EN' ? item.enDescripts : item.title}
              {dataIndex === 'preColCount' || dataIndex === 'aftColCount' ? (
                <Popconfirm title={'复制将会把手术前的数据覆盖到 ' + (dataIndex === 'preColCount' ? '关切口前' : '手术后') + '，确定复制吗?'} onConfirm={() => this.handleCopy(item)}>
                  <Button
                    ghost
                    size="small"
                    type="primary"
                    style={{ marginLeft: '6px', fontSize: '12px' }}
                  >
                    复制
                  </Button>
                </Popconfirm>
              ) : ''}
            </div>
          )
        },
        render: (text, record, index) => {
          if (dataIndex === 'preOpCount' || dataIndex === 'preColCount' || dataIndex === 'aftColCount') {
            return (
              <Input
                style={{ width: '95%' }}
                value={record && dataIndex in record ? record[dataIndex] : undefined}
                ref={ref => this[dataIndex + index] = ref}
                onChange={(e) => this.handleInputChange(index, e.target.value, item, record)}
                onKeyDown={(e) => this.handleKeyDown(dataIndex, index, item, e, record)}
              />
            )
          } else if (dataIndex === 'numeName') { // 二维码
            return this.handleCodeRender(text, record, index)
          } else {
            return text;
          }
        }
      }
    })
    this.setState({ columns });
  }

  // 复制
  handleCopy = (item) => {
    let dataIndex = item?.dataIndex || '';
    let { tableData } = this.state;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i][dataIndex] != (tableData[i]?.preOpCount || '')) {
        tableData[i].modifyFlag = 'Y';
        tableData[i][dataIndex] = tableData[i]?.preOpCount || '';
      }
    }
    this.setState({});
  }

  // 合并单元格
  handleCodeRender = (text, record, index) => {
    let { tableData } = this.state;
    const obj = { children: text, props: {} };
    const groups = tableData.reduce((acc, curr, idx) => {
      if (curr.numeName !== text) return acc;
      const prevGroup = acc[acc.length - 1];
      if (!prevGroup || idx > prevGroup.end + 1)
        acc.push({ start: idx, end: idx });
      else
        prevGroup.end = idx;
      return acc;
    }, []);
    const group = groups.find(g => g.start <= index && g.end >= index);
    if (!group) return obj;
    let rowSpan = index === group.start ? group.end - group.start + 1 : 0;
    obj.props.rowSpan = rowSpan;
    return obj;
  }

  handleInputChange = (index, val, item, record) => {
    let dataIndex = item?.dataIndex || '';
    record[dataIndex] = val;
    record.modifyFlag = 'Y';
    this.setState({});
  }

  //列跳转设置
  handleKeyDown = (dataIndex, index, item, e, record) => {
    const keyCode = e.keyCode;
    if (keyCode == '13' || keyCode == '39') { // 回车和右箭头
      let selectionEnd = 0;
      let selectionInputType = ['Input', 'InputNumber', 'inputNumber', 'InputTable', 'TextArea', 'Labelarea'];
      if (selectionInputType.indexOf(item?.inputType || '') > -1) {
        let currentVal = e.target.value;
        selectionEnd = this[dataIndex + index]?.input?.selectionEnd || 0;
        selectionEnd = currentVal.length - selectionEnd;
      }
      !selectionEnd && e?.preventDefault();
      !selectionEnd && this.getFocusNext(index, item, 'next');
    } else if (keyCode == '37') { // 左箭头
      let selectionStart = this[dataIndex + index]?.input?.selectionStart || 0;
      !selectionStart && e?.preventDefault();
      !selectionStart && this.getFocusNext(index, item, 'prev');
    } else if (keyCode == '38') { // 光标上移
      e?.preventDefault();
      this.getNextJumpAbleRowSubscript(index, item, 'prev', e)
    } else if (keyCode == '40') { // 光标下移
      e?.preventDefault();
      this.getNextJumpAbleRowSubscript(index, item, 'next', e);
    }
  }

  // 获取下一个可跳转的行下标并跳转
  getNextJumpAbleRowSubscript = (index, item, type, e) => {
    let { tableData } = this.state;
    function getNextIndex(currentIndex) {
      if ((currentIndex < 0 && type === 'prev') || (tableData.length < currentIndex && type === 'next')) {
        return 'none';
      }
      if (type === 'prev') {
        currentIndex = currentIndex - 1;
      } else {
        currentIndex = currentIndex + 1;
      }
      let currentEditingFlag = tableData[currentIndex]?.editingFlag || '';
      if (currentEditingFlag !== 'N') {
        return currentIndex;
      } else {
        return getNextIndex(currentIndex);
      }
    }
    let nextIndex = getNextIndex(index);
    let nextDataIndex = item?.dataIndex || '';
    if (nextIndex !== 'none' && nextDataIndex) {
      let currentDataIndex = nextDataIndex + nextIndex;
      nextDataIndex && this[currentDataIndex] && this[currentDataIndex].focus ? this[currentDataIndex].focus() : '';
    }
  }

  // 获取焦点
  getFocusNext = (index, item, type = 'next') => {
    let { columns } = this.state;
    let currentIndex = 0;
    let operateColumns = columns && [...columns].filter(item => !!item.inputType); // 获取可操作表头的数据
    for (let i = 0; i < operateColumns.length; i++) {
      if (operateColumns[i].dataIndex === item.dataIndex) {
        currentIndex = i;
        break;
      }
    }
    if ((type === 'prev' && currentIndex > 0) || (type === 'next' && currentIndex > -1)) {
      let count = type === 'next' ? currentIndex + 1 : currentIndex - 1;
      let nextDataIndex = operateColumns[count]?.dataIndex || '';
      let currentDataIndex = nextDataIndex + index;
      nextDataIndex && this[currentDataIndex] && this[currentDataIndex].focus ? this[currentDataIndex].focus() : '';
    }
  }

  // 手动添加
  handleAdd = async () => {
    let values = await this.formRef.handleSave();
    if (!(values && values.instrumentID)) {
      message.warning('请选择需要添加的器械!');
      return;
    }
    let { tableData } = this.state;
    let currentKey = tableData?.length + 1
    let addObj = {
      ...values,
      key: currentKey,
      numeName: values?.itemBagDesc || '',
      instrumentID: values?.instrumentID || '',
      descripts: values?.instrumentDesc || '',
      modifyFlag: 'Y'
    };
    tableData.push(addObj);
    this.setState({}, () => {
      this.handleFilterColumns();
      this.formRef?.setFieldsValue({ instrumentID: undefined }); // 清空器械名称
      setTimeout(() => {
        this['preOpCount' + (currentKey - 1)]?.focus(); // 手动添加后手术前输入域自动获取焦点
      }, 300)
    });
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key });
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

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

  // 扫码入库
  handleScanningCodePressEnter = async () => {
    try {
      let { scanningCode, tableData } = this.state;
      let data = {
        params: [{
          number: scanningCode
        }]
      }
      let res = await React.$asyncPost(this, '04160048', data);
      let scanningData = res.result || [];
      for (let i = 0; i < scanningData.length; i++) {
        scanningData[i].modifyFlag = 'Y';
      }
      this.setState({ scanningCode: undefined, tableData: Util.addKeyValueToDataSource([...tableData, ...scanningData]) }, () => {
        this.handleFilterColumns();
        setTimeout(() => {
          this.scanningRef.current?.focus();
        }, 300)
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 保存
  handleSave = async (callback) => {
    try {
      this.setState({ saveLoading: true });
      const { rowData, userData, tableData } = this.state;
      const data = {
        params: [{
          ...rowData,
          tableData,
          userID: userData?.userID || ''
        }]
      }
      const res = await React.$asyncPost(this, '03055015', data);
      message.success(res?.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      this.getTableData();
      callback && callback();
    } catch (error) {
      console.log(error);
      this.setState({ saveLoading: false });
    }
  }

  // 打印
  handlePrint = () => {
    const { tableData } = this.state;
    let modifyData = tableData.filter(item => item.modifyFlag === 'Y');
    if (modifyData && modifyData.length > 0) {
      Modal.confirm({
        title: '数据变动提醒',
        content: '存在修改未保存的数据，是否需要保存后再打印?',
        okText: '是->先保存',
        cancelText: '否->直接打印',
        onOk: () => {
          this.handleSave(this.handleHttpPrint)
        },
        onCancel: () => {
          this.handleHttpPrint();
        },
      })
    } else {
      this.handleHttpPrint();
    }
  }

  // 调用接口打印
  handleHttpPrint = async () => {
    try {
      this.setState({ printLoading: true });
      const { rowData, userData } = this.state;
      const data = {
        params: [{
          ...rowData,
          userID: userData?.userID || ''
        }]
      }
      const res = await React.$asyncPost(this, '04160022', data);
      this.setState({ printLoading: false });
      let printData = res.result?.data || [];
      let templateName = res?.result?.template || '';
      for (let i = 0; i < printData.length; i++) {
        let dataResult = printData[i];
        $fastReportTemplate(templateName, userData?.hospID, dataResult, '');
      }
    } catch (error) {
      console.log(error);
      this.setState({ printLoading: false });
    }
  }

  // 删除
  handleDelete = (record, index, e) => {
    React.$stopPropagation(e);
    if (record && (record.id)) {
      this.handleHttpDelete(record);
    } else {
      this.deleteRow(record.key);
    }
  }

  // 调用接口删除
  handleHttpDelete = async (record) => {
    try {
      const { userData } = this.state;
      const data = {
        params: [{
          id: [record?.id || ''],
          userID: userData?.userID || ''
        }]
      }
      const res = await React.$asyncPost(this, '04160020', data);
      message.success(res?.errorMessage || '删除成功');
      this.deleteRow(record.key);
    } catch (error) {
      console.log(error);
    }
  }

  // 本地删除数据
  deleteRow = (key) => {
    let { tableData } = this.state;
    tableData = tableData.filter(item => item.key !== key);
    this.setState({ tableData, rowID: '' });
  }

  render() {
    const { visible, rowData, patientData, formData, selectData, scanningCode, loading, columns, tableData, totalWidth, saveLoading, printLoading } = this.state;
    const operationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record, index) => {
        return (
          record?.deleteFlag === 'N' ? ( // 已保存的不让删除
            <span style={{ cursor: 'no-drop' }}>
              <Icon type="delete"></Icon>
              删除
            </span>
          ) : (
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onClick={(e) => React.$stopPropagation(e)} onConfirm={(e) => this.handleDelete(record, index, e)}>
              <Icon type="delete" className="common-record-delete-span"></Icon>
              <span className="span common-record-delete-span">删除</span>
            </Popconfirm>
          )
        )
      }
    };

    return (
      <Modal
        title="手术清点"
        width="60vw"
        maskClosable
        visible={visible}
        bodyStyle={{ padding: '12px' }}
        onCancel={() => this.modifyVisible(false)}
        footer={[
          <Button key="1" type="primary" loading={saveLoading} onClick={() => this.handleSave()}>
            保存
          </Button>,
          <Button key="2" ghost type="primary" loading={printLoading} onClick={this.handlePrint}>
            打印
          </Button>
        ]}
      >
        <div style={{ maxHeight: '80vh', overflow: 'auto' }}>
          <PatientInfo admID={rowData?.admID || patientData?.admID || ''} />
          <div className="table-body-height" style={{ marginTop: '6px' }}>
            <Row>
              <Col span={9}>
                <div
                  style={{ position: 'relative', height: '100%', paddingRight: '24px' }}
                >
                  <Card
                    size="small"
                    bordered={false}
                    title={(
                      <div className="card-title-left-icon">
                        <div></div>
                        扫码添加
                      </div>
                    )}
                    bodyStyle={{ paddingBottom: 0, paddingTop: '16px' }}
                  >
                    <Input
                      ref={this.scanningRef}
                      placeholder="扫码添加"
                      value={scanningCode}
                      style={{ width: '90%', marginRight: '12px' }}
                      onChange={Util.commonInputChange.bind(this, 'scanningCode')}
                      onPressEnter={this.handleScanningCodePressEnter}
                    />
                  </Card>
                  <div className="common-card-right-split-line" style={{ width: 24, background: '#fff' }}></div>
                </div>
              </Col>
              <Col span={15}>
                <Card
                  size="small"
                  bordered={false}
                  title={(
                    <div className="card-title-left-icon">
                      <div></div>
                      手动添加
                    </div>
                  )}
                  bodyStyle={{ paddingBottom: 0 }}
                >
                  <DynamicRenderingForm
                    rowData={{}}
                    selectData={selectData}
                    formData={formData}
                    onRef={ref => this.formRef = ref}
                  />
                </Card>
              </Col>
            </Row>
            <PublicTablePagination
              param={{
                loading,
                data: tableData, // 表格数据
                x: totalWidth, // 表格的宽度
                y: store.getState().tableHeight.y - 200,
                height: store.getState().tableHeight.y - 150 + 'px',
                componentName: 'OperativeCount',
                columns: columns && columns.length > 0 ? [...columns, operationObj] : [], // 表头配置
              }}
              getColumns={this.getTableColumns}
              onClickRowPublic={this.onClickRowPublic}
              setRowClassNamePublic={this.setRowClassNamePublic}
            />
          </div>
        </div>
      </Modal>
    )
  }
};

export default OperativeCount;