import React, { Component, useMemo, useState } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, Slider, Button } from 'antd-v4';
import { MessageOutlined, MinusOutlined } from '@ant-design/icons';
import CommonListEvent from '@/components/Common/CommonListEvent';/* 继承销售模块业务功能 */
import * as commonFunc from '@/components/Common/commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from '@/components/Common/ToolBar/ToolBarNew';
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */
import StaticEditTableNew from '@/components/Common/CommonTable';/* 可编辑表格 */
import styles from '@/index.less';
import CommonBase from '@/components/Common/CommonBase';/* 获取配置及数据 */
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
import SearchComponent from '@/components/Common/SearchComponent';/* 搜索组件 */
import commonConfig from '@/utils/config';
import * as commonUtils from '@/utils/utils';
import StaticEditTree from '@/components/Common/Tree/StaticTree';
import Eject from '@/assets/eject.svg';/* 弹出图标 */
import Close from '@/assets/close.svg';/* 关闭图标 */
import AntdDraggableModal from '@/components/Common/AntdDraggableModal';
import CommonListSelect from '@/components/Common/CommonListSelect';/* 选择界面 */
import WorkOrderSystemAddModal from '@/components/Common/WorkOrderSystem/WorkOrderSystemAdd';
import WorkOrderSystemDetailModal from '@/components/Common/WorkOrderSystem/WorkOrderSystemDetail';

const { Header, Content } = Layout;
let NoTotalData = '';
class CommonList extends Component {
  handleEject = () => {
    const { currentPane, panes } = this.props.app;
    if (commonUtils.isNotEmptyArr(panes) && commonUtils.isNotEmptyObject(currentPane)) {
      // const index = panes.indexOf(currentPane);
      const index = panes.findIndex(item => item.formId === currentPane.formId && item.key === currentPane.key && item.notCurrentPane === currentPane.notCurrentPane && item.route === currentPane.route && item.title === currentPane.title && item.sModelsType === currentPane.sModelsType && item.sProcName === currentPane.sProcName);
      /* 当前页签 */
      let currentTab = document.getElementById('navTabWrap').children[index];
      if (commonUtils.isEmpty(currentTab)) {
        const oChildren = document.getElementById('navTabWrap').getElementsByClassName('ant-tabs-content')[0].children;
        for (const child of oChildren) {
          if (child.nodeName === 'DIV' && index !== undefined && child.getAttribute('id') === `navTabWrap-panel-${panes[index].key}`) {
            currentTab = child;
          }
        }
      }
      if (!commonUtils.isEmpty(currentTab)) {
        const filterTreeArr = currentTab.getElementsByClassName('xly-filter-tree');/* 获取当前页签下的树组件 */
        if (commonUtils.isNotEmptyArr(filterTreeArr)) {
          const filterTree = filterTreeArr[0];
          if (filterTree.style.display === 'block') {
            filterTree.style.display = 'none';
          } else {
            filterTree.style.display = 'block';
          }
        }
      }
    }
  };
  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e) => {
    this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };

  handleCancelModal = (modelVisible) => {
    this.props.onSaveState({
      [modelVisible]: false,
    });
  }

  handleSelectModal = (modelVisible) => {
    this.props.onSaveState({
      [modelVisible]: false,
    });
  }

  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              onEject={this.handleEject}
              onSelectTree={this.handleTreeSelect}
              onSelectModal={this.handleSelectModal}
              onCancelModal={this.handleCancelModal}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonListComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData, masterConfig } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form, masterConfig);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, slavePagination, slaveConfig, slaveColumn, iHeight, logVisible, slaveFilterCondition,
    flowHistroyId, flowHistroyVisible, app,
  } = props;
  const { userinfo, token } = app;
  // isSmall将分页变小，以及去掉跳转页面和总条数记录
  /*   回带表单   */
  if (commonUtils.isNotEmptyObject(slavePagination)) {
    // if (isSmall) {
    //   slavePagination.showTotal = null;
    // }
  }
  onReturnForm(form);

  const masterSum = commonUtils.isNotEmptyObject(slaveConfig) ? slaveConfig.gdsconfigformslave.filter(item => item.bSum && item.sName !== '') : [];
  const masterTitleGroup = commonUtils.isNotEmptyObject(slaveColumn) ? slaveColumn.filter(item => commonUtils.isNotEmptyObject(item.title) && item.title.indexOf('-') > -1) : [];
  const hasColumnGroup = masterTitleGroup.length;
  if (masterSum.length > 0) {
    NoTotalData = hasColumnGroup > 0 ? 'TitleGroup' : 'NoTitleGroup';
  } else {
    NoTotalData = hasColumnGroup > 0 ? 'NoTotalData TitleGroup' : 'NoTotalData NoTitleGroup';
  }
  // const mProps = { ...commonBusiness.createMemoProps('master', props)};

  const name = 'filterTree';
  const treeProps = {
    ...commonBusiness.getTreeTypes('tree', props),
    isSearch: false,
    checkable: false,
    disabled: false,
    checkedAll: false,
    unChecked: false,
    [`${name}Column`]: props[`${name}Column`],
    [`${name}Config`]: props[`${name}Config`],
    [`${name}Data`]: props[`${name}Data`],
    getFloatNum: props.getFloatNum,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getDateFormat: props.getDateFormat,
    onDoubleClick: props.onDoubleClick,
    onSelect: props.onSelectTree,
    expandedKeys: props.expandedKeys,
  };
  const logProps = {
    app: {
      ...props.app,
      currentPane: {
        ...props.app.currentPane,
        formRoute: '/indexPage/commonList',
        route: '/indexPage/commonList',
        name: 'logView',
        config: props.logConfig,
        select: props.onSelectModal.bind(this, 'logVisible'),
        selectCancel: props.onCancelModal.bind(this, 'logVisible'),
        sModelsType: 'modal/logView',
      },
    },
    token: props.app.token,
    slaveColumn: props.logColumn, /*   表头   */
    slaveConfig: props.logConfig,
    slaveData: props.logData,
    dispatch: props.dispatch,
    content: props.content,
    id: new Date().getTime().toString(),
    pageLoading: false,
  };

  const refreshSlaveTable = () => {
    props.handleGetDataSet({
      name: 'slave',
      configData: props.slaveConfig,
      condition: {
        pageNum: 1,
        pageSize: slavePagination.pageSize,
        bFilter: slaveFilterCondition,
      },
      flag: true,
      clearSelectData: true,
    });
  };
  const workOrderSystemAddProps = {
    ...props,
    onAddWorkOrderSuccess: () => {
      props.onSaveState({ workOrderSystemAddModalVisible: false });
      refreshSlaveTable();
    },
  };

  let workOrderSystemDetailTitle = '';
  if (commonUtils.isNotEmptyObject(props.slaveCurrentData)) {
    const { sTitle, sModuleName, tCreateDate } = props.slaveCurrentData;
    /* eslint-disable */
    workOrderSystemDetailTitle = (
    <>
      <span style={{ opacity: 0 }}>{sTitle}</span>
      <span
        style={{ position: 'absolute', right: 70 }}
      >{`菜单名称: ${sModuleName} ${Array(10)
        .fill('\xa0')
        .join('')} 创建时间: ${tCreateDate.split(' ')[0]}`}
      </span>
      <Button
        type="link"
        style={{
          position: 'absolute',
          right: 30,
          top: 6,
          color: '#4a495f',
        }}
        onClick={() => {
          props.onSaveState({ bMin: true });
        }}
      >
        <MinusOutlined />
      </Button>
    </>);
    /* eslint-enable */
  }

  const workOrderSystemDetailProps = {
    ...props,
    sId: commonUtils.isNotEmptyObject(props.slaveCurrentData) ? props.slaveCurrentData.sId : '',
    refreshSlaveTable,
  };

  let addressStr = `${location.protocol}//${location.host}`;
  if (props.sModelsType && props.sModelsType.includes('http')) {
    addressStr = location.host;
  }

  const sFlowUrl = `${commonConfig.server_host}process/historyListerp/{sBillId}/{sBrandsId}/{sSubsidiaryId}/{sUserName}/{token}`;
  const flowHistrory = sFlowUrl !== undefined ? sFlowUrl.replace('{sBrandsId}', userinfo.sBrandsId).replace('{sSubsidiaryId}', userinfo.sSubsidiaryId).replace('{sUserName}', userinfo.sUserName).replace('{sUserId}', userinfo.sId)
    .replace('{token}', token)
    .replace('{ipAddress}', addressStr)
    .replace('{sBillId}', flowHistroyId) : '';

  // 获取树位置的配置
  let bTreeLeft = false;
  let treeLeftWidth = 300;
  let defaultExpand = true;
  const treeLeftIndex =
    commonUtils.isNotEmptyObject(slaveConfig)
      ? slaveConfig.gdsconfigformslave.findIndex(item => item.sControlName === 'bTreeLeft') : -1;
  if (treeLeftIndex !== -1) {
    bTreeLeft = true;
    const treeLeftConfig = slaveConfig.gdsconfigformslave[treeLeftIndex];
    treeLeftWidth = treeLeftConfig.iFitWidth || treeLeftWidth;
    defaultExpand = treeLeftConfig.bVisible;
  }

  return (
    <Form style={{ height: '100%' }}>
      <Layout style={{ height: '100%' }} className="xly-list">
        {!commonUtils.isEmpty(props.routing) ? '' :
        <Header className={styles.header}>
          <Toolbar {...props} />
        </Header>}
        <Layout className={styles.clayout}>
          <div style={{ maxHeight: '100%', zIndex: 20 }}>
            <SearchComponent {...props} />
          </div>
          <Content
            style={{
              height: iHeight || 'auto',
              display: 'flex',
            }}
            className={`xly-normal-list ${NoTotalData}`}
          >
            {bTreeLeft && <LeftTreeComponent {...props} treeProps={treeProps} treeLeftWidth={treeLeftWidth} defaultExpand={defaultExpand} />}
            <TreeTableComponent {...props} />
          </Content>
        </Layout>
      </Layout>
      {/* {!commonUtils.isEmpty(props.routing) ? '' : <SlaveMemo {...props} />} */}
      {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
      {!bTreeLeft && <RightTreeComponent {...props} treeProps={treeProps} />}
      {
        logVisible ?
          <AntdDraggableModal
            width="1200"
            title="查看操作日志"
            visible={logVisible}
            onCancel={props.onCancelModal.bind(this, 'logVisible')}
            onOk={props.onSelectModal.bind(this, 'logVisible')}
            footer={null}
          >
            <CommonListSelect {...logProps} />
          </AntdDraggableModal> : ''
      }
      {
        props.bDataAuditProgress ?
          <div className="dataAuditProgress">
            <Slider
              min={1}
              max={props.dataAuditProcessMaxValue}
              tooltipVisible
              step={1}
              draggableTrack
              defaultValue={3}
              value={props.dataAuditProcessValue}
            />
          </div> : ''

      }
      {
        commonUtils.isNotEmptyObject(slaveConfig) &&
        slaveConfig.sTbName === 'sys_workorder' &&
        props.bMin &&
        <Button
          style={{
            position: 'absolute',
            left: 0,
            top: '78%',
            background:
            '#ff822d',
            borderColor:
            '#ff822d',
          }}
          type="primary"
          shape="circle"
          size="large"
          onClick={() => {
            props.onSaveState({ bMin: false });
            if (window.setBMin) {
              window.setBMin(false);
            }
          }}
        >
          <MessageOutlined />
        </Button>
      }
      {
        props.workOrderSystemAddModalVisible &&
        <AntdDraggableModal
          width="70%"
          title={
            /* eslint-disable */
            <>
              <span>新增</span>
              <Button
                type="link"
                style={{
                  position: 'absolute',
                  right: 30,
                  top: 6,
                  color: '#4a495f',
                }}
                onClick={() => {
                  props.onSaveState({ bMin: true });
                }}
              >
                <MinusOutlined />
              </Button>
            </>
            /* eslint-enable */
          }
          style={{ top: 10 }}
          className={styles.workOrderSystemModal}
          visible={props.workOrderSystemAddModalVisible && !props.bMin}
          onCancel={props.onCancelModal.bind(this, 'workOrderSystemAddModalVisible')}
          onOk={props.onSelectModal.bind(this, 'workOrderSystemAddModalVisible')}
          footer={null}
        >
          <WorkOrderSystemAddModal {...workOrderSystemAddProps} />
        </AntdDraggableModal>
      }
      {
        props.workOrderSystemDetailModalVisible &&
        <AntdDraggableModal
          width="70%"
          title={workOrderSystemDetailTitle}
          style={{ top: 10 }}
          className={styles.workOrderSystemModal}
          visible={props.workOrderSystemDetailModalVisible && !props.bMin}
          onCancel={props.onCancelModal.bind(this, 'workOrderSystemDetailModalVisible')}
          onOk={props.onSelectModal.bind(this, 'workOrderSystemDetailModalVisible')}
          footer={null}
        >
          <WorkOrderSystemDetailModal {...workOrderSystemDetailProps} />
        </AntdDraggableModal>
      }
      {
        flowHistroyVisible ?
          <AntdDraggableModal
            width="90%"
            title="审批历史"
            visible={props.flowHistroyVisible}
            onCancel={props.onCancelModal.bind(this, 'flowHistroyVisible')}
            onOk={props.onCancelModal.bind(this, 'flowHistroyVisible')}
            footer={null}
          >
            {/* eslint-disable-next-line jsx-a11y/iframe-has-title */}
            <iframe src={flowHistrory} style={{ width: '100%', height: '550px' }} frameBorder="0" />
            {/* <div id="strToLabel" dangerouslySetInnerHTML={{ __html: flowHistroryData }} /> */}
          </AntdDraggableModal> : ''
      }
    </Form>
  );
});

const TreeTableComponent = (props) => {
  const {
    slavePagination,
    slaveConfig,
    formData,
    slaveData,
    isSmall,
    sModelsType,
  } = props;
  const pagination = {
    pageSize: commonUtils.isNotEmptyNumber(props.iPageSize) && props.iPageSize !== 0 ? props.iPageSize : commonConfig.pageSize,
    ...slavePagination,
    size: isSmall ? 'small' : 'large',
    pageSizeOptions: commonConfig.pageSizeOptions,
    showSizeChanger: !isSmall,
    showQuickJumper: !isSmall,
  };

  let slaveTreeData = slaveData;
  const bTree = slaveConfig?.sTableType === 'single' && slaveData?.some(item => !!item.sFatherSlaveId);
  if (bTree) {
    let keyField = 'sId';
    let keyParentField = 'sParentId';
    let sSqlCondition = '';

    if (commonUtils.isNotEmptyArr(formData)) {
      // eslint-disable-next-line prefer-destructuring
      sSqlCondition = formData[0].sSqlCondition;
      const parts = sSqlCondition.split('.');
      if (commonUtils.isNotEmptyObject(sSqlCondition) && commonUtils.isNotEmptyArr(parts) && parts.length > 2) {
        // eslint-disable-next-line prefer-destructuring
        keyField = parts[1];
        // eslint-disable-next-line prefer-destructuring
        keyParentField = parts[2];
      }
    }
    slaveTreeData = useMemo(() => commonUtils.genTreeByArr(slaveData, keyField, keyParentField), [JSON.stringify(slaveData)]);
  }

  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    data: slaveTreeData,
    tableProps: { rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange },
    onSaveState: props.onSaveState,
    clearArray: props.clearArray,
    readOnly: true,
    isSmall,
    sGroupByList: props.sGroupByList,
    customConfig: props.customConfig,
  };

  /* 有树形的不用虚拟列表 */
  if (commonUtils.isNotEmptyObject(sModelsType) && sModelsType.includes('childrenList') && commonUtils.isNotEmptyArr(slaveTreeData)) {
    tableProps.noVlist = true;
  }

  return (
    <div
      style={{
        width: 100,
        flex: 1,
        height: '100%',
      }}
    >
      {/* <StaticEditTable {...tableProps} tableBelone="list" /> */}
      <StaticEditTableNew {...tableProps} />
    </div>
  );
};

const LeftTreeComponent = (props) => {
  const { treeProps, treeLeftWidth, defaultExpand } = props;

  const [treeExpand, setTreeExpand] = useState(defaultExpand);

  return (
    <div
      style={{
        flex: `0 0 ${treeExpand ? treeLeftWidth : 15}px`,
        backgroundColor: '#fff',
        border: `${treeExpand ? 1 : 0}px solid #d9d9d9`,
        marginBottom: 10,
        position: 'relative',
      }}
    >
      {treeExpand && <StaticEditTree {...treeProps} />}
      <Button
        style={{
          position: 'absolute',
          right: 0,
          top: 'calc(50% - 20px)',
          backgroundColor: 'transparent',
          padding: 0,
          margin: 0,
        }}
        icon={<img src={Eject} alt="eject" style={{ width: 28, height: 28, rotate: treeExpand ? '0deg' : '180deg' }} />}
        type="text"
        onClick={() => {
          setTreeExpand(!treeExpand);
        }}
      />
    </div>
  );
};

const RightTreeComponent = (props) => {
  const { treeProps } = props;

  /* eslint-disable */
  return <>
    {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' : <div className="xly-eject"> <a onClick={props.onEject}> <img src={Eject} alt="eject" /></a> </div>}
    {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' :
      <div className="xly-filter-tree">
        <StaticEditTree {...treeProps} />
        <div className="xly-tree-close" >
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
          <a onClick={props.onEject}> <img src={Close} alt="close" /></a>
        </div>
      </div>
    }
  </>
  /* eslint-enable */
};

export default CommonBase(CommonListEvent(CommonList));
