/*
 * Create:      柿子
 * CreateDate:  2023/08/31
 * Describe：   订单参数查询 - 供外部查看订单参数
 * */
import React, { Component } from 'react';
import { Card, Button, Tooltip, Spin } from 'antd';
import { Util } from 'tools/index';
import { handleExcel } from 'tools/handleExcel';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import './style/index.less';

class OrderParameterQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      spinLoading: true,
      categoryData: {},
      baseInfoFormData: [],
      orderInfoFormData: [],
      applicationFormData: [],
      exportLoading: false,
      rowData: {},
      applicationRowData: {},
    }
  }

  componentDidMount() {
    let newCategory;
    // http://127.0.0.1:4003/#/17050013?admID=943480&reqNo=H23O202308280006
    let path = window.location && window.location.href ? window.location.href.split('#')[1] : '';
    if (path && path.indexOf('?') > -1) { // 按照路径维护的数据取值
      newCategory = path.split('?')[1];
      React.$setSessionData('OrderParameterQuery', newCategory, false);
    } else { // 头菜单刷新界面时获取类别
      newCategory = React.$getSessionData('OrderParameterQuery', false);
    }
    let categoryData = Util.getObjByUrlStr(newCategory, '=');
    console.log('OrderParameterQuery', categoryData);
    this.setState({ categoryData }, () => {
      this.getBaseInfoFormData();
      this.getOrderInfoFormData();
      this.getApplicationFormData();
    });
  }

  // 获取表头数据
  getBaseInfoFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OrderParameterQueryBaseInfo',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let baseInfoFormData = res.result?.formData || [];
      this.setState({
        baseInfoFormData
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getOrderInfoFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OrderParameterQueryOrderInfo',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let orderInfoFormData = res.result?.formData || [];
      this.setState({
        orderInfoFormData
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 获取配镜申请单配置
  getApplicationFormData = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          ...categoryData
        }]
      }
      let res = await React.$asyncPost(this, '17030094', data);
      let orderSet = res.result?.orderSet || [];
      let eyeValue = res.result?.value || [];
      let applicationRowData = {};
      // 左眼
      if (eyeValue && Array.isArray(eyeValue)) {
        this.applicationRef && this.applicationRef.resetFields();
        for (var i = 0; i < eyeValue.length; i++) {
          let typeCode = orderSet && orderSet.length > 0 ? Util.returnDataCccordingToAttributes(orderSet, eyeValue[i].fieldCode, 'code')?.componentTypeCode : '';
          applicationRowData[eyeValue[i].fieldCode] = typeCode === 'Select' ? eyeValue[i].reqFieldValueID : eyeValue[i].reqFieldValue;
        }
      }
      this.getEyeFormData('applicationFormData', orderSet);
      this.setState({ rowData: res.result?.baseObj || {}, applicationRowData, spinLoading: false })
    } catch (error) {
      console.log(error);
      this.setState({ spinLoading: false });
    }
  }

  // 获取左眼表单数据
  getEyeFormData = (dataIndex, formData) => {
    formData = formData && formData.map((item, index) => {
      return {
        ...item,
        isEnterJump: 'Y', // 回车下一个输入域
        dataIndex: item.code,
        required: item.required,
        defaultValue: undefined,
        typeCode: item.componentTypeCode,
        col: item?.componentTypeCode === 'Divider' || item?.componentTypeCode === 'UploadFile' || item?.componentTypeCode === 'Upload' || item.componentTypeCode === 'UploadImg' ? 24 : 6,
        labelCol: item?.componentTypeCode === 'Divider' || item?.componentTypeCode === 'UploadFile' || item?.componentTypeCode === 'Upload' || item.componentTypeCode === 'UploadImg' ? 2 : 8,
        wrapperCol: item?.componentTypeCode === 'Divider' || item?.componentTypeCode === 'UploadFile' || item?.componentTypeCode === 'Upload' || item.componentTypeCode === 'UploadImg' ? 22 : 16,
        detailItem: item?.selectData || [],
        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: 'Y',
        onSelect: item.componentTypeCode === 'Select' ? () => this.handleSelectChange(dataIndex, item) : '',
      }
    });
    if (formData && formData.length > 0) {
      formData = [...formData];
    }
    this.state[dataIndex] = formData;
    this.setState({});
  }

  // 下拉框change事件
  handleSelectChange = (dataIndex, item) => {
    console.log('dataIndex, item', dataIndex, item)
  }

  // 导出 
  handleExport = async () => {
    try {
      this.setState({ exportLoading: true });
      const { categoryData } = this.state;
      let data = {
        params: [{
          ...categoryData
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.exportCode, data);
      if (categoryData?.reactExportFlag === 'Y') { // 前端导出标志
        this.handleReactExportData(res);
      } else {
        handleExcel.downloadExcel(res.result);
      }
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 前端导出ERP - 数据量多的情况每次调用固定的条数，分页请求，最后拿到全部数据再导出
  handleReactExportData = async (res) => {
    let tableData = res.result?.rows || [];
    if (tableData && tableData.length > 0) {
      handleExcel.exportExcel(res.result?.columns || [], res.result?.rows || [], res.result?.fileName || '订单参数查询', '', res.result?.type || 'xlsx', res.result?.sheetName || 'mySheet');
    } else {
      message.error('前端导出异常，请检查返回数据！')
    }
  }

  render() {
    const { spinLoading, categoryData, exportLoading, rowData, baseInfoFormData, orderInfoFormData, applicationFormData, applicationRowData } = this.state;
    return (
      <Spin
        tip="正在初始化表单数据..."
        spinning={spinLoading}
        wrapperClassName="order-parameter-query-spin"
      >
        <div className="order-parameter-query">
          <div className="order-parameter-query-content scroll-bar-style" style={{ width: '100%', height: categoryData?.exportCode ? 'calc(100% - 56px)' : '100%', overflow: 'auto' }}>
            <Card
              type="inner"
              size="small"
              bordered={false}
              title={<div className="card-title-left-icon"><div></div>基本信息</div>}
            >
              <DynamicRenderingForm
                rowData={rowData || {}}
                formData={baseInfoFormData}
                onRef={ref => this.baseInfoRef = ref}
              />
            </Card>
            <Card
              type="inner"
              size="small"
              bordered={false}
              title={<div className="card-title-left-icon"><div></div>订单信息</div>}
            >
              <DynamicRenderingForm
                rowData={rowData || {}}
                formData={orderInfoFormData}
                onRef={ref => this.orderInfoRef = ref}
              />
            </Card>
            <Card
              type="inner"
              size="small"
              bordered={false}
              title={<div className="card-title-left-icon"><div></div>参数信息{rowData?.eyePartCode ? '(' + rowData.eyePartCode + ')' : ''}</div>}
            >
              <DynamicRenderingForm
                rowData={applicationRowData || {}}
                formData={applicationFormData}
                onRef={ref => this.applicationRef = ref}
                formItemCol={{ labelCol: categoryData?.labelCol || 9, wrapperCol: categoryData?.wrapperCol || 14 }}
              />
            </Card>
          </div>
          {categoryData?.exportCode ? (
            <div className="order-parameter-query-footer flex-center">
              <Button style={{ marginRight: '12px' }} onClick={this.getApplicationFormData}>重新查询</Button>
              <Button ghost type="primary" loading={exportLoading} onClick={this.handleExport}>导出</Button>
            </div>
          ) : ''}
        </div>
      </Spin>
    )
  }
};

export default OrderParameterQuery;