/* eslint-disable */
import React, { PureComponent } from "react";
import { Form } from "@ant-design/compatible";
// import "@ant-design/compatible/assets/index.css";
import { Layout, Spin, Button, Row, Col } from "antd-v4";
import * as commonFunc from "@/components/Common/commonFunc"; /* 通用单据方法 */ /* 通用单据方法 */
import StaticEditTable from "@/components/Common//CommonTable"; /* 可编辑表格 */
import StaticEditTree from "@/components/Common/Tree/StaticTree";
import CommonBase from "@/components/Common/CommonBase"; /* 获取配置及数据 */
import * as commonBusiness from "@/components/Common//commonBusiness"; /* 单据业务功能 */
import SearchComponent from "@/components/Common/SearchComponent";
import * as commonUtils from "@/utils/utils";
import CommonListEvent from "@/components/Common/CommonListEvent";
import { cloneDeep } from "lodash";

const { Content } = Layout;

class CommonList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      filterTreeData: [],
      filterTreeDataKey: [],
      filterTreeDetailData: [],
      filterTreeDetailDataKey: [],
      slaveFilterKeys: null,
    };
  }

  componentDidUpdate(prevProps, prevState) {
    const { props } = this;
    if (Array.isArray(props.slaveData) && props.slaveData.length) {
      if (!this.hasUpdate) {
        this.hasUpdate = true;
        this.replaceData();
      }
    }
    if (Array.isArray(props.treeData) && props.treeData.length) { 
      if (!this.hastreeUpdate) {
        this.hastreeUpdate = true;
        this.setState({
          filterTreeData: props.treeData?.slice(0, 1),
          filterTreeDataKey: [props.treeData?.[0]?.key],
          filterTreeDetailData: props.treeData?.slice(1, 2),
          filterTreeDetailDataKey: [props.treeData?.[1]?.key],
        })
      }
    }
  }

  // 更新数据
  replaceData = () => {
    const { props } = this;
    const { slaveSelectedRowKeys = [] } = props;
    if (props.app?.currentPane?.config?.sControlName?.startsWith('BtnPopupEdit')) {
      const selectData = props.app?.sMemoData;
      const showHasEditData = [];
      if (Array.isArray(selectData)) {
        selectData.forEach((i) => {
          const index = props.slaveData?.findIndex(j => j && j.sId === i.sId);
          if (index >= 0) {
            props.slaveData[index] = i;
          } else {
            showHasEditData.push(i);
          }
        });
        const slaveData = [...props.slaveData || [], ...showHasEditData];
        const slaveSelectedRowKeysNew = Array.isArray(selectData) ? selectData.map(i => i && i.sSlaveId).filter(Boolean) : [];
        props.onSaveState({ slaveSelectedRowKeys: [...slaveSelectedRowKeysNew, ...slaveSelectedRowKeys], slaveData, slaveSelectedData: selectData || [] });
      }
    }
  };

  handleSelect = () => {
    const { slaveSelectedRowKeys, app, slaveData } = this.props;
    this.props.app.currentPane.select(
      app.currentPane.name,
      app.currentPane.config,
      slaveData.filter(item => slaveSelectedRowKeys.includes(item.sSlaveId)),
    );
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };

  handleDoubleClickSelect = () => {
    const { slaveConfig } = this.props;
    if (commonUtils.isNotEmptyObject(slaveConfig) && !slaveConfig.bMutiSelect) {
      // 单选时双击选中数据
      this.handleSelect();
    }
  };

  /**   关闭   */
  handleCancelModal = () => {
    const { app } = this.props;
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };
  /**   树节点多选框选中   */
  handleTreeCheck = (checkedKeys, e) => {
    this.props.onCheck(checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };

  filterData = (data, selectKeys) => {
    if (!selectKeys) return data;
    if (Array.isArray(data)) {
      return data.filter(i => {
        if (i) {
           if (selectKeys === i.sSqlConditionId) {
            return true
           }
           if (i.children && i.children.length) {
            const value = this.filterData(i.children, selectKeys);
            if (value.length) { 
              i.children = value;
              return true;
            }
           }
        }
        return false;
      })
    }
    return [];
  }

  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e, treeName) => {
    if (treeName === 'filterTreeData' && Array.isArray(this.props.treeData)) {
      if (['sOffsetwaste'].includes(this.props.app?.currentPane?.config?.sName)) {
        const value = this.filterData(cloneDeep(this.props.treeData.slice(1,2)), checkedKeys?.[0]?.split('_')[1]);
        this.setState({ filterTreeDetailData: value });
        return;
      }
      if (['sFilmwaste'].includes(this.props?.app?.currentPane?.config?.sName)) {
        this.setState({ slaveFilterKeys: checkedKeys?.[0]?.split('_')[1] });
        return;
      }
    }
    if (treeName === 'filterTreeDetailData') {
      this.setState({ slaveFilterKeys: checkedKeys?.[0]?.split('_')[1] });
    }
  };

  onExpandTree = (key, name) => {
    this.setState({
      [name]: key,
    });
  }

  
  // ----------------------------数据修改回带end  ---------------------------- //

  render() {
    const { pageLoading } = this.props;
    const filterSpan = this.props.treeData?.length >= 2 ? this.props.filterSpan || 4 : 0;
    const treeSpan = this.props.treeData?.length >= 1 ? this.props.treeSpan || 4 : 0;
    const tableSpan = this.props.treeData?.length >= 2 ? this.props.tableSpan : 24 - filterSpan - treeSpan;
    return (
      <div style={{ height: "100%" }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: "100%" }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              onSelect={this.handleSelect}
              onCancel={this.handleCancelModal}
              onDoubleClick={this.handleDoubleClickSelect}
              onCheck={this.handleTreeCheck}
              onSelectTree={this.handleTreeSelect}
              onExpandTree={this.onExpandTree}
              filterData={this.filterData}
              filterTreeDetailSelectKeys={this.state.filterTreeDetailSelectKeys}
              tableSpan={tableSpan}
              treeSpan={treeSpan}
              filterSpan={filterSpan}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonListComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  }
})(props => {

  const {
    form,
    onReturnForm,
    slavePagination,
    app,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const pagination = {
    ...slavePagination,
    size: "large",
    pageSize: 1000,
    showQuickJumper: true,
    hideOnSinglePage: true
  };

  const bEdit = commonUtils.isNotEmptyObject(app.currentPane) && commonUtils.isNotEmptyObject(app.currentPane.name) && app.currentPane.bEdit; /* 是否可编辑 */

  const tableProps = {
    ...commonBusiness.getTableTypes("slave", props),
    tableProps: {
      rowKey: "sSlaveId",
      pagination,
      onChange: props.onTitleChange,
      AutoTableHeight: 375,
    },
    bRowClick: bEdit,
    enabled: bEdit,
    onDelRow: (name, isWait, tableSelectedRowKeys, callback, index) => props.onDataRowDel(name, isWait, tableSelectedRowKeys, callback, index, props?.app?.currentPane?.config?.sControlName),
    onAddRow: (name, isWait) => props.onDataRowAdd(name, isWait, props?.app?.currentPane?.config?.sControlName),
  };

  const treeProps = {
    ...commonBusiness.getTreeTypes("tree", props),
    isSearch: false,
    checkable: false,
    disabled: false,
    checkedAll: false,
    unChecked: false,
    defaultExpandAll: true,
    multiple: false,
    onSaveState: props.onSaveState
  };

  const tableBelone =
    commonUtils.isNotEmptyObject(app.currentPane) &&
    commonUtils.isNotEmptyObject(app.currentPane.name) &&
    app.currentPane.bEdit
      ? "none"
      : "list";

  let slaveDataShow = props.slaveData || [];
  if (props.slaveFilterKeys) {
    slaveDataShow = props.slaveData.filter(i => i && i.sSqlConditionId === props.slaveFilterKeys);
  }

  return (
    <div className="modalChooseProcessContent">
      <Form>
        <Layout>
          <Layout>
            <div>
              <div style={{ maxHeight: "100%", zIndex: 20 }}>
                <SearchComponent {...props} />
              </div>
              <Content
                className="xly-normal-list"
                style={{ paddingLeft: "10px" }}
              >
                <Row gutter={[8, 0]}>
                  <Col span={props.treeSpan}>
                    <div className="xly-tree-box">
                      <div className="xly-tree-title">过滤项</div>
                      <StaticEditTree 
                        {...treeProps}
                        expandedKeys={props.filterTreeDataKey} 
                        onExpandTree={(_, expandedKeys) => props.onExpandTree(expandedKeys, 'filterTreeDataKey')}
                        treeData={props.filterTreeData}
                        onSelect={(name, checkedKeys, e) => props.onSelectTree(name, checkedKeys, e, 'filterTreeData')}
                      />
                    </div>
                  </Col>
                  <Col span={props.filterSpan}>
                    <div className="xly-tree-box">
                      <div className="xly-tree-title">过滤项</div>
                      <StaticEditTree 
                        {...treeProps}
                        expandedKeys={props.filterTreeDetailDataKey}
                        onExpandTree={(_, expandedKeys) => props.onExpandTree(expandedKeys,'filterTreeDetailDataKey')}
                        treeData={props.filterTreeDetailData} 
                        onSelect={(name, checkedKeys, e) => props.onSelectTree(name, checkedKeys, e, 'filterTreeDetailData')}
                      />
                    </div>
                  </Col>
                  <Col span={props.tableSpan || 16}>
                    <StaticEditTable
                      {...tableProps}
                      data={slaveDataShow}
                      footer="hidden"
                      tableBelone={tableBelone}
                      noVlist
                      showConfig={props.showConfig}
                      setOpterationColumn={props.setOpterationColumn || 'Y'}
                    />
                  </Col>
                </Row>
              </Content>
            </div>
          </Layout>
          <div
            style={{
              textAlign: "right",
              marginRight: "9px",
              marginBottom: "9px"
            }}
          >
            <Button
              key="back"
              style={{ marginRight: "8px" }}
              onClick={props.onCancel}
            >
              取消
            </Button>
            <Button type="primary" onClick={props.onSelect}>
              确认
            </Button>
          </div>
        </Layout>
      </Form>
    </div>
  );
});

export default CommonBase(CommonListEvent(CommonList));
