// 素材库
import React, { useEffect, memo, useState, useCallback, useMemo } from 'react';
import styles from './index.less';
import classnames from 'classnames';
import { connect } from 'react-redux';
import { getMaterialCenter, getUserCategory, setCurrent, createResourceCount, ResourceTs } from 'models/material-lib';
import { Image, Popover } from '@easyv/antd';
import { addImageComponent, addVideoComponent } from 'models/component';
import { addFavorite } from 'models/favorite';
import VideoComponent from '../../MaterialModal/video';
import defaultThumb from 'images/sourceImg.png';
import emptySimple from 'images/empty-img-simple.png';
import MyFavorite from './MyFavorite';
import Loading from './Loading';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import NoData from './NoData';
import {getAssetsUrl} from 'utils/utils';

function _transformFormat(data: ResourceTs, key = 'platformCategory') {
  const { category, list } = data;
  return [
    ...category
      .filter((d) => !!d.parentId)
      .map((d) => {
        return {
          ...d,
          list: list.filter((x) => x[key].id === d.id)
        };
      })
  ];
}

function MaterialLib({
  getMaterialCenter,
  theFirstColumn,
  designMaterial,
  myFavorite,
  themeResource,
  addImageComponent,
  addVideoComponent,
  createResourceCount,
  setCurrent,
  loading,
  item,
  addFavorite,
  getUserCategory
}: {
  theFirstColumn: any[];
  constantsList: any[];
  loading: boolean;
  item: any;
  designMaterial: ResourceTs;
  themeResource: ResourceTs;
  myFavorite: {
    designMaterial: ResourceTs;
    themeResource: ResourceTs;
  };
  getUserCategory: () => void;
  getMaterialCenter: (x?: number) => void;
  createResourceCount: (x: number, source?: 'platform' | 'official') => void;
  addImageComponent: (param: { name: string; url: string }) => Promise<any>;
  addVideoComponent: (param: { name: string; url: string }) => Promise<any>;
  addFavorite: (x: number, source?: 'platform' | 'official') => void;
  setCurrent: (x: number[]) => void;
}) {
  const [centerId, setCenterId] = useState(0);
  const [resource, setResource] = useState<any[]>([]);
  const [localAddress, setLocalAddress] = useState<any[]>([]);
  const [isOpen, setIsOpen] = useState<{ open: 1 | 2 }[]>([]);

  useEffect(() => {
    onClassify(item.id, 0);
  }, [item]);

  useEffect(() => {
    const activeItem = theFirstColumn.find((d) => d.id === item.id);
    if (activeItem) {
      const { type } = activeItem;
      let list: any[] = [];

      switch (type) {
        case 'designMaterial':
          list = autoSetCurrent(designMaterial);
          break;
        case 'myFavorite':
          list = autoSetCurrent(myFavorite, 'collect');
          break;
        case 'themeResource':
        default:
          list = autoSetCurrent(themeResource);
          break;
      }
      setResource(list);
    }
  }, [themeResource, designMaterial, item, myFavorite]);

  const autoSetCurrent = (data: any, code?: string): any => {
    if (code === 'collect') {
      setCenterId(1);
      const { designMaterial, themeResource } = data;
      setLocalAddress([
        {
          name: '设计素材',
          type: 1,
          id: 1,
          data: designMaterial
        },
        {
          name: '主题资源',
          type: 2,
          id: 2,
          data: themeResource
        }
      ]);
    } else {
      const _localAddress = data.category?.filter((d) => !d.parentId);
      _localAddress && setLocalAddress(_localAddress.sort((a, b) => b.id - a.id));
      if (_localAddress && _localAddress.length) {
        setCenterId(_localAddress[0].id);
      }
      return _transformFormat({
        ...data,
        category: data.category.filter((d) => d.parentId)
      });
    }
  };

  const onClassify = async (d, i) => {
    setCenterId(d);
    if (!i) {
      setLocalAddress([]);
      setResource([]);
      setCurrent(d);
      if (d === 3) {
        await getUserCategory();
      } else {
        await getMaterialCenter(d);
      }
    }
  };
  const firstId = item.id;

  const addComponents = async (item, source?: 'platform' | 'official') => {
    if ([1, 3].includes(firstId) && item) {
      // 静态资源
      // type => 1图片 2视频
      const param = { name: item.name, url: item.content };
      const result = item.type === 1 ? await addImageComponent(param) : item.type === 2 ? await addVideoComponent(param) : null;

      if (result) {
        createResourceCount(item.id, source);
      }
    }
  };

  const onCreateComponents = useCallback(
    (d, source?: 'platform' | 'official') => {
      const code = [1, 2].includes(firstId) ? firstId : [3].includes(firstId) ? centerId : null;
      if (code === 2) {
        // 成组
        addFavorite(d.id, source);
      } else if (code === 1) {
        // 静态资源
        addComponents(d, source);
      }
    },
    [firstId, centerId]
  );

  const filterResource = useMemo(() => {
    return item.id !== 3 ? resource.filter((d) => d.parentId === centerId) : [];
  }, [item, resource, centerId]);

  const resourceData = localAddress.find((d) => d.id === centerId);

  useEffect(() => {
    const temp: { open: 1 | 2 }[] = [];
    filterResource.map((item) => {
      temp.push({
        open: 1
      });
    });
    setIsOpen(temp);
  }, [filterResource]);

  const openOrClose = (index) => {
    isOpen.map((item, i) => {
      const list = [...isOpen];
      if (i === index) {
        if (isOpen[i].open === 1) {
          setIsOpen(list.map((item, idx) => (idx === i ? { ...item, open: 2 } : item)));
        } else if (isOpen[i].open === 2) {
          setIsOpen(list.map((item, idx) => (idx === i ? { ...item, open: 1 } : item)));
        }
      }
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.itemTab}>
        <span>{item.name}</span>
      </div>

      <ul className={styles.list} style={{ padding: 0, width: 'auto' }}>
        <div className={styles.classifyBox}>
          {localAddress.length ? (
            <div className={styles.subclassification}>
              {localAddress.map((d) => {
                return (
                  <div
                    key={d.id}
                    onMouseOver={() => {
                      onClassify(d.id, 1);
                    }}
                    className={classnames(styles.subItem, d.id === centerId ? styles.subActive : null)}>
                    <span title={d.name}>{d.name}</span>
                  </div>
                );
              })}
            </div>
          ) : null}

          <div className={styles.classifiedContent}>
            <div className={styles.receptacle}>
              {loading ? (
                <Loading />
              ) : item.id === 3 && resourceData ? (
                <MyFavorite resource={resourceData} onCreateComponents={(d) => onCreateComponents(d, 'official')} />
              ) : filterResource.length ? (
                filterResource.map((v, index) => {
                  return (
                    <div key={v.id} className={styles.contentItem}>
                      <div className={styles.title}>{v.name}</div>
                      <div
                        className={styles.containerList}
                        style={
                          isOpen[index]?.open === 2
                            ? { maxHeight: 'unset', overflowY: 'unset' }
                            : { maxHeight: '180px', overflowY: 'hidden' }
                        }>
                        {v.list?.length ? (
                          v.list.map((d) => {
                            return (
                              <div
                                key={d.id}
                                onClick={() => {
                                  onCreateComponents(d, 'platform');
                                }}
                                className={classnames(styles.containerItem, styles[`edition_${d.edition}`])}>
                                <div className={styles.cover}>
                                  {d.type === 2 ? (
                                    <VideoComponent url={getAssetsUrl(d.thumb)} isSelect={true} title={d.name} />
                                  ) : (
                                    <Popover
                                      content={
                                        <div className={styles.content}>
                                          <Image
                                            preview={false}
                                            fallback={defaultThumb}
                                            id={d.id}
                                            src={d.thumb ? getAssetsUrl(d.thumb) : defaultThumb}
                                          />
                                        </div>
                                      }
                                      mouseEnterDelay={2}
                                      placement="top"
                                      title={d.name}
                                      trigger="hover"
                                      overlayClassName={styles.preview}>
                                      <Image
                                        preview={false}
                                        fallback={defaultThumb}
                                        id={d.id}
                                        src={d.thumb ? getAssetsUrl(d.thumb) : defaultThumb}
                                      />
                                    </Popover>
                                  )}
                                </div>
                                <span>{d.name}</span>
                              </div>
                            );
                          })
                        ) : (
                          <NoData />
                        )}
                      </div>
                      {v.list?.length > 6 && (
                        <div
                          className={styles.open}
                          onClick={() => {
                            openOrClose(index);
                          }}>
                          {isOpen[index]?.open === 2 ? (
                            <span>
                              收起
                              <UpOutlined />
                            </span>
                          ) : (
                            <span>
                              展开
                              <DownOutlined />
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })
              ) : (
                <DefaultGraph title="素材库为空" />
              )}
            </div>
          </div>
        </div>
      </ul>
    </div>
  );
}
function mapStateToProps({ materialLib, constants }) {
  const { list: constantsList } = constants;
  const { theFirstColumn, loading, designMaterial, themeResource, myFavorite } = materialLib;
  return {
    theFirstColumn,
    constantsList,
    loading,
    designMaterial,
    themeResource,
    myFavorite
  };
}

export default connect(mapStateToProps, {
  getMaterialCenter,
  getUserCategory,
  addImageComponent,
  addVideoComponent,
  addFavorite,
  setCurrent,
  createResourceCount
})(memo(MaterialLib));

export function DefaultGraph({ title = '暂无数据' }: { title?: string }) {
  return (
    <div className={styles.emptySimple}>
      <img src={emptySimple} />
      <span>{title}</span>
    </div>
  );
}
