import React, { useState, useEffect, useMemo, useReducer } from 'react';
import { connect } from 'react-redux';
import type { FC } from 'react';
import styles from './index.less';
import { GroupMenu, Template, UploadModal } from './containers';
import { useTitle } from 'components/easyUse';
import { resetMaterial } from 'models/material-lib';
import { getGroupList, getItemList, getStorage } from './api';
import { GROUP_FIELDS as F, STATIC } from './constant';
import orderBy from 'lodash/orderBy';

export const SourceContext = React.createContext<any>({});

const Resource: FC<any> = ({ spaceId, resetMaterial }) => {
  useTitle('资源中心');
  const [sourceStore, dispatch] = useReducer((a, b) => ({ ...a, ...b }), {
    type: 0,
    draggingType: null,
    draggingId: null,
    draggingGroupId: null
  });

  const [storage, setStorage] = useState<any>(null);
  const [groupId, setGroupId] = useState<any>([]);
  const [groups, setGroups] = useState<any>([]);
  const [alllist, setAlllist] = useState<any>([]);
  const [datalist, setDatalist] = useState<any[]>([]);
  const [modalParams, setModalParams] = useReducer((a, b) => ({ ...a, ...b }), {
    visible: false
  });
  const [staticId, setStaticId] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    init();
    resetMaterial();
  }, [spaceId]);

  useEffect(() => {
    dispatch({
      refresh: init
    });
  }, [spaceId, staticId]);

  useEffect(() => {
    getDataList();
  }, [alllist]);

  const init = () => {
    getMenuList();
    getItemList(STATIC[staticId], staticId === 3 ? staticId : undefined).then((res) => {
      setAlllist(res);
    });
    !window.appConfig.LOCAL && getStorageData();
  };

  const getMenuList = () => {
    getGroupList().then((data) => {
      setGroups(data);
    });
  };

  const getStorageData = () => {
    getStorage().then((res) => {
      setStorage(res);
    });
  };

  const getDataList = (newGroupId = groupId) => {
    const [id, type, group] = newGroupId;
    let list = [];
    if (id === 0) {
      // 全部
      list = alllist;
    } else if (id === -1) {
      // 未分组
      list = alllist?.filter((o) => !o[F.GROUP_ID]);
    } else {
      list = alllist?.filter((o) => o[F.GROUP_ID] === id);
    }
    setDatalist(list);
  };

  const onMenuChange = (id) => {
    const [a, type, group] = id;
    if (staticId !== group) {
      setLoading(true);
      setAlllist([]);
      setStaticId(group);
      getItemList(STATIC[group], group === 3 ? group : undefined).then((res) => {
        setAlllist(res);
        setLoading(false);
      });
      dispatch({ type: id.slice(-1)[0] });
    }
    setGroupId(id);
    getDataList(id);
  };

  const openUpload = () => {
    setModalParams({ visible: true });
  };

  const handleDragStart = (id, type, groupId) => {
    dispatch({
      draggingType: type,
      draggingId: id,
      draggingGroupId: groupId
    });
  };

  const handleDragEnd = () => {
    dispatch({
      draggingType: null,
      draggingId: null
    });
  };

  const handleUpload = () => {
    init();
    setModalParams({ visible: false });
  };

  const menulist = useMemo(() => {
    // TODO 后续重写
    const list: any = {
      0: [],
      1: [],
      2: [],
      3: []
    };
    groups.forEach((o) => {
      const item = { ...o };
      list[item.type].push(item);
    });
    const newList = Object.keys(list || {}).reduce(
      (pre, cur) => ({
        ...pre,
        [cur]: [...orderBy(list[cur].slice(0, list[cur].length - 1), 'updatedAt', 'desc'), ...list[cur].slice(-1)]
      }),
      {}
    );
    return newList;
  }, [groups]);

  return (
    <SourceContext.Provider value={sourceStore}>
      <div className={styles.resource}>
        <div className={styles.sider}>
          <GroupMenu groupId={groupId} onChange={onMenuChange} menulist={menulist} storage={storage} />
        </div>
        <div className={styles.content}>
          <Template
            groupId={groupId[0]}
            data={datalist}
            type={sourceStore.type}
            onUpload={openUpload}
            onDragStart={handleDragStart}
            onDragEnd={handleDragEnd}
            loading={loading}
            storage={storage}
          />
        </div>
        <UploadModal
          onOK={handleUpload}
          onCancel={() => setModalParams({ visible: false })}
          visible={modalParams.visible}
          groupId={groupId}
          menulist={menulist[sourceStore.type]}
          categoryType={sourceStore.type}
        />
      </div>
    </SourceContext.Provider>
  );
};

const mapStateToProps = ({ space }) => {
  return {
    spaceId: space.current
  };
};

export default connect(mapStateToProps, {
  resetMaterial
})(Resource);
