/* eslint-disable array-callback-return,no-undef */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, Tabs, Row, Col } from 'antd-v4';
import styles from '@/index.less';
import * as commonUtils from '@/utils/utils';
import Toolbar from '@/components/Common/ToolBar/ToolBarNew';
import * as commonFunc from '@/components/Common/commonFunc';
import CommonBase from '@/components/Common/CommonBase';
import CommonElementEvent from '@/components/Common/CommonElementEvent';
import CommonView from '@/components/Common/CommonView';
import TabCounter from '@/components/Common/CommonCalculator';
import TabParam from '@/components/Common/commonParam';
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
import ShowTypeNew from '@/components/Common/CommonComponent';
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */

const { Header, Content } = Layout;
const { TabPane } = Tabs;

class SisformulaInfoComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
    this.form = {}; /*   表单对象   */
    // 删除sessionStorage里key值已sModelsId开头的值
    const { sModelsId } = props;
    for (let i = 0; i < sessionStorage.length; i++) {
      const key = sessionStorage.key(i);
      if (key.startsWith(`${sModelsId}_`)) {
        sessionStorage.removeItem(key);
      }
    }
  }

  // onDoubleClick = (record) => { /* 双击行 将参数名 @参数名放到公式框里 */
  //   if (this.props.enabled && commonUtils.isNotEmptyObject(record)) {
  //     const { sParam } = record;
  //     if (commonUtils.isNotEmptyObject(sParam)) {
  //       const { masterData: masterDataOld } = this.props;
  //       const value = `@${sParam}`;
  //       const masterData = { ...masterDataOld };
  //       const sFormulaMemo = (Object.keys(masterData).length > 0 && masterData.sFormulaMemo !== undefined) ? masterData.sFormulaMemo : '';
  //       const changeFormula = `${sFormulaMemo}${value}`;
  //       masterData.sFormula = changeFormula;
  //       masterData.sFormulaMemo = changeFormula;
  //       masterData.handleType = masterData.handleType === 'add' ? 'add' : 'update';
  //       this.props.onSaveState({ masterData });
  //     }
  //   }
  // };

  handleFieldDoubleClick = (record, sValue, showConfig, tbName) => {
    if (!this.props.bUserModel) {
      return;
    }
    const lastChar = tbName.charAt(tbName.length - 1);
    const firstChar = this.props.onGetFirstChar(lastChar);
    const { [`${tbName}Data`]: tableData, enabled } = this.props;
    if (enabled && commonUtils.isNotEmptyObject(showConfig) && commonUtils.isNotEmptyArr(tableData)) {
      if (commonUtils.isNotEmptyObject(record)) {
        const { masterData: masterDataOld } = this.props;
        let sParam = '';
        /* 找到该字段所在行 */
        const iIndex = tableData.findIndex(item => item.sId === record.sId);
        if(showConfig.sName=== 'sName') {
          if (iIndex > -1) {
            sParam = record[showConfig.sName];
          } else {
            sParam = showConfig.sName;
          }
        }else {
          if (iIndex > -1) {
            sParam = `${firstChar}${iIndex}_${showConfig.sName}`;
          } else {
            sParam = showConfig.sName;
          }
        }
        const value = `@${sParam}`;
        const masterData = { ...masterDataOld };
        const sFormulaMemo = (Object.keys(masterData).length > 0 && masterData.sFormulaMemo !== undefined) ? masterData.sFormulaMemo : '';
        const changeFormula = `${sFormulaMemo}${value}`;
        masterData.sFormula = changeFormula;
        masterData.sFormulaMemo = changeFormula;
        masterData.handleType = masterData.handleType === 'add' ? 'add' : 'update';
        this.props.onSaveState({ masterData });
      }
    }
  };

  render() {
    const { pageLoading } = this.props;
    return (
      <div>
        <Spin spinning={pageLoading}>
          <div>
            <SisformulaComponent
              {...this.props}
              {...this.state}
              // onDoubleClick={this.onDoubleClick}
              onFieldDoubleClick={this.handleFieldDoubleClick}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const SisformulaComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, sModelsId, app, customizeParamConfig,
  } = props;
  onReturnForm(form);
  const { masterConfig } = props;
  let { masterData } = props;
  masterData = masterData === undefined ? {} : masterData;
  const masterShowConfig = commonUtils.isNotEmptyObject(masterConfig) ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'sFormulaMemo') : {};
  const masterShowConfigMemo = commonUtils.isNotEmptyObject(masterShowConfig) ? masterShowConfig[0] : {};
  const tabFormulaDetails = commonFunc.showMessage(app.commonConst, 'tabFormulaDetails');/* 公式详情 */
  // const tabCalculatorArea = commonFunc.showMessage(app.commonConst, 'tabCalculatorArea');/* 计算器区域 */
  const tabCalculationParameter = commonFunc.showMessage(app.commonConst, 'tabCalculationParameter');/* 计算参数 */
  const tabSystemFunction = commonFunc.showMessage(app.commonConst, 'tabSystemFunction');/* 系统函数 */
  const tabBusinessFunction = commonFunc.showMessage(app.commonConst, 'tabBusinessFunction');/* 业务函数 */
  const tabBusinessParameters = commonFunc.showMessage(app.commonConst, 'tabBusinessParameters');/* 自定义参数 */

  const showTypeProps = {
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    isDropDownLoadFinish: true,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: masterShowConfigMemo,
    formItemLayout: true,
    textArea: true,
    enabled: props.enabled,
    dataValue: masterData.sFormulaMemo,
    bTable: true,
    onFilterDropDownData: props.onFilterDropDownData,
    onSaveState: props.onSaveState,
  };

  /* 开发者模式 */
  const customizeParamPropsType = {
    ...commonBusiness.getTableTypes('customizeParam', props),
    tableProps: {
      AutoTableHeight: 255,
    },
    // bNaturalWidth: true, /* 原始宽度 不进行最后一列计算 */
    rowSelection: null,
  };

  /* 自定义参数 */
  const selfParamPropsType = {
    ...commonBusiness.getTableTypes('selfParam', props),
    tableProps: {
      AutoTableHeight: 150,
    },
    // bNaturalWidth: true, /* 原始宽度 不进行最后一列计算 */
    rowSelection: null,
  };

  const customizeParamPropsTypeArr = [];
  if (commonUtils.isNotEmptyArr(props.customizeParamName)) {
    props.customizeParamName.forEach((paramName) => {
      customizeParamPropsTypeArr.push({
        ...commonBusiness.getTableTypes(paramName, props),
        tableProps: {
          AutoTableHeight: 255,
        },
        // bNaturalWidth: true, /* 原始宽度 不进行最后一列计算 */
        rowSelection: null,
        bHideCopyAll: true,
      });
    });
  }

  /* 用户模式 */
  const customizeParamUserPropsType = {
    ...commonBusiness.getTableTypes('customizeParam', props),
    data: props.customizeParamData,
    config: props.userParamConfig,
    headerColumn: props.userParamColumn,
    tableProps: {
      AutoTableHeight: 469,
    },
    // bNaturalWidth: true, /* 原始宽度 不进行最后一列计算 */
    rowSelection: null,
  };

  const customizeParamUserPropsTypeArr = [];
  if (commonUtils.isNotEmptyArr(props.userParamName)) {
    props.userParamName.forEach((paramName) => {
      const customizeParamName = paramName.replace('userParam', 'customizeParam');
      customizeParamUserPropsTypeArr.push({
        ...commonBusiness.getTableTypes(customizeParamName, props),
        data: props[`${customizeParamName}Data`],
        config: props[`${paramName}Config`],
        headerColumn: props[`${paramName}Column`],
        tableProps: {
          AutoTableHeight: 469,
        },
        // bNaturalWidth: true, /* 原始宽度 不进行最后一列计算 */
        rowSelection: null,
        bHideCopyAll: true,
      });
    });
  }

  const editableClass = commonUtils.isNotEmptyObject(props) && props.enabled ? 'xly-bill-list editUser' : 'xly-bill-list viewUser';

  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar {...props} />
        </Header>
        <Layout className={styles.clayout}>
          <Content className={`bill-search-group ${styles.content}`}>
            <CommonView {...props} />
          </Content>
          {/* <div> */}
          {/*  <Avatar src={props.imgSrc} /> */}
          {/* </div> */}
          {
            commonUtils.isNotEmptyObject(masterData) && masterData.bUserModel ?
              <div id="calTab" className="searchMainForm" style={{ height: '560px' }}>
                <Row>
                  <Col span={18}>
                    <Row>
                      <Col span={24} className={styles.jsqSider} style={{ height: '200px' }}>
                        <Tabs style={{ marginRight: '10px' }}>
                          <TabPane tab={tabFormulaDetails} key={2} >
                            { commonUtils.isNotEmptyObject(masterShowConfig) ? <div className="formula" style={{ marginTop: '15px' }}> <ShowTypeNew {...showTypeProps} /></div> : ''}
                          </TabPane>
                        </Tabs>

                        {/* <Tabs style={{ marginRight: '10px' }}> */}
                        {/*  <TabPane tab={tabCalculatorArea} key={2} > */}
                        {/*    <div style={{ height: '1px', backgroundColor: '#d9d9d9', width: '100%' }} /> */}
                        {/*    <TabCounter {...props} /> */}
                        {/*  </TabPane> */}
                        {/* </Tabs> */}
                      </Col>
                      <Col span={24} className={styles.jsqSider}>
                        <Tabs className={styles.slaveTabs} style={{ marginRight: '10px' }}>
                          {
                            commonUtils.isNotEmptyArr(customizeParamPropsTypeArr) ?
                              customizeParamPropsTypeArr.map((paramProps, index) => {
                                const key = `${props.tableKey || 2}_${index}`;
                                return (
                                  <TabPane tab={`${props[`customizePanelName${index || ''}`]}`} key={key} className="xly-bill-list" >
                                    <div style={{ marginTop: '15px' }}>
                                      { commonUtils.isNotEmptyObject(paramProps) ? <StaticEditTable {...paramProps} setOpterationColumn="Y" footer="hidden" /> : ''}
                                    </div>
                                  </TabPane>
                                );
                              }) :
                              <TabPane tab={props.customizePanelName || '变量设置'} key={props.tableKey || 2} className="xly-bill-list" >
                                <div style={{ marginTop: '15px' }}>
                                  { commonUtils.isNotEmptyObject(customizeParamConfig) ? <StaticEditTable {...customizeParamPropsType} setOpterationColumn="Y" footer="hidden" /> : ''}
                                </div>
                              </TabPane>
                          }
                        </Tabs>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={6} className={styles.jsqSider} style={{ height: '215px' }}>
                    <Tabs className={styles.slaveTabs} >
                      <TabPane tab={tabCalculationParameter} key={3} >
                        <TabParam {...commonBusiness.getShowTableSelectTypes('param', props, 'sName')} />
                      </TabPane>
                      <TabPane tab={tabSystemFunction} key={4}>
                        <TabParam {...commonBusiness.getShowTableSelectTypes('systemFunction', props, 'value')} />
                      </TabPane>
                      <TabPane tab={tabBusinessFunction} key={5}>
                        <TabParam {...commonBusiness.getShowTableSelectTypes('bussinessFunction', props, 'value')} />
                      </TabPane>
                      <TabPane tab={tabBusinessParameters} key={6}>
                        { commonUtils.isNotEmptyObject(selfParamPropsType) ? <StaticEditTable {...selfParamPropsType} setOpterationColumn="Y" footer="hidden" /> : ''}
                      </TabPane>
                    </Tabs>
                    {/* <div style={{ height: '1px', backgroundColor: '#d9d9d9', width: '100%' }} /> */}
                    <TabCounter {...props} />
                  </Col>
                </Row>
              </div> :
              <div id="calTab" className="searchMainForm" style={{ height: '560px' }}>
                <Row className="userParam">
                  <Col span={24} className={styles.jsqSider} style={{ height: '552px' }}>
                    <Tabs className={styles.slaveTabs} style={{ marginRight: '10px' }}>
                      {
                        commonUtils.isNotEmptyArr(customizeParamUserPropsTypeArr) ?
                          customizeParamUserPropsTypeArr.map((paramProps, index) => {
                            const key = `${props.tableKey || 2}_${index}`;
                            return (
                              <TabPane tab={`${props[`customizePanelName${index || ''}`]}`} key={key} className={editableClass} >
                                <div style={{ marginTop: '15px' }} className="customizeParam">
                                  { commonUtils.isNotEmptyObject(paramProps) ? <StaticEditTable {...paramProps} setOpterationColumn="Y" footer="hidden" /> : ''}
                                </div>
                              </TabPane>
                            );
                          }) :
                          <TabPane tab={props.customizePanelName || '变量设置'} key={props.tableKey || 2} className={editableClass} >
                            <div style={{ marginTop: '15px' }} className="customizeParam">
                              { commonUtils.isNotEmptyObject(customizeParamConfig) ? <StaticEditTable {...customizeParamUserPropsType} setOpterationColumn="Y" footer="hidden" /> : ''}
                            </div>
                          </TabPane>
                      }
                    </Tabs>
                  </Col>
                </Row>
              </div>
          }

        </Layout>
      </Layout>
    </Form>
  );
});
export default CommonBase(CommonElementEvent(SisformulaInfoComponent));

