import GridLayout, { ReactGridLayoutProps } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import style from './index.less';
import {
  CHILD_MAP,
  DEFAULT_LAYOUT,
  COL_COLS,
  ROW_COLS,
  DEFAULT_MAP_LAYOUT,
  U3D_PATH_STATE,
} from './config';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Modal } from 'antd';
import Model from './Model';
import { useModel, useRequest } from '@umijs/max';
import {
  getLayoutOptions,
  saveLayoutOptions,
} from '@/Project/services/DataMeter';

const gridWidth = document.documentElement.clientWidth;

function DataMeter(props: DataMeter.IProps) {
  const {
    initialState: { projectId },
  } = useModel('@@initialState');

  const { hasModel, subModule, isNew } = props;
  // 编辑模块
  const [editVisible, setEditVisible] = useState(false);
  // 子模块列表
  const [currentModel, setCurrentModel] = useState<DataMeter.ILayout>();
  // 抽屉栏显示状态
  const [visible, setVisible] = useState(false);
  // 布局信息
  const [layout, setLayout] = useState<DataMeter.ILayout[]>([]);
  // 编辑状态
  const [edit, setEdit] = useState(false);
  // 子模块多选
  const [modelCheck, setModelCheck] = useState<any>([]);

  const [dataCenterChild, setDataCenterChild] = useState([]);
  // map 类型
  const [type, setType] = useState('1');
  // 根据col算出高度
  const [rowHeight, setRowHeight] = useState(
    (document.documentElement.clientHeight - 70) / ROW_COLS,
  );
  const mapEle = useRef();
  const [hasSwitchSubModule, setHasSwitchSubModule] = useState(false);
  //模块列表抽屉显示状态
  const [mouldVisible, setMouldVisible] = useState(false);
  //创建模板弹窗状态
  const [createMouldVisible, setCreateMouldVisible] = useState(false);

  const layoutRequest = useRequest(getLayoutOptions, {
    defaultParams: [
      {
        projectId: projectId || 0,
        module: 1,
        sub_module: subModule,
        is_default: 0,
      },
    ],
    onSuccess(data, params) {
      setLayout(data.config_json);
    },
  });
  // 布局发生改变回调函数
  const onLayoutChange = (newLayout: DataMeter.ILayout[]) => {
    // console.log(newLayout);
    let newArr = newLayout.map((newModel) => {
      let oldModel = layout.find((item) => item.i == newModel.i) || {};
      return {
        // 新属性覆盖旧属性
        ...oldModel,
        ...newModel,
      };
    });
    setLayout(newArr);
    if (!edit && hasSwitchSubModule) {
      // getMapPosition();
      setHasSwitchSubModule(false);
    }
  };

  // 删除模块
  const removeModel = (key: string, active: string) => {
    Modal.confirm({
      title: '提醒',
      content: `确认删除模块吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        let index = layout.findIndex((cur) => {
          if (active) return key == cur.key && active == cur.active;
          return key == cur.key;
        });
        let newLayout = [...layout];
        newLayout.splice(index, 1);
        setLayout(newLayout);
      },
    });
  };
  // 显示子模块编辑框
  const showEditModel = (item: DataMeter.ILayout) => {
    // 模块列表显示时会导致无法滚动的bug，编辑时隐藏模块列表
    setVisible(false);
    setEditVisible(true);
    setCurrentModel(item);

    // 设置默认选中
    let checked: any[] = [];
    item.child?.forEach((item) => {
      if (item.show) checked.push(item.key);
    });
    setModelCheck(checked);
  };
  // 保存配置
  const saveLayout = async (newLayout: DataMeter.ILayout[], isDefault = 0) => {
    let id,
      payload = {
        projectId,
        module: 1,
        sub_module: subModule,
        is_default: isDefault,
      };
    if (isDefault == 1) {
      // 查询默认配置的id
      let res = await getLayoutOptions({ ...payload });
      id = res.data.id || 0;
      // 修改默认配置
      await saveLayoutOptions({
        ...payload,
        config_json: JSON.stringify(newLayout),
        id,
        //默认配置的projectId为0
      });
    } else {
      let item = layoutRequest.data;
      id = item.is_default == 1 ? 0 : item.id;
      await saveLayoutOptions({
        ...payload,
        config_json: JSON.stringify(newLayout),
        id,
      });
    }
  };
  const models = useMemo(() => {
    return layout.map((item) => {
      const setActive = (key: number | string) => {
        item.active = key;
        saveLayout(layout);
      };
      return (
        <Model
          key={item.i}
          hasModel={hasModel}
          child={item.child || []}
          projectId={projectId}
          removeModel={removeModel}
          edit={edit}
          layout={item}
          setActive={setActive}
          subModule={subModule}
          isNew={isNew}
          showEditModel={showEditModel}
        />
      );
    });
  }, [layout]);

  console.log(layoutRequest);

  return (
    <div
      className={`dataMeter ${style.dataMeter} ${!edit ? style.noScroll : ''}`}
      // onDragEnd={onDragEnd}
      style={{ minHeight: '100vh' }}
    >
      {/* <CreateMould
          visible={createMouldVisible}
          handleCancel={() => setCreateMouldVisible(false)}
          handleOk={createMouldHandleOk}
        ></CreateMould>
        <DrawerLeft
          onClose={() => {
            setVisible(false);
          }}
          layout={layout}
          dragActive={dragActive}
          addModel={addModel}
          removeModel={removeModel}
          // onDrag={onHandleDrag}
          visible={visible}
          subModule={subModule}
          dataCenterChild={dataCenterChild}
        />
        {mouldVisible && <div className={style.mask}></div>}
        <MouldDrawerLeft
          mouldList={mouldList}
          onClose={() => {
            setMouldVisible(false);
          }}
          visible={mouldVisible}
          mouldSave={saveMould}
        ></MouldDrawerLeft> */}
      {/*         
        <EditMould
          title="编辑子模块"
          visible={editVisible}
          onOk={handleOk}
          onCancel={() => {
            setEditVisible(false);
          }}
          setModelCheck={setModelCheck}
          modelCheck={modelCheck}
          setCurrentModel={setCurrentModel}
          currentModel={currentModel}
        ></EditMould> */}
      <div className={style.gridBox}>
        <GridLayout
          className="layout"
          isDraggable={edit}
          isResizable={edit}
          // layout={layout}
          layout={[
            {
              i: '1',
              w: 1,
              h: 2,
              x: 0,
              y: 0,
            },
            {
              i: '2',
              w: 1,
              h: 2,
              x: 0,
              y: 0,
            },
            {
              i: '3',
              w: 1,
              h: 2,
              x: 0,
              y: 0,
            },
          ]}
          onLayoutChange={onLayoutChange}
          cols={COL_COLS}
          rowHeight={rowHeight}
          width={gridWidth}
          margin={[15, 10]}
        >
          {/* {models} */}
          <div>1</div>
          <div>2</div>
          <div>3</div>
        </GridLayout>
      </div>
    </div>
  );
}

export default DataMeter;
