import React, { useState, useEffect, useCallback, useRef } from "react";
import { useHistory } from "react-router-dom";
import PropTypes from "prop-types";
import styles from "./style.less";
import Navigator from "./component/navigator/view.jsx";
import Top from "./component/top/view.jsx";
import ModelMsg from "./component/modelMsg/view.jsx";
import BreadcrumbView from "./component/breadcrumb/view";
import TipMsg from "./component/tipMsg/view.jsx";

import $store from "@store/";
import {
  Dropdown,
  Menu,
  message,
  Button,
  Form,
  Modal,
  Tabs,
  Input,
} from "antd";
import DefaultImg from "@components/defaultImg/view.jsx";
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  AreaChartOutlined,
  PieChartOutlined,
  BarChartOutlined,
  DotChartOutlined,
  LineChartOutlined,
  RadarChartOutlined,
  HeatMapOutlined,
  FallOutlined,
  RiseOutlined,
  StockOutlined,
  BoxPlotOutlined,
  FundOutlined,
  SlidersOutlined,
  DatabaseOutlined,
  DollarOutlined,
  ControlOutlined,
  CodeOutlined,
  BarsOutlined,
  AppstoreAddOutlined,
  ApartmentOutlined,
  InfoCircleOutlined,
  StarOutlined,
  StarFilled,
} from "@ant-design/icons";
import {
  getDmpAccessUrl,
  getFineBiToken,
  getValueByDictCode,
  getPreFineBiUrl,
  getSunwayAccessUrl,
} from "./component/top/api";
import { dealDiffSheetType, crossMenuClick } from "@utils/util";
import utils from "@utils/index";
import "@themes/themes.less";
import { saveMenu } from "@apis/enter.js";
import { careOrCancelResource, getUserResourceTree } from "./api";
import { observer, observable } from "mobx-react";
import { toJS } from "mobx";
const { SubMenu } = Menu;
const { TabPane } = Tabs;

// Frame.propTypes = {
//   child: PropTypes.object,
// };

let keys = [];

let attrs = {
  style: { color: "#c7c7c7", fontSize: 13 },
};

const iconObj = {
  AreaChartOutlined: <AreaChartOutlined {...attrs} />,
  PieChartOutlined: <PieChartOutlined {...attrs} />,
  BarChartOutlined: <BarChartOutlined {...attrs} />,
  DotChartOutlined: <DotChartOutlined {...attrs} />,
  LineChartOutlined: <DotChartOutlined {...attrs} />,
  RadarChartOutlined: <RadarChartOutlined {...attrs} />,
  HeatMapOutlined: <HeatMapOutlined {...attrs} />,
  FallOutlined: <FallOutlined {...attrs} />,
  RiseOutlined: <RiseOutlined {...attrs} />,
  StockOutlined: <StockOutlined {...attrs} />,
  BoxPlotOutlined: <BoxPlotOutlined {...attrs} />,
  FundOutlined: <FundOutlined {...attrs} />,
  SlidersOutlined: <SlidersOutlined {...attrs} />,
  DatabaseOutlined: <DatabaseOutlined {...attrs} />,
  DollarOutlined: <DollarOutlined {...attrs} />,
  ControlOutlined: <ControlOutlined {...attrs} />,
  CodeOutlined: <CodeOutlined {...attrs} />,
  BarsOutlined: <BarsOutlined {...attrs} />,
  AppstoreAddOutlined: <AppstoreAddOutlined {...attrs} />,
  ApartmentOutlined: <ApartmentOutlined {...attrs} />,
};

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 18,
  },
};

let leafNode = {
  // nodeId: {num, parentIds}
};

const findLeaves = (tree = []) => {
  function loop(list, parentIds = []) {
    list.map((item) => {
      // 新建当前ID的键值对
      if ((item.resourceList || []).length > 0) {
        loop(item.resourceList, parentIds.concat([item.resourceId]));
      } else {
        leafNode[item.resourceId] = {
          name: item.resourceName,
          id: item.resourceId,
          parentIds,
        };
      }
    });
  }

  loop(tree, []);
};

let sVal = "";

export default observer(function Frame(props) {
  const [searchVal, setSearchVal] = useState(""); /**搜索关键词内容 */
  const [collapsed, setCollapsed] = useState(false);
  const [leftMenuHeight, setleftMenuHeight] = useState("100%");
  const [leftMenuWidth, setleftMenuWidth] = useState(220);
  const [modelMsgs, setModelMsgs] = useState({});
  const [tipMsgs, setTipMsgs] = useState({});
  const history = useHistory();
  const [curKey, setKey] = useState("1");
  const moveBar = useRef();
  const [isMove,setisMove] = useState(false);
  const name_arr = {
    "#/home/gvc": "产供销价值链",
    "#/home/operation": "运营数据中心",
    "#/home/tlk": "TLK运营数据中心 / TLK Plant Dashboard",
  }
  const [titleName, setTitleName] = useState(name_arr[window.location.hash]);

  const { Search } = Input;
  let showIds = $store.app.showIds;

  function calcValue(str) {
    if (str === "sysToken") {
      return `${sessionStorage.getItem("token")}$`;
    }
  }

  document.onmousemove = function (e) {
    //是否为可移动状态
    if (isMove) {
      let e = e || window.event;

      let moveX = e.clientX; //得到距离左边移动距离
      if (moveX < 44) {
        moveX = 44;
      } else if (moveX > 800) {
        moveX = 800;
      }
      setleftMenuWidth(moveX);
    } else {
      return;
    }
  };

  document.onmouseup = () => {
    setisMove(false);
  };

  const stopLeftMenu = () => {
    setisMove(false);
  };

  const moveLeftMenu = () => {
    setisMove(true);
  };

  /**打开 报表目录 */
  const openReportDire = (key) => {
    let activePath = `/home/directory/${key}`;
    let navObj = {
      name: sessionStorage.getItem("resourceName"),
      path: activePath,
      type: "sys",
      openType: "self",
      id: key,
    };
    // $store.app.setNavList(navObj);
    // $store.app.setCurNav(activePath);
    // history.push(activePath);
  };

  function callback(key) {
    return setKey(key);
  }

  const onResize = useCallback(() => {
    setleftMenuHeight(document.documentElement.clientHeight - 82 + "px");
  }, []);
  const onResize_pop = useCallback(() => {
  }, []);

  useEffect(() => {
    setSearchVal("");
    leafNode = {};
    $store.app.setShowIds([]);
    // showIds = [];
    setleftMenuHeight(document.documentElement.clientHeight - 82 + "px");
    window.addEventListener("resize", onResize);

    findLeaves($store.sysMenu.submenuList);

    return () => {
      window.removeEventListener("resize", onResize);
      window.removeEventListener("popstate", onResize_pop);
    };
  }, [$store.app.refresh]);

  const onRef = (ref) => {
    setModelMsgs(ref);
  };
  const getTips = () => {
    tipMsgs.getTip()
  };
  const cleatTips = () => {
    tipMsgs.cleatTips()
  };
  const onRef2 = (ref) => {
    setTipMsgs(ref);
    console.log(tipMsgs, "tipMsgs")
  };

  return (
    <div className={styles.frame}>
      <Top names={titleName}/>
      <ModelMsg onRef={onRef} getTips={getTips} cleatTips={cleatTips} changeName={(name) => {
        setTitleName(name);
      }} />

      {/* 断网或超时显示提示 */}
      {/* <div className="nowifi-tip">当前网络状态不佳</div> */}

      {/* 正文 */}
      <div style={{ display: "flex", height: '100%' }}>
        {$store.sysMenu.submenuList.length > 0 && !collapsed && (
          <div
            className="movebar"
            style={{ left: leftMenuWidth }}
            ref={moveBar}
            onMouseDown={moveLeftMenu}
            onMouseUp={stopLeftMenu}
          ></div>
        )}
        {isMove && <div className="markmore"></div>}

        <div
          className={"body_box homePage"}
        >
          <Navigator
            style={{
              display: "none",
            }}
          />
          <TipMsg onRef={onRef2}></TipMsg>
          {$store.app.navList.length === 0 && false &&
            !history.location.pathname.match(/index|work|center|clush/) ? (
            <DefaultImg />
          ) : (
            props.child && props.child
          )}
        </div>
      </div>

      {/* 元数据展示 */}
      <Modal
        title="报表元数据"
        visible={$store.app.metaData.visible}
        width="665px"
        onCancel={() => {
          $store.app.setMetaData({
            visible: false,
          });
        }}
        footer={null}
      >
        <Form {...layout}>
          <Tabs defaultActiveKey="0" onChange={callback}>
            <TabPane tab="基础信息" key="0">
              <Form.Item name="remark" label="报表描述" {...formItemLayout}>
                <span>{$store.app.metaData.data.remark}</span>
              </Form.Item>

              <Form.Item name="department" label="责任部门" {...formItemLayout}>
                <span>{$store.app.metaData.data.departmentInfo}</span>
              </Form.Item>

              <Form.Item name="charger" label="资产责任人" {...formItemLayout}>
                <span>{$store.app.metaData.data.charger}</span>
              </Form.Item>

              <Form.Item name="itManager" label="IT经理" {...formItemLayout}>
                <span>{$store.app.metaData.data.itManager}</span>
              </Form.Item>

              <Form.Item name="itDeveloper" label="IT研发" {...formItemLayout}>
                <span>{$store.app.metaData.data.itDeveloper}</span>
              </Form.Item>
            </TabPane>

            <TabPane tab="资产信息" key="1">
              <Form.Item name="dataFrom" label="数据来源" {...formItemLayout}>
                <span>{$store.app.metaData.data.dataFrom}</span>
              </Form.Item>

              <Form.Item
                name="updateFrequency"
                label="数据更新频率"
                {...formItemLayout}
              >
                <span>{$store.app.metaData.data.updateFrequency}</span>
              </Form.Item>

              <Form.Item name="businessFormat" label="业态" {...formItemLayout}>
                <span>{$store.app.metaData.data.businessFormat}</span>
              </Form.Item>

              <Form.Item name="module" label="业务模块" {...formItemLayout}>
                <span>{$store.app.metaData.data.module}</span>
              </Form.Item>

              <Form.Item
                name="sonModule"
                label="业务子模块"
                {...formItemLayout}
              >
                <span>{$store.app.metaData.data.sonModule}</span>
              </Form.Item>

              <Form.Item name="assetType" label="资产类型" {...formItemLayout}>
                <span>{$store.app.metaData.data.assetType}</span>
              </Form.Item>

              <Form.Item name="assetLevel" label="资产密级" {...formItemLayout}>
                <span>{$store.app.metaData.data.assetLevel}</span>
              </Form.Item>
            </TabPane>
          </Tabs>
        </Form>
      </Modal>
    </div>
  );
});
