/* eslint-disable */
import React, {
  useReducer,
  useContext,
  useRef,
  useState,
  useEffect
} from "react";
import { Tree, Divider, Tabs, Button, Tooltip } from "antd-v4";
import {
  ProfileOutlined,
  FileTextOutlined,
  PrinterOutlined
} from "@ant-design/icons";
import styles from "./index.less";
import CommonViewTable from "@/components/Common/CommonViewTable";
import CommonViewDragable from "@/components/Common/CommonViewDragable";
import { useReactToPrint } from "react-to-print";
// const getPageMargins = () => {
//   return `@page { margin: 10 10 10 10 !important; }`;
// };
// <style>{getPageMargins()}</style>

import * as commonUtils from "@/utils/utils";
const { myContext, reducer } = commonUtils;

const initialState = {
  selectedData: {}
};

const CommonPartsInfo = props => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const { processData = [], controlData = [] } = props;
  const allData = [
    ...controlData.map(item => ({ ...item, iLv: 2 })),
    ...processData
  ];

  const contentRef = useRef(null);

  return (
    <myContext.Provider
      value={{
        props,
        hooksProps: { ...state, dispatch, contentRef }
      }}
    >
      <div className={styles.commonPartsInfo}>
        <div className="leftTree">
          {location.pathname === "/indexPage/processCardPackTableTree" ? (
            <TreeComponent />
          ) : (
            <TreeComponent1 />
          )}
        </div>
        <div className="rightContent" ref={contentRef}>
          <ContentComponent />
          {allData.map(item => (
            <ContentComponent selectedData={item} hidePrint />
          ))}
        </div>
      </div>
    </myContext.Provider>
  );
};

const TreeComponent = () => {
  const { props, hooksProps } = useContext(myContext);
  const { dispatch } = hooksProps;
  const {
    slaveData = [],
    controlData = [],
    processData = [],
    partsInfoBtnConfig = {}
  } = props;
  const { sAssignField } = partsInfoBtnConfig;
  const [selectedKeys, setSelectedKeys] = useState([]);
  const initFlag = useRef(true);

  const treeData = [];
  slaveData.forEach(slaveRow => {
    const { sId: sId0, sProductName, sProductNo } = slaveRow;
    const lv1 = {
      title: sProductName,
      key: sId0,
      icon: <ProfileOutlined />,
      readOnly: true,
      children: []
    };

    let bFirst = true;
    controlData.forEach(controlRow => {
      const { sId: sId1, sPartsName, sCombinedMemo } = controlRow;
      const sCombinedMemoArr = commonUtils.convertStrToObj(sCombinedMemo, []);
      const bMatch = sCombinedMemoArr.some(
        item => item.sProductNo && sProductNo === item.sProductNo
      );
      if (bMatch) {
        if (bFirst) {
          bFirst = false;
          treeData.push(lv1);
        }
        const lv2 = {
          title: sPartsName,
          key: sId1,
          icon: <ProfileOutlined />,
          readOnly: false
        };
        lv1.children.push(lv2);
        const childrenData = processData.filter(
          process => process.sControlId === sId1
        );
        if (commonUtils.isNotEmptyArr(childrenData)) {
          lv2.children = childrenData.map(process => {
            const { sId, sProcessName } = process;
            const sMemo = sAssignField ? process[sAssignField] : "";
            if (initFlag.current) {
              initFlag.current = false;
              setSelectedKeys([sId]);
            }
            return {
              title: `${sProcessName}${
                sAssignField ? `【${sMemo || "无"}】` : ""
              }`,
              key: sId,
              icon: <FileTextOutlined />
            };
          });
        }
      }
    });
  });

  useEffect(
    () => {
      if (selectedKeys[0]) {
        /* 判断是从表的选中还是第三层工序表选中 */
        let selectedData = processData.find(
          item => item.sId === selectedKeys[0]
        );
        if (commonUtils.isEmptyArr(selectedData)) {
          // selectedData =  slaveData.find(item => item.sId === selectedKeys[0]);
          // if(commonUtils.isNotEmptyObject(selectedData)) {
          //   selectedData.iLv = 1; /* 从表选中 */
          // }
          selectedData = controlData.find(item => item.sId === selectedKeys[0]);
          if (commonUtils.isNotEmptyObject(selectedData)) {
            selectedData.iLv = 2; /* 控制表选中 */
          }
        }
        dispatch([
          "saveState",
          {
            selectedData: selectedData
          }
        ]);
      }
    },
    [selectedKeys[0]]
  );

  return (
    <Tree
      showLine
      showIcon
      defaultExpandAll
      selectedKeys={selectedKeys}
      treeData={treeData}
      onSelect={(selectedKeys, { node }) => {
        if (!node.readOnly) {
          setSelectedKeys(selectedKeys);
        }
      }}
    />
  );
};

const TreeComponent1 = () => {
  const { props, hooksProps } = useContext(myContext);
  const { dispatch } = hooksProps;
  const { controlData = [], processData = [] } = props;

  const [selectedKeys, setSelectedKeys] = useState([]);
  const initFlag = useRef(true);
  const treeData = controlData.map(control => {
    const { sId, sPartsName } = control;
    const lv1 = {
      title: sPartsName,
      key: sId,
      icon: <ProfileOutlined />
      // readOnly: true
    };

    const childrenData = processData.filter(
      process => process.sControlId === sId
    );
    if (commonUtils.isNotEmptyArr(childrenData)) {
      lv1.children = childrenData.map(process => {
        const { sId, sProcessName } = process;
        if (initFlag.current) {
          initFlag.current = false;
          setSelectedKeys([sId]);
        }
        return {
          title: sProcessName,
          key: sId,
          icon: <FileTextOutlined />
        };
      });
    }

    return lv1;
  });

  useEffect(
    () => {
      if (selectedKeys[0]) {
        /* 判断是从表的选中还是第三层工序表选中 */
        let selectedData = processData.find(
          item => item.sId === selectedKeys[0]
        );
        if (commonUtils.isEmptyArr(selectedData)) {
          // selectedData =  slaveData.find(item => item.sId === selectedKeys[0]);
          // if(commonUtils.isNotEmptyObject(selectedData)) {
          //   selectedData.iLv = 1; /* 从表选中 */
          // }
          selectedData = controlData.find(item => item.sId === selectedKeys[0]);
          if (commonUtils.isNotEmptyObject(selectedData)) {
            selectedData.iLv = 2; /* 控制表选中 */
          }
        }
        dispatch([
          "saveState",
          {
            selectedData: selectedData
          }
        ]);
      }
    },
    [selectedKeys[0]]
  );

  return (
    <Tree
      showLine
      showIcon
      defaultExpandAll
      selectedKeys={selectedKeys}
      treeData={treeData}
      onSelect={(selectedKeys, { node }) => {
        if (!node.readOnly) {
          setSelectedKeys(selectedKeys);
        }
      }}
    />
  );
};

const ContentComponent = nextProps => {
  const { selectedData: selectedData0, hidePrint } = nextProps;
  const { props, hooksProps } = useContext(myContext);
  const { partsInfoType, slaveGuidConfig } = props;
  const { selectedData: selectedData1, contentRef } = hooksProps;
  const selectedData = selectedData0 || selectedData1;
  let { sProcessName } = selectedData;

  let bSlave = false;
  if (commonUtils.isNotEmptyObject(selectedData)) {
    if (selectedData.iLv === 1) {
      bSlave = true;
      sProcessName = selectedData.sProductName;
    } else if (selectedData.iLv === 2) {
      bSlave = true;
      sProcessName = selectedData.sPartsName;
    }
  }
  const commonViewDragableProps = {
    ...props,
    hideTabsNav: true,
    sParamData: [
      {
        sParamType: partsInfoType,
        sParamName: "参数"
      }
    ],
    tableName: "partsInfo",
    partsInfoData: [selectedData],
    partsInfoSelectedRowKeys: [selectedData.sId]
  };
  /* 从表view */
  const viewConfig = commonUtils.isNotEmptyObject(slaveGuidConfig)
    ? slaveGuidConfig.gdsconfigformslave.filter(
        item =>
          item.sName !== "" &&
          item.bControl &&
          item.sControlName.indexOf("Btn") === -1
      )
    : [];
  // const slaveViewProps = {
  //   ...props,
  //   viewConfigs: viewConfig,
  //   tableConfig: slaveGuidConfig,
  //   iColValueView: 24,
  //   viewRow: selectedData,
  //   tableName: 'slave',
  // };
  const controlViewProps = {
    ...props,
    viewConfigs: viewConfig,
    tableConfig: slaveGuidConfig,
    iColValueView: 24,
    viewRow: selectedData,
    tableName: "control"
  };

  const customToPrint = printWindow => {
    const printedScrollContainer = contentRef.current;
    const originScrollContainer = contentRef.current;
    printedScrollContainer.scrollTop = originScrollContainer.scrollTop;
    printWindow.contentWindow.print();
  };

  const reactToPrintFn = useReactToPrint({ contentRef, print: customToPrint });
  const tabBarExtraContent = !hidePrint
    ? {
        right: (
          <Tooltip title="打印全部">
            <Button
              type="icon"
              icon={<PrinterOutlined />}
              onClick={reactToPrintFn}
            />
          </Tooltip>
        )
      }
    : {};

  return (
    <>
      {bSlave ? (
        <div className={hidePrint ? styles.xlyPrintShow : styles.xlyPrintHide}>
          {/* <Divider orientation="left" plain>
            {sProcessName}
          </Divider> */}
          <Tabs
            defaultActiveKey="1"
            tabBarExtraContent={tabBarExtraContent}
            items={[
              {
                label: sProcessName,
                key: "1",
                children: <CommonViewTable {...controlViewProps} />
              }
            ]}
          />
        </div>
      ) : (
        <div className={hidePrint ? styles.xlyPrintShow : styles.xlyPrintHide}>
          {/* <Divider orientation="left" plain>
            {sProcessName}
          </Divider> */}
          <Tabs
            defaultActiveKey="1"
            tabBarExtraContent={tabBarExtraContent}
            items={[
              {
                label: sProcessName,
                key: "1",
                children: <CommonViewDragable {...commonViewDragableProps} />
              }
            ]}
          />
        </div>
      )}
    </>
  );
};

export default CommonPartsInfo;
