/*
 * Create:      柿子
 * CreateDate:  2022/08/31
 * Describe：   配镜管理 - 详情
 * */
import React, { Component } from 'react';
import { Modal, Card, Steps, Button, Tooltip, Popconfirm, message, Icon, Spin, Checkbox, Tag } from 'antd';
import { Util } from 'tools';
import { httpConfig } from 'containers/config/httpConfig'
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import '../style/index.less';
const { Step } = Steps;

class MatchingDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      orderSetData: [], // 镜片参数数据
      rowData: {},
      stepsData: [],
      currentStep: 1,
      patInfo: {}, // 患者信息
      uploadUrl: '',
      saveFlag: 'N', // 保存标志，是否点了保存按钮
      activeKey: '',
      activeData: {}, // 选中数据
      loading: false,
      checked: false, // 显示本销售单所有产品
      solutionLoading: false,
      solutionColumns: [],
      solutionTotalWidth: 0,
      solutionTableData: [],
      selectedRowKeys: []
    };
    // 逆流程状态code，需要展示红点的
    this.errorStatusCode = ['07', '09', '10', '20', '21', '22', '23', '24', '25', '27', '28', '52'];
    this.operationInterfaceType = ['Y', 'K', 'N', 'ProcurementPlan', 'ReturnOrder', 'G', 'exchange'];
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    let httpUrl = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? httpConfig.ipDeault : windowHost;
    let uploadUrl = httpUrl + '/images/optomefile/';
    this.setState({ uploadUrl });
  }

  // 修改弹窗状态
  modifyVisible = (visible, record = {}, isGetDetails = 'Y') => {
    const { saveFlag, solutionColumns } = this.state;
    if (visible) {
      if (!(record?.glassesRequestID || record?.requestID) && !(solutionColumns && solutionColumns.length > 0)) {
        this.getSolutionTableColumns();
      }
      this.setState({ rowData: record });
    } else { // 关闭弹窗时
      saveFlag === 'Y' && this.props.handleQuery && this.props.handleQuery();
    }
    this.setState({ visible, saveFlag: 'N', activeKey: '', activeData: {}, stepsData: [], checked: false }, () => {
      if (this.state.visible && isGetDetails !== 'N') {
        record?.glassesRequestID || record?.requestID ? this.getMatchingDetails() : this.getSolutionMatchingDetails();
      }
    })
  }

  // 获取申请单详情
  getMatchingDetails = async () => {
    try {
      const { interfaceFlag } = this.props;
      const { rowData } = this.state;
      this.setState({ loading: true });
      let data = {
        params: [{
          suppFlag: rowData?.suppFlag || 'N', // 订单管理Y
          componentName: rowData?.suppFlag || 'N',
          glassesRequestID: rowData?.glassesRequestID || rowData?.requestID, // 17030025 - 按申请单查询(2023/12/11)
          admID: rowData?.admID || '',
        }]
      }
      let res = await React.$asyncPost(this, '17030104', data);
      let orderSetData = res?.result?.detailArr || []
      for (let i = 0; i < orderSetData.length; i++) {
        let index = i;
        let eyeData = orderSetData[index]?.eye || [];
        let orderSet = orderSetData[index]?.orderSet || [];
        orderSetData[index].index = index;
        orderSetData[index].rowData = {
          product: orderSetData[index]?.projectDesc || '',
          price: orderSetData[index]?.price || 0,
          valueData: eyeData,
          varietiesRecord: {
            price: orderSetData[index]?.price || 0,
            stockID: orderSetData[index]?.stockItemID || ''
          },
          ...this.filterRowData(eyeData, orderSet, index)
        }
        orderSetData[index].formData = this.getEyeFormData(orderSet, index, orderSetData[index])
      }
      this.setState({
        orderSetData,
        loading: false,
        patInfo: res.result?.admObj || {}
      }, () => {
        // 默认选中点击的订单
        let currentOrderSetData = orderSetData && orderSetData.filter(item => String(item?.glassesRequestID || item?.requestID || '') === String(rowData?.glassesRequestID || rowData?.requestID || ''));
        if (currentOrderSetData && currentOrderSetData.length > 0) {
          this.handleCardClick(currentOrderSetData[0]);
          setTimeout(() => {
            let currentIndex = currentOrderSetData[0]?.index || 0;
            let eyeCardBody = document.getElementById((interfaceFlag + 'md-eye-body'));
            if (eyeCardBody && eyeCardBody.scrollWidth) {
              eyeCardBody.scrollLeft = 572 * currentIndex;
            }
          }, 100)
        }
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 获取表单回显数据
  filterRowData = (eyeData, orderSet, index) => {
    let returnVal = {};
    if (eyeData && Array.isArray(eyeData)) {
      this['eyeFormRef_' + index] && this['eyeFormRef_' + index].resetFields();
      for (var i = 0; i < eyeData.length; i++) {
        let leftTypeCode = orderSet && orderSet.length > 0 ? Util.returnDataCccordingToAttributes(orderSet, eyeData[i].fieldCode, 'code')?.componentTypeCode : '';
        returnVal[eyeData[i].fieldCode] = leftTypeCode === 'Select' ? eyeData[i].reqFieldValueID : eyeData[i].reqFieldValue;
      }
    }
    return returnVal;
  }

  // 获取步骤条数据
  getStepsData = (stepsData) => {
    const { interfaceFlag } = this.props; // 用于区分界面来源
    // 当前所在步骤
    let currentStep = 0;
    for (let i = 0; i < stepsData.length; i++) {
      if (stepsData[i].handleFlag === 'Y') {
        currentStep = i;
      }
    }
    this.setState({ stepsData, currentStep }, () => {
      setTimeout(() => {
        var gundong = document.getElementById((interfaceFlag + 'md-steps'));
        if (gundong && gundong.scrollHeight) {
          gundong.scrollTop = gundong.scrollHeight - (63 * (stepsData.length - 1 - currentStep) + 90);
        }
      }, 100)
    })
  }

  // 获取表单数据
  getEyeFormData = (formData, propIndex, propItem) => {
    const { rowData } = this.state;
    const suppFlag = rowData?.suppFlag || ''; // 父组件标识
    const curStatusCode = propItem?.curStatusCode || ''; // 当前状态
    const initFormData = [{
      dataIndex: 'product',
      placeholder: '请先在右侧选中产品',
      title: '配镜产品', //  + '(' + (dataIndex === 'leftEyeFormData' ? 'OS' : 'OD') + ')'
      typeCode: 'Input', // TextArea
      required: 'Y',
      disabled: 'Y',
      col: 24
    }];
    formData = formData && formData.map((item, index) => {
      return {
        ...item,
        isEnterJump: 'Y', // 回车下一个输入域
        dataIndex: item.code,
        required: item.required,
        defaultValue: undefined,
        typeCode: item.componentTypeCode,
        col: Number(item?.seatSize || 24),
        detailItem: item?.selectData || [],
        doubt: item?.inputTip || '', // 输入域描述
        title: item.descripts, // + '(' + (dataIndex === 'leftEyeFormData' ? 'OS' : 'OD') + ')'
        addonAfter: (
          item.unitDesc !== 'none' ? (
            <Tooltip title={item.unitDesc || '单位'}>
              <span className='ellipsis' style={{ color: item.unitDesc ? '#666' : '#d9d9d9', width: '36px', display: 'block' }}>{item.unitDesc || '单位'}</span>
            </Tooltip>
          ) : ''
        ),
        disabled: suppFlag === 'Y' ? 'Y' : (
          ( // 验配师 - 配镜申请单列表
            (curStatusCode === '01' || curStatusCode === '10' || curStatusCode === '20' || propItem?.updateFlag === 'Y' || curStatusCode === '25') && rowData.suppFlag === 'N'
          ) || ( // 退回订单
            (curStatusCode === '06' || curStatusCode === '36') && rowData.suppFlag === 'ReturnOrder'
          ) || ( // 处方流转
            rowData.suppFlag === 'exchange' ? item.readOnly : 'Y'
          )
        ), // 退镜也可修改参数
        linkStaticParams: item && 'linkStaticParams' in item && item.linkStaticParams ? item.linkStaticParams : { productBrandOrderSetID: item?.productBrandOrderSetID || '' }, // 表单静态参数
        onSelect: item.componentTypeCode === 'Select' ? () => this.handleSelectChange(item, propIndex) : '',
      }
    });
    if (formData && formData.length > 0) {
      formData = [...initFormData, ...formData];
    }
    return formData;
  }

  handleSelectChange = (record, index) => {
    // 修改加急标志/加急标志修改如果是同一个品牌的话就一起修改掉
    if (record?.code === 'Urgent') { // 加急标志 - 改版后没法处理了
      this.handleUrgentModify(record, index)
    }
  }

  // 修改加急标志
  handleUrgentModify = (record, index) => {
    const { orderSetData } = this.state;
    let currentRowData = record?.rowData || {};
    let reqNoArr = orderSetData && orderSetData.filter(item => item?.reqNo === record?.reqNo); // 过滤出相同订单号的数据
    if (reqNoArr && reqNoArr.length > 1) {
      let value = this['eyeFormRef_' + index] && this['eyeFormRef_' + index].getFieldsValue();
      for (let i = 0; i < reqNoArr.length; i++) {
        if (reqNoArr[i]?.brandID === currentRowData?.brandID) { // 相同订单号且品牌一样的话直接修改对应的加急标志
          let opposeIndex = i;
          this['eyeFormRef_' + opposeIndex] && this['eyeFormRef_' + opposeIndex].setFieldsValue({
            Urgent: value?.Urgent || undefined
          });
        }
      }
    }
  }

  // 发货详情
  getDeliverGoods = (deliver) => {
    const { uploadUrl } = this.state;
    return (
      <div className="md-deliver-goods">
        <div className="md-deliver-goods-title">
          发货详情
        </div>
        {deliver && deliver.map((item, index) => {
          let valueArrIndex = item.part === 'L' ? 'leftValueArr' : 'rightValueArr';
          return (
            <>
              {index % 2 === 1 ? <div style={{ borderTop: '1px dashed #e8e8e8', height: 1 }}></div> : ''}
              <div key={index} style={{ padding: '6px 0' }}>
                <div className="md-deliver-goods-item">
                  <span className="md-deliver-goods-item-label">产品名称：</span>
                  <span className="md-deliver-goods-item-value">{item?.medDesc || ''}</span>
                </div>
                <div className="md-deliver-goods-item">
                  <span className="md-deliver-goods-item-label">眼别：</span>
                  <span className="md-deliver-goods-item-value">{item?.part === 'L' ? '左眼' : '右眼'}</span>
                </div>
                <div className="md-deliver-goods-item">
                  <span className="md-deliver-goods-item-label">生产日期：</span>
                  <span className="md-deliver-goods-item-value">{item?.produceDate || ''}</span>
                </div>
                <div className="md-deliver-goods-item">
                  <span className="md-deliver-goods-item-label">有效日期：</span>
                  <span className="md-deliver-goods-item-value">{item?.expDate || ''}</span>
                </div>
                <div className="md-deliver-goods-item">
                  <span className="md-deliver-goods-item-label">产品编号：</span>
                  <span className="md-deliver-goods-item-value">{item?.productNo || ''}</span>
                </div>
                <div className="md-deliver-goods-item-matching-detail" onClick={() => this.handleViewLensParameters(item, index)}>
                  <span>{item.visible ? '收起' : '查看'}配镜参数</span>
                  <Icon type={item.visible ? 'caret-up' : 'caret-down'} />
                </div>
                <div style={{ display: item.visible ? 'block' : 'none', color: '#ddd', paddingTop: '4px' }}>
                  {valueArrIndex in item && item[valueArrIndex] && item[valueArrIndex].length > 0 ? item[valueArrIndex].map((detailItem, detailIndex) => {
                    let reqFieldValue = typeof (detailItem?.reqFieldValue) === 'string' ? (detailItem?.reqFieldValue || '') : (Array.isArray(detailItem?.reqFieldValue) ? detailItem?.reqFieldValue : []);
                    return (
                      <div key={detailIndex} className="md-deliver-goods-item">
                        <span className="md-deliver-goods-item-label" style={{ width: '120px' }}>{detailItem?.reqFieldDesc || ''}{valueArrIndex === 'leftValueArr' ? '(OS)' : '(OD)'}：</span>
                        {typeof (reqFieldValue) === 'string' ? (
                          <span className="md-deliver-goods-item-value" style={{ width: '90px' }}>
                            {/* 展示数据 */}
                            {reqFieldValue + ' ' + (detailItem?.unitDesc || '单位')}
                          </span>
                        ) : (
                          // 展示附件
                          <div className="md-deliver-goods-item-value" style={{ width: '90px' }}>
                            {reqFieldValue && reqFieldValue.map((fileItem, fileIndex) => {
                              return (
                                <div key={fileIndex}>
                                  <a href={uploadUrl + fileItem.filePath} target="_Blank">{fileItem.name}</a>
                                </div>
                              )
                            })}
                          </div>
                        )}
                      </div>
                    )
                  }) : ''}
                </div>
              </div>
            </>
          )
        })}
      </div>
    )
  }

  // 查看配镜参数
  handleViewLensParameters = (item, index) => {
    item.visible = !item.visible;
    this.setState({});
  }

  // 获取悬浮文字
  getFloatDesc = (floatDesc) => {
    let fTitle = floatDesc && typeof (floatDesc) === 'string' && floatDesc.indexOf('/title') > -1 ? floatDesc.split('/title')[0] : '';
    let fContent = floatDesc && typeof (floatDesc) === 'string' && floatDesc.indexOf('/title') > -1 ? floatDesc.split('/title')[1] : '';
    let fContentArr = fContent ? fContent.split('/n') : floatDesc.split('/n');
    return (
      <div className="md-deliver-goods">
        <div style={{ display: fTitle ? 'block' : 'none' }} className="md-deliver-goods-title">
          {fTitle}
        </div>
        <div style={{ padding: '8px 0', height: '50vh', overflow: 'auto' }} className="scroll-bar-style">
          {fContentArr && fContentArr.map((item, index) => {
            if (item && item.indexOf('<br/>') > -1) {
              let brStr = item.split('<br/>')[1];
              return (
                <>
                  <div style={{ borderBottom: '1px dashed #e8e8e8', height: 1, margin: '6px 0' }}></div>
                  <div key={index}>
                    {this.handleTextAlignment(brStr, index)}
                  </div>
                </>
              )
            } else {
              return this.handleTextAlignment(item, index);
            }
          })}
        </div>
      </div>
    )
  }

  // 获取退回原因
  getRemarkDesc = (floatDesc, record) => {
    let reasonDesc = floatDesc && typeof (floatDesc) === 'string' && floatDesc.indexOf('^') > -1 ? floatDesc.split('^')[0] : floatDesc;
    let remark = floatDesc && typeof (floatDesc) === 'string' && floatDesc.indexOf('^') > -1 ? floatDesc.split('^')[1] : '';
    return (
      <div className="md-deliver-goods">
        <div className="md-deliver-goods-title">
          {record.statusCode === '10' ? '退回原因' : (record.statusCode === '07' ? '退镜原因' : '详情')}
        </div>
        <div style={{ padding: '6px 0' }}>
          <div className="md-deliver-goods-item">
            <span className="md-deliver-goods-item-label" style={{ width: '50px' }}>原因：</span>
            <span className="md-deliver-goods-item-value">{reasonDesc}</span>
          </div>
          <div className="md-deliver-goods-item">
            <span className="md-deliver-goods-item-label" style={{ width: '50px' }}>备注：</span>
            <span className="md-deliver-goods-item-value">{remark || '暂无备注'}</span>
          </div>
        </div>
      </div>
    )
  }

  // 文字对齐
  handleTextAlignment = (str, index) => {
    if (str && str.indexOf(':') > -1) {
      let title = str.split(':')[0];
      let desc = str.split(':')[1];
      return (
        <div key={index} className="md-deliver-goods-item">
          <span className="md-deliver-goods-item-label">{title}：</span>
          <span className="md-deliver-goods-item-value">{desc}</span>
        </div>
      )
    } else {
      return str;
    }
  }

  // 修改订单状态
  modifyApplicationFormStatus = (statusCode, record) => {
    const { orderSetData } = this.state;
    let requestIDArr = [record?.glassesRequestID || record?.requestID];
    let toBeSendData = [];
    if (statusCode === '02') { // 如果查看详情点击发送，则需要判断是否还有其他待发送的订单，如果有的话则不关闭弹窗
      toBeSendData = orderSetData && orderSetData.filter(item => (item?.glassesRequestID || item?.requestID) !== (record?.glassesRequestID || record?.requestID)).filter(item => item?.curStatusCode === '01')
    }
    this.props.modifyApplicationFormStatus && this.props.modifyApplicationFormStatus(statusCode, requestIDArr, 'matchingDetails', '', toBeSendData && toBeSendData.length > 0 ? 'N' : 'Y');
  }

  // 判断内容是否修改
  whetherTheContentIsModified = (record, index) => {
    let values = this['eyeFormRef_' + index] && this['eyeFormRef_' + index].getFieldsValue();
    let rowData = record?.rowData || {};
    let modifyFlag = false;
    if (values && values.product) { // 左眼
      for (var leftValKey in values) {
        for (var leftRowKey in rowData) {
          if ((leftValKey === leftRowKey) && (values[leftValKey] !== rowData[leftRowKey])) {
            modifyFlag = true;
            break;
          }
        }
      }
    }
    return modifyFlag;
  }

  // 保存
  handleSave = async (fn, record, index) => {
    try {
      let formValues = {};
      if (record && record.projectDesc) {
        formValues = await this['eyeFormRef_' + index].handleSave('empty');
        if (formValues && formValues.error) {
          message.error('请完善必填信息。');
          return;
        }
      }
      let eyeData = this.handleCombineFormData(formValues, record?.formData || {}, record?.rowData?.valueData || []);
      let data = {
        params: [{
          admID: record?.admID || '', // 就诊ID
          glassesRequestID: record?.glassesRequestID || '',
          prePayAmt: record?.prePayAmt, // 预交金
          optoSourceID: record?.optoSourceID || '', // 来源渠道
          remark: record?.remark || '', // 备注
          fittingRemark: record?.fittingRemark || '', // 开单备注
          leftPrice: record && 'leftPrice' in record ? record.leftPrice : '',
          leftStockItemID: record?.leftStockItemID || '',
          leftEye: record?.part === 'L' ? eyeData : [],
          rightPrice: record && 'rightPrice' in record ? record.rightPrice : '',
          rightStockItemID: record?.rightStockItemID || '',
          rightEye: record?.part === 'R' ? eyeData : [],
        }]
      }
      if (fn === 'confirmTheMirrorRetraction') { // 确认退镜，在退镜接口去做保存
        this.props.getDetailsParams && this.props.getDetailsParams(eyeData);
        this.modifyVisible(false);
      } else {
        let res = await React.$asyncPost(this, '17030009', data);
        if (fn) {
          fn && fn();
        } else {
          this.setState({ saveFlag: 'Y' }); // 用于保存后关闭弹窗时是否需要调用外部传入的查询接口
          message.success(res.errorMessage || '保存成功');
        }
        let modifyFlag = this.whetherTheContentIsModified(record, index);
        modifyFlag && this.handleUpdateRowData(formValues, record, index);
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 更新参数，与保存类似
  handleParamsUpload = async (fn, record, index) => {
    try {
      let formValues = {};
      if (record && record.projectDesc) {
        formValues = await this['eyeFormRef_' + index].handleSave();
        if (formValues && formValues.error) {
          message.error('请完善必填信息。');
          return;
        }
      }
      let eyeData = this.handleCombineFormData(formValues, record?.formData || {}, record?.rowData?.valueData || []);
      let data = {
        params: [{
          admID: record?.admID || '', // 就诊ID
          glassesRequestID: record?.glassesRequestID || '',
          valueArr: eyeData,
        }]
      }
      let res = await React.$asyncPost(this, '17030106', data);
      if (fn) {
        fn && fn();
      } {
        message.success(res.errorMessage || '保存成功');
      }
      let modifyFlag = this.whetherTheContentIsModified(record, index);
      modifyFlag && this.handleUpdateRowData(formValues, record, index);
    } catch (error) {
      console.log(error);
    }
  };

  // 更新眼别数据
  handleUpdateRowData = (values, record) => {
    let rowData = record?.rowData || {};
    for (var rowKey in rowData) {
      for (var valKey in values) {
        if ((rowKey === valKey) && (rowData[rowKey] !== values[valKey])) {
          rowData[rowKey] = values[valKey];
        }
      }
    }
    this.setState({});
  }

  // 获取动态眼别表单数据
  handleCombineFormData = (values, dataSource, valueData) => {
    let combineFormData = [];
    if (dataSource && dataSource.length > 0) {
      for (var i = 0; i < dataSource.length; i++) {
        for (var keys in values) {
          if ((dataSource[i].dataIndex === keys) && (dataSource[i].dataIndex !== 'product')) {
            combineFormData.push({
              glassesReqDetailID: valueData && valueData.length > 0 ? Util.returnDataCccordingToAttributes(valueData, keys, 'fieldCode')?.glassesReqDetailID : undefined,
              reqFieldID: dataSource[i].productBrandOrderSetID,
              reqFieldValue: dataSource[i].typeCode === 'Select' ? (values && (keys + 'Desc') in values && values[keys + 'Desc'] ? values[keys + 'Desc'] : '') : values[keys],
              reqFieldValueID: dataSource[i].typeCode === 'Select' ? values[keys] : undefined,
            })
          }
        }
      }
    }
    return combineFormData;
  }

  // 发送
  handleSend = (statusCode, record, index) => {
    let modifyFlag = this.whetherTheContentIsModified(record, index);
    if (modifyFlag) {
      Modal.confirm({
        title: '确认发送提醒',
        content: (modifyFlag === 'left' ? '左眼' : (modifyFlag === 'left' ? '右眼' : '左/右眼')) + '参数内容改变，确认保存并发送/提交订单？',
        okText: '是',
        cancelText: '否',
        onOk: () => {
          if (statusCode === '01' || statusCode === '20' || statusCode === '25') {
            this.handleSave(() => this.modifyApplicationFormStatus(statusCode || '02', record, index), record, index);
          } else {
            this.handleParamsUpload(() => this.modifyApplicationFormStatus(statusCode || '02', record, index), record, index);
          }
        },
        onCancel: () => { },
      });
    } else {
      this.modifyApplicationFormStatus(statusCode || '02', record);
    }
  }

  // 退回订单
  handleReturnOrder = (statusCode, record) => {
    this.setState({ visible: false }, () => {
      this.props.handleReturnOrder && this.props.handleReturnOrder(record, statusCode);
    })
  }

  // 打印订单
  handlePrint = async (record) => {
    try {
      let { rowData } = this.state;
      let data = {
        params: [{
          glassesRequestIDArr: [record?.glassesRequestID],
          invoiceFlag: 'N', // Y:发货订单 N:配镜申请订单
          suppFlag: rowData?.suppFlag || 'N', // 订单管理Y, // 供应商标志
          componentName: rowData?.suppFlag || 'N',
        }]
      }
      let res = await React.$asyncPost(this, '17030077', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 订单发货
  handleDeliverGoods = (record) => {
    this.setState({ visible: false }, () => {
      this.props.handleDeliverGoods && this.props.handleDeliverGoods(record);
    })
  }

  // 处方流转保存
  handleExchangeSave = async (statusCode, record, index) => {
    try {
      let formValues = {};
      if (record && record.projectDesc) {
        formValues = await this['eyeFormRef_' + index].handleSave();
        if (formValues && formValues.error) {
          message.error('请完善右眼必填信息。');
          return;
        }
      }
      let eyeArr = this.handleCombineFormData(formValues, record?.formData || [], record?.rowData?.valueData || []);
      let data = {
        params: [{
          statusCode,
          admID: record?.admID || '', // 就诊ID
          glassesRequestID: record?.glassesRequestID || '',
          eyeArr, // 拆单号只存在一种眼别
        }]
      }
      let res = await React.$asyncPost(this, '17030085', data);
      message.success(res?.errorMessage || '操作成功');
      this.setState({ saveFlag: 'Y' }, () => {
        this.modifyVisible(false);
      })
    } catch (error) {
      console.log(error);
    }
  };

  // card选择
  handleCardClick = (item, activeDataIndex) => {
    this.setState({ activeKey: item && (activeDataIndex || 'glassesRequestID') in item && item[activeDataIndex || 'glassesRequestID'] ? item[activeDataIndex || 'glassesRequestID'] : (item?.key || ''), activeData: item }, () => {
      this.getStepsData(item?.statusArr || []);
    });
  };

  // 复制参数
  handleParamsCopy = () => {
    const { orderSetData, activeKey } = this.state;
    let index = 0;
    let formData = [];
    for (let i = 0; i < orderSetData.length; i++) {
      if (orderSetData[i]?.glassesRequestID === activeKey) {
        index = i;
        formData = orderSetData[i]?.formData || [];
        break;
      }
    }
    let values = this['eyeFormRef_' + index] && this['eyeFormRef_' + index].getFieldsValue();
    let copyText = '';
    for (let i = 0; i < formData.length; i++) {
      if (formData[i]?.typeCode !== 'Divider') {
        copyText += (formData[i]?.title || '') + '：' + (
          formData[i]?.typeCode === 'Select' ? (
            values && ((formData[i]?.dataIndex || '') + 'Desc') in values && values[(formData[i]?.dataIndex || '') + 'Desc'] ? values[(formData[i]?.dataIndex || '') + 'Desc'] : values[formData[i]?.dataIndex || '']
          ) : (
            values[formData[i]?.dataIndex || '']
          )
        ) + '\n';
      }
    }
    React.$copyToClipboard(copyText, '参数复制成功');
  };

  // 获取护理液表头数据
  getSolutionTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SolutionMatchingDetails',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      this.setState({ solutionColumns: res.result?.C || [], solutionTotalWidth: res.totalWidth });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取护理液及其他详情数据
  getSolutionMatchingDetails = async () => {
    try {
      const { rowData } = this.state;
      this.setState({ loading: true });
      let data = {
        params: [{
          suppFlag: rowData?.suppFlag || 'N', // 订单管理Y
          componentName: rowData?.suppFlag || 'N',
          orderDetailID: rowData?.orderDetailID || '',
          admID: rowData?.admID || '',
        }]
      }
      let res = await React.$asyncPost(this, '17030107', data);
      let copySolutionTableData = Util.addKeyValueToDataSource(res?.result?.detailArr || [], 'orderID');
      let solutionTableData = copySolutionTableData && copySolutionTableData.filter(item => item?.curRow === 'Y');
      this.setState({
        solutionTableData,
        copySolutionTableData,
        loading: false,
        patInfo: res.result?.admObj || {},
        selectedRowKeys: [],
      }, () => {
        // 默认选中点击的订单
        if (solutionTableData && solutionTableData.length > 0) {
          this.handleCardClick(solutionTableData[0], 'orderID');
        } else {
          this.setState({
            activeKey: '',
            activeData: {}
          });
        }
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 显示本销售单所有产品
  handleCheckboxChange = (e) => {
    this.setState({ loading: true });
    const { copySolutionTableData } = this.state;
    let checked = e.target.checked;
    let solutionTableData = copySolutionTableData;
    if (!checked) {
      solutionTableData = copySolutionTableData && copySolutionTableData.filter(item => item?.curRow === 'Y');
    }
    this.setState({
      checked,
      selectedRowKeys: []
    }, () => {
      setTimeout(() => { // 模拟查询效果
        this.setState({
          loading: false,
          solutionTableData
        })
      }, 300)
    })
  };

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.activeKey === '' || (this.state.activeKey && (this.state.activeKey !== record.orderID))) {
          this.handleCardClick(record, 'orderID');
        }
      }
    }
  };

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

  // 删除订单 - 护理液
  handleDelete = async () => {
    try {
      const { rowData, selectedRowKeys } = this.state;
      if (!(selectedRowKeys && selectedRowKeys.length > 0)) {
        message.warning('请选择需要删除的订单');
        return;
      }
      let data = {
        params: [{
          orderDetailIDArr: selectedRowKeys,
          suppFlag: rowData?.suppFlag || 'N', // 订单管理Y
          componentName: rowData?.suppFlag || 'N',
          admID: rowData?.admID || '',
        }]
      }
      let res = await React.$asyncPost(this, '17030108', data);
      message.success(res?.errorMessage || '删除成功');
      this.getSolutionMatchingDetails();
      this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    const { interfaceFlag } = this.props;
    const { visible, rowData, patInfo, stepsData, currentStep, orderSetData, activeKey, activeData, loading, checked, solutionLoading, solutionColumns, solutionTableData, solutionTotalWidth, selectedRowKeys } = this.state;
    const suppFlag = rowData?.suppFlag || ''; // 父组件标识
    return (
      <Modal
        title={suppFlag === 'exchange' ? '处方流转' : '查看详情'}
        width="1460px"
        footer={null}
        visible={visible}
        className="glasses-matching-modal matching-details-modal"
        onCancel={() => this.modifyVisible(false)}
      >
        <Spin tip="数据加载中..." spinning={loading}>
          <div className="mdm-left-header flex-align-items">
            <span>
              病人ID：
            </span>
            {patInfo?.patNo}
            <span>
              姓名：
            </span>
            {patInfo?.patName}
            <span>
              性别：
            </span>
            {patInfo?.patSexDesc}
            <span>
              年龄：
            </span>
            {patInfo?.patAge}
            <span>
              手机号：
            </span>
            {patInfo?.patMobile}
            {/* <span>
              预交金：
            </span>
            {patInfo?.deposit}元 */}
            <span>
              就诊科室：
            </span>
            <Tooltip title={patInfo?.admLocDesc || ''}>
              <i style={{ display: 'inline-block', fontStyle: 'inherit', maxWidth: '130px' }} className="ellipsis">
                {patInfo?.admLocDesc}
              </i>
            </Tooltip>
            <span>
              就诊医生：
            </span>
            {patInfo?.admDocDesc}
            <span>
              就诊时间：
            </span>
            {patInfo?.admDate}
            <span>
              验配师：
            </span>
            {patInfo?.createUserDesc}
            <span>
              机构：
            </span>
            {patInfo?.admHospDesc}
          </div>
          <div className="flex">
            <div style={{ width: '1150px' }}>
              <div
                style={{ paddingRight: '6px', position: 'relative', height: '100%' }}
              >
                {rowData?.glassesRequestID || rowData?.requestID ? ( // 配镜申请单
                  // <Card
                  //   size="small"
                  //   className="md-card md-left-card"
                  //   bodyStyle={{ width: '100%' }}
                  //   title={(
                  //     <div className="card-title-left-icon">
                  //       <div></div>
                  //       镜片参数
                  //     </div>
                  //   )}
                  //   extra={(
                  //     activeKey && (
                  //       <span className="span" onClick={this.handleParamsCopy}>
                  //         <Icon type="copy" />
                  //         复制参数
                  //       </span>
                  //     )
                  //   )}
                  // >
                  <div id={interfaceFlag + 'md-eye-body'} style={{ width: '100%', overflow: 'auto' }}>
                    <div style={{ width: (orderSetData?.length || 0) * 572 - 6 + 'px' }} className="md-eye-body">
                      <div style={{ height: '100%' }} className="flex-align-items">
                        {orderSetData && orderSetData.map((item, index) => {
                          let formData = item?.formData || [];
                          const curStatusCode = item?.curStatusCode || ''; // 当前状态
                          return (
                            <div key={index} className={['md-eye-items', activeKey === item.glassesRequestID ? 'md-eye-items-active' : ''].join(' ')} onClick={() => this.handleCardClick(item)}>
                              <div
                                style={{
                                  height: activeKey === item.glassesRequestID ? store.getState().tableHeight.y + 42 + 'px' : store.getState().tableHeight.y + 87 + 'px'
                                  // height: activeKey === item.glassesRequestID && this.operationInterfaceType.includes(suppFlag) ? store.getState().tableHeight.y + 42 + 'px' : store.getState().tableHeight.y + 87 + 'px'
                                }}
                                className="md-left-card-content"
                              >
                                <div className="md-card-left-tag">
                                  <div className="md-card-left-tag-body flex-between-center">
                                    <div style={{ fontSize: '14px', width: '70%' }}>
                                      <span className="span">{item?.part === 'L' ? '左眼(OS)' : '右眼(OD)'}-- </span>
                                      <span style={{ fontWeight: 'normal' }}>
                                        <span style={{ fontSize: '12px', color: '#999' }}>订单号：</span>
                                        {(item?.reqNo || '')}
                                      </span>
                                    </div>
                                    <div
                                      style={{ color: '#999', fontSize: '12px', fontWeight: 'normal', width: '30%' }}
                                      className="flex-wrap-end-align-items"
                                    >
                                      <Tag color={item?.reqStatusDesc !== '等待发送' ? '#87d068' : '#f50'} style={{ marginRight: 0, borderRadius: '22px' }}>{item?.reqStatusDesc || ''}</Tag>
                                    </div>
                                  </div>
                                </div>
                                <div className="md-left-card-content-form scroll-bar-style">
                                  <DynamicRenderingForm
                                    className={(curStatusCode === '01' || curStatusCode === '10') ? 'gmaf-dynamic-form' : ''}
                                    rowData={item?.rowData || {}}
                                    formData={formData}
                                    formItemCol={{ labelCol: 7, wrapperCol: 17, col: 24 }}
                                    onRef={ref => this['eyeFormRef_' + index] = ref}
                                  />
                                  <div className="no-matching-data" style={{ display: formData && formData.length > 0 ? 'none' : 'block' }}>
                                    暂无配镜信息
                                  </div>
                                </div>
                              </div>
                              {activeKey === item.glassesRequestID && (
                                <div style={{ padding: '0 12px', minHeight: '45px' }}>
                                  <div style={{ padding: '6px 0', borderTop: '1px solid #e8e8e8' }} className="flex-center">
                                    {suppFlag === 'Y' ? ( // 订单管理
                                      <>
                                        {/* {curStatusCode === '04' ? (
                      <Popconfirm title="确定撤销发货吗?" onConfirm={() => this.modifyApplicationFormStatus('09', item)} >
                        <Button
                          ghost
                          type="danger"
                          style={{ marginRight: ' 12px' }}
                        >
                          撤销发货
                        </Button>
                      </Popconfirm>
                    ) : ''} */}
                                        {curStatusCode === '03' ? (
                                          <>
                                            <Popconfirm title="确定撤销接收吗?" onConfirm={() => this.modifyApplicationFormStatus('09', item)} >
                                              <Button
                                                ghost
                                                type="danger"
                                                style={{ marginRight: ' 12px' }}
                                              >
                                                撤销接收
                                              </Button>
                                            </Popconfirm>
                                            <Button
                                              type="primary"
                                              onClick={() => this.handleDeliverGoods(item)}
                                            >
                                              订单发货
                                            </Button>
                                          </>
                                        ) : ''}
                                        {curStatusCode === '02' ? (
                                          <Button ghost type="primary" onClick={() => this.handlePrint(item)}>打印订单</Button>
                                        ) : ''}
                                        {curStatusCode === '02' || curStatusCode === '38' ? (
                                          <Popconfirm title="确定退回订单吗?" onConfirm={() => this.handleReturnOrder('52', item)}>
                                            <Button
                                              ghost
                                              type="danger"
                                              style={{ margin: '0 12px' }}
                                            >
                                              退回订单
                                            </Button>
                                          </Popconfirm>
                                        ) : ''}
                                        {curStatusCode === '38' ? (
                                          <Button
                                            type="primary"
                                            onClick={() => this.modifyApplicationFormStatus('03', item)}
                                          >
                                            接收订单
                                          </Button>
                                        ) : ''}
                                      </>
                                    ) : (suppFlag === 'K' ? ( // 订单审核
                                      <>
                                        {curStatusCode === '02' ? (
                                          <>
                                            <Popconfirm title="确定退回订单吗?" onConfirm={() => this.handleReturnOrder('20', item)} >
                                              <Button
                                                ghost
                                                type="danger"
                                                style={{ marginRight: ' 12px' }}
                                              >
                                                退回订单
                                              </Button>
                                            </Popconfirm>
                                            <Button
                                              type="primary"
                                              style={{ marginRight: ' 12px' }}
                                              onClick={() => this.modifyApplicationFormStatus('11', item)}
                                            >
                                              审核通过
                                            </Button>
                                          </>
                                        ) : (curStatusCode === '11' ? (
                                          <>
                                            <Popconfirm title="确定要撤销审核吗?" onConfirm={() => this.modifyApplicationFormStatus('09', item)} >
                                              <Button
                                                ghost
                                                type="danger"
                                                style={{ marginRight: ' 12px' }}
                                              >
                                                撤销审核
                                              </Button>
                                            </Popconfirm>
                                          </>
                                        ) : (curStatusCode === '25' ? (
                                          <>
                                            <Popconfirm title="确定退回订单吗?" onConfirm={() => this.handleReturnOrder('20', item)}>
                                              <Button
                                                ghost
                                                type="danger"
                                                style={{ marginRight: ' 12px' }}
                                              >
                                                退回订单
                                              </Button>
                                            </Popconfirm>
                                            <Button
                                              style={{ background: '#fa8c17' }}
                                              className="add-btn add-btn-nohover"
                                              onClick={() => this.modifyApplicationFormStatus('11', item)}
                                            >
                                              重新提交
                                            </Button>
                                          </>
                                        ) : ''))}
                                      </>
                                    ) : (suppFlag === 'N' ? ( // 配镜管理
                                      <>
                                        {curStatusCode === '02' ? (
                                          <Popconfirm title="确定撤回订单吗?" onConfirm={() => this.modifyApplicationFormStatus('09', item)} >
                                            <Button
                                              ghost
                                              type="danger"
                                              style={{ marginRight: ' 12px' }}
                                            >
                                              撤回订单
                                            </Button>
                                          </Popconfirm>
                                        ) : ''}
                                        <Button
                                          type="primary"
                                          style={{ marginRight: ' 12px' }}
                                          disabled={!(curStatusCode === '01' || curStatusCode === '10' || curStatusCode === '20' || curStatusCode === '25' || activeData?.updateFlag === 'Y')}
                                          onClick={curStatusCode === '01' || curStatusCode === '20' || curStatusCode === '25' ? () => this.handleSave('', item, index) : () => this.handleParamsUpload('', item, index)}
                                        >
                                          {curStatusCode === '01' || curStatusCode === '20' || curStatusCode === '25' ? '保存' : '更新'}
                                        </Button>
                                        {curStatusCode === '01' ? (
                                          <Button
                                            className="add-btn add-btn-nohover"
                                            style={{ background: '#27b148', borderColor: '#27b148' }}
                                            onClick={() => this.handleSend('02', item, index)}
                                          >
                                            发送订单
                                          </Button>
                                        ) : ''}
                                        {curStatusCode === '10' || curStatusCode === '02' || curStatusCode === '20' ? (
                                          <Button
                                            disabled={curStatusCode === '02'}
                                            style={{ background: curStatusCode === '10' ? '#fa8c17' : '' }}
                                            className={curStatusCode === '10' ? 'add-btn add-btn-nohover' : ''}
                                            onClick={() => this.handleSend(curStatusCode === '10' ? '38' : '02', item, index)}
                                          >
                                            重新发送
                                          </Button>
                                        ) : ''}
                                        {curStatusCode === '25' ? ( // 医院采购退回配镜申请单可以重新提交
                                          <Button
                                            style={{ background: '#fa8c17' }}
                                            className="add-btn add-btn-nohover"
                                            onClick={() => this.handleSend(rowData?.hisRtnStatusCode || '11', item, index)}
                                          >
                                            重新提交
                                          </Button>
                                        ) : ''}
                                      </>
                                    ) : (suppFlag === 'ProcurementPlan' ? ( // 采购计划
                                      <>
                                        {rowData.statusCode === '0' || rowData.statusCode === '40' ? ( // 从订单选择或状态为40才支持退回订单
                                          <Popconfirm title="确定退回订单吗?" onConfirm={() => this.handleReturnOrder('25', item)} >
                                            <Button
                                              ghost
                                              type="danger"
                                            >
                                              退回订单
                                            </Button>
                                          </Popconfirm>
                                        ) : ''}
                                      </>
                                    ) : (suppFlag === 'ReturnOrder' ? ( // 退镜
                                      <>
                                        {/* <Button
                                            style={{ marginRight: ' 12px' }}
                                            onClick={() => this.modifyVisible(false, item)}
                                          >
                                            取消
                                          </Button> */}
                                        <Button
                                          type="primary"
                                          onClick={() => this.handleSave('confirmTheMirrorRetraction', item, index)}
                                        >
                                          确定
                                        </Button>
                                      </>
                                    ) : (suppFlag === 'G' ? ( // 集团确认发货
                                      <>
                                        {/* <Button
                                            style={{ marginRight: ' 12px' }}
                                            onClick={() => this.modifyVisible(false, item)}
                                          >
                                            取消
                                          </Button> */}
                                        {curStatusCode === '52' ? ( // 52为供应商退回
                                          <Popconfirm title="确定退回订单吗?" onConfirm={() => this.handleReturnOrder('10', item)}>
                                            <Button
                                              ghost
                                              type="danger"
                                              style={{ margin: '0 12px' }}
                                            >
                                              退回订单
                                            </Button>
                                          </Popconfirm>
                                        ) : ''}
                                        {curStatusCode === '04' ? (
                                          <Button
                                            type="primary"
                                            onClick={() => this.modifyApplicationFormStatus('39', item)}
                                          >
                                            确认发货
                                          </Button>
                                        ) : ''}
                                      </>
                                    ) : (suppFlag === 'exchange' ? ( // 处方交换
                                      <>
                                        <Button
                                          type="primary"
                                          style={{ marginRight: ' 12px' }}
                                          onClick={() => this.handleExchangeSave('01', item, index)}
                                        >
                                          保存
                                        </Button>
                                        {/* <Button
                      className="add-btn add-btn-nohover"
                      style={{ background: '#27b148', borderColor: '#27b148' }}
                      onClick={() => this.handleExchangeSave('02')}
                    >
                      发送
                    </Button> */}
                                      </>
                                    ) : ''))))))}
                                    <Button
                                      style={{ marginLeft: ' 12px' }}
                                      onClick={this.handleParamsCopy}
                                    >
                                      复制参数
                                    </Button>
                                  </div>
                                </div>
                              )}
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  </div>
                  // </Card>
                ) : (
                  <Card
                    size="small"
                    className="md-card md-left-card table-body-height"
                    bodyStyle={{ width: '100%' }}
                    title={(
                      <div className="card-title-left-icon">
                        <div></div>
                        详情
                      </div>
                    )}
                    extra={(
                      <Checkbox checked={checked} onChange={this.handleCheckboxChange}>显示本销售单所有产品</Checkbox>
                    )}
                  >
                    <PublicTablePagination
                      param={{
                        loading: solutionLoading,
                        columns: solutionColumns, // 表头配置
                        data: solutionTableData, // 表格数据
                        x: solutionTotalWidth, // 表格的宽度
                        y: store.getState().tableHeight.y - 45,
                        height: store.getState().tableHeight.y + 'px',
                        componentName: 'SolutionMatchingDetails',
                      }}
                      rowSelectionPublic={{
                        selectedRowKeys,
                        onChange: (selectedRowKeys, selectedRows) => {
                          this.setState({
                            selectedRowKeys,
                          })
                        },
                        getCheckboxProps: record => ({
                          disabled: record.chooseFlag === 'N',
                        }),
                      }}
                      getColumns={this.getSolutionTableColumns}
                      onClickRowPublic={this.onClickRowPublic}
                      setRowClassNamePublic={this.setRowClassNamePublic}
                    />
                    <div style={{ textAlign: 'center', marginTop: '8px', position: 'relative' }}>
                      {patInfo?.tip && <span style={{ position: 'absolute', left: '0px', top: '8px', color: '#999', fontSize: '12px', fontWeight: 'normal' }}>{patInfo?.tip || ''}</span>}
                      <Popconfirm title="删除不可恢复，你确定要删除吗?" disabled={!(selectedRowKeys && selectedRowKeys.length > 0)} onConfirm={this.handleDelete}>
                        <Button ghost type="danger" disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}>删除</Button>
                      </Popconfirm>
                    </div>
                  </Card>
                )}
              </div>
              <div className="common-card-right-split-line" style={{ width: 12, background: '#fff' }}></div>
            </div>
            <div style={{ width: '310px' }}>
              <Card
                size="small"
                className="md-card md-right-card"
                bordered={false}
                title={(
                  <div className="card-title-left-icon">
                    <div></div>
                    生命周期
                  </div>
                )}
                extra={(
                  activeKey && (
                    <span style={{ fontSize: '12px', fontWeight: 'normal', color: '#999', }}>
                      订单号: {activeData?.reqNo || activeData?.extCode || ''}{!(rowData?.glassesRequestID || rowData?.requestID) ? '(序号' + (activeData?.seqNo || 1) + ')' : ''}
                    </span>
                  )
                )}
              >
                <div style={{ height: store.getState().tableHeight.y + (orderSetData?.length > 2 ? 46 : 29) + 'px' }} id={interfaceFlag + 'md-steps'} className="md-steps scroll-bar-style">
                  <Steps progressDot direction="vertical" current={currentStep}>
                    {stepsData && stepsData.map((item, index) => {
                      return (
                        <Step
                          key={index}
                          title={item.statusTitle}
                          className={(this.errorStatusCode.indexOf(item.statusCode) > -1) || item?.statusTitle.indexOf('取消订单') > -1 ? 'md-steps-item-error' : ''}
                          subTitle={(
                            ('deliverGoods' in item && item.deliverGoods && item.deliverGoods.length > 0) || item.floatDesc || item.remark ? (
                              <Tooltip
                                title={('deliverGoods' in item && item.deliverGoods && item.deliverGoods.length > 0) ? this.getDeliverGoods(item.deliverGoods) : (item.floatDesc ? this.getFloatDesc(item.floatDesc) : (item.remark ? this.getRemarkDesc(item.remark, item) : ''))}
                                trigger="click"
                                placement="right"
                              >
                                <span className="span">详情</span>
                              </Tooltip>
                            ) : ''
                          )}
                          description={
                            <>
                              <div>
                                {item && item.statusDesc ? item.statusDesc : item.updateDateTime}
                              </div>
                              {item.updateUserDesc ? (
                                <div>
                                  {item.updateUserDesc}
                                </div>
                              ) : ''}
                              {/* {item.remark ? <div style={{ color: 'red' }}>原因：{item.remark}</div> : ''} */}
                            </>
                          }
                        />
                      )
                    })}
                  </Steps>
                </div>
              </Card>
            </div>
          </div>
        </Spin>
      </Modal>
    )
  }
};

export default MatchingDetails;