import React, { useState, useContext, useReducer } from 'react';
import message from 'components/message';
import TemplateItem from '../TemplateItem';
import Toolbar from '../Toolbar';
import { STATIC } from '../../constant';
import { deleteItems, renameItem, createScreen } from '../../api';
import { SourceContext } from '../../index';
import { Preview } from '../../components';
import './index.less';
import { useEffect } from 'react';
import orderBy from 'lodash/orderBy';
import TransferScroll from 'containers/TransferScroll';
import EasyvNoData from 'components/EasyvNoData';
import Loading from 'components/Loading';
import { updateVersion } from 'models/updateVersion';
import { useAuth } from 'components/easyUse';
import { useDispatch } from 'react-redux';

type Data = any[];
const reducer = (a, b) => ({ ...a, ...b });
export default function Template({
  groupId,
  prefixCls,
  type,
  data,
  onUpload,
  onDragStart,
  onDragEnd,
  loading,
  storage,
}: any) {
  const { refresh } = useContext(SourceContext);

  const [dataList, setDataList] = useState<Data>(data);
  const [selectedList, setSelectedList] = useState<Data>([]);
  const [current, setCurrent] = useState(1);
  const [edit, setEdit] = useState(false);
  const [searchKey, setSearchKey] = useState('');
  const [sortKey, setSortKey] = useState('updatedAt');
  const [previewList, setPreviewList] = useState<Data>([]);

  const dispatch = useDispatch();
  const { checkAuth } = useAuth();

  const [previewParams, setPreviewParams] = useReducer(reducer, {
    visible: false,
    createLoading: false,
    id: null,
  });

  useEffect(() => {
    if (searchKey) {
      setDataList(data?.filter((o) => o.name.includes(searchKey)));
    } else {
      setDataList(data);
    }
    setCurrent(1);
    cancelEdit();
  }, [data, searchKey]);

  const handleSelect = (checked, item) => {
    if (checked) {
      setSelectedList(selectedList.concat([item]));
    } else {
      setSelectedList(selectedList.filter((o) => o.id !== item.id));
    }
  };

  const cancelEdit = () => {
    setEdit(false);
    setSelectedList([]);
  };

  const handleDelete = (ids) => {
    const hide = message.loading('删除中...', 0);
    deleteItems(ids, STATIC[type]).then(() => {
      hide();
      message.success('删除成功');
      refresh();
    });
  };

  const handlePreview = (item) => {
    setPreviewList(selectedList.concat([item]));
    setPreviewParams({
      visible: true,
      id: item.id,
    });
  };

  const handleRename = (id, name) => {
    renameItem(STATIC[type], id, name)?.then(() => {
      refresh();
    });
  };

  const checkVersionScreen = (onSuccess, item) => {
    if (item.measureType === 3 && !checkAuth('useVipTemplate')) {
      dispatch(updateVersion({ show: true, targetVersion: 'saas_vip' }));
      return;
    } else if (item.measureType === 2 && !checkAuth('useAdvancedTemplate')) {
      dispatch(updateVersion({ show: true, targetVersion: 'saas_advanced' }));
      return;
    } else {
      onSuccess && onSuccess(item);
    }
  };

  const handleAddTemplate = (item) => {
    const create = () => {
      setPreviewParams({ createLoading: true });
      createTemplate(item).then(() => {
        setPreviewList([]);
        setPreviewParams({
          createLoading: false,
          id: null,
          visible: false,
        });
      });
    };
    checkVersionScreen(create, item);
  };

  const handleCreate = (item) => {
    checkVersionScreen(createTemplate, item);
  };

  const createTemplate = (item) => {
    return createScreen(item.id).then((res) => {
      if (res?.id) {
        const screenId = res.id;
        let url = `./create/${screenId}`;
        if (BASENAME) {
          url = `./${BASENAME}/create/${screenId}`;
        }
        window.open(url, '_blank');
      }
    });
  };

  const count = dataList.length;

  return (
    <div className={prefixCls}>
      <TransferScroll />
      <Toolbar
        groupId={groupId}
        count={count}
        selectedList={selectedList}
        selectedAll={selectedList.length === dataList.length}
        onSelectAll={(all) => setSelectedList(all ? dataList.filter((o) => !o.isDisable) : [])}
        edit={edit}
        onEdit={() => setEdit(true)}
        onCancel={cancelEdit}
        onSearch={setSearchKey}
        onUpload={onUpload}
        onDelete={handleDelete}
        onSort={setSortKey}
        type={type}
        refresh={refresh}
        storage={storage}
      />
      {count ? (
        <div className={`${prefixCls}-list`}>
          <div className={`${prefixCls}-list-grid`}>
            {orderBy(dataList, sortKey, 'desc').map((item) => (
              <TemplateItem
                edit={edit}
                item={item}
                key={item.id}
                selected={~selectedList.findIndex((o) => o.id === item.id)}
                onSelect={(checked) => handleSelect(checked, item)}
                onDelete={(id) => handleDelete([id])}
                onPreview={handlePreview}
                onCreate={handleCreate}
                type={type}
                onDragStart={onDragStart}
                onDragEnd={onDragEnd}
                onRename={handleRename}
              />
            ))}
          </div>
        </div>
      ) : (
        <EasyvNoData text="暂无可用素材" />
      )}
      {loading && <Loading />}
      {previewParams.visible && (
        <Preview
          onCancel={() => {
            setPreviewList([]);
            setPreviewParams({
              visible: false,
              id: null,
            });
          }}
          type={type}
          list={previewList}
          defaultId={previewParams.id}
          addTemplate={handleAddTemplate}
          createBtnLoading={previewParams.createLoading}
        />
      )}
    </div>
  );
}

Template.defaultProps = {
  prefixCls: 'source-template',
  data: [],
};
