import React, { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector, connect } from 'react-redux';
import { getMyTemplates, getRecommendTemplates, addToMyTemplate } from 'models/template';

import OftenTemplates, { oftenTemplates } from './OftenTemplates';
import TemplateItem from './TemplateItem';
import { PreviewModal } from './PreviewModal';
import { updateVersion } from 'models/updateVersion';
import styles from './TemplateList.less';
import { Select } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';
import EasyvButton from 'components/EasyvButton';
import { getGroupList } from 'containers/resource/api';
import { RootState } from 'models';
import { useAuth } from 'components/easyUse';

interface SearchTypeInterface {
  id: number | string; //分组ID ,服务端只会传number、这里为了兼容前端拼接全部分组和未分组
  name: string; //分组名
  rank?: number;
  spaceId?: number;
  type?: 0 | 1 | 2; //0是资源中心的模板库分组记录、1是素材库设计素材分组记录、2是素材库主题资源分组记录
}

const { Search } = Input;
const { Option } = Select;

function MarketTemplates({ userId, userType, onClick, updateVersion }) {
  const [previewType, setPreviewType] = useState<number | null>(null);
  const [previewIndex, setPreviewIndex] = useState(null);
  const [searchType, setSearchType] = useState<'全部' | '未分组' | number>('全部');
  const [searchOption, setSearchOption] = useState<SearchTypeInterface[]>([
    { id: '全部分组', name: '全部分组' },
    { id: '未分组', name: '未分组' },
  ]);
  const [searchText, setSearchText] = useState<string>('');
  const { checkAuth } = useAuth();

  const dispatch = useDispatch();
  const { myTemplates = [], recommendTemplates = [] } = useSelector((state: RootState) => ({
    myTemplates: state.templates.myTemplates,
    recommendTemplates: state.templates.recommendTemplates,
  }));

  useEffect(() => {
    dispatch(getMyTemplates());
    dispatch(getRecommendTemplates());

    getGroupList().then((data) => {
      if (data && data.length) {
        setSearchOption(
          [
            { id: '全部', name: '全部' },
            { id: '未分组', name: '未分组' },
          ].concat(...data.filter((item) => item.type === 0 && item.id)),
        );
      }
    });
  }, []);

  const handleCreate = async (templateId) => {
    if (templateId) {
      let template = myTemplates.find((d) => d.id === templateId);
      if (template) {
        // TODO: 版本修改
        if (template.measureType === 3 && !checkAuth('useVipTemplate')) {
          updateVersion({ show: true, targetVersion: 'saas_vip' });
          return;
        } else if (template.measureType === 2 && !checkAuth('useAdvancedTemplate')) {
          updateVersion({ show: true, targetVersion: 'saas_advanced' });
          return;
        }
      } else {
        template = recommendTemplates.find((d) => d.id === templateId);
        // TODO: 版本修改
        if (template.measureType === 3 && !checkAuth('useVipTemplate')) {
          updateVersion({ show: true, targetVersion: 'saas_vip' });
          return;
        } else if (template.measureType === 2 && !checkAuth('useAdvancedTemplate')) {
          updateVersion({ show: true, targetVersion: 'saas_advanced' });
          return;
        } else {
          await dispatch(addToMyTemplate(templateId));
        }
      }

      oftenTemplates.add(userId, templateId);
    }
    onClick(templateId);
  };

  const filterTemplate = (filterParam: '全部' | '未分组' | number) => {
    if (filterParam === '全部') {
      return myTemplates;
    }
    if (filterParam === '未分组') {
      return myTemplates.filter((item) => item.groupId === null);
    }
    return myTemplates.filter((item) => item.groupId === filterParam);
  };

  const renderTemplate = useCallback(() => {
    const data = filterTemplate(searchType);

    return data
      .filter((d) => d.name.toLowerCase().includes(searchText?.toLowerCase()))
      .map((item) => {
        return (
          <TemplateItem
            key={item.id}
            thumb={item.thumb}
            name={item.name}
            info={item.info}
            type={item.measureType}
            category={item.category}
            purchased={item.purchased}
            onCreate={() => handleCreate(item.id)}
            onPreview={() => {
              setPreviewType(1);
              setPreviewIndex(myTemplates.findIndex((p) => p.id === item.id));
            }}
          />
        );
      });
  }, [searchType, searchText, myTemplates]);

  const renderSearchText = useCallback(() => {
    const data = filterTemplate(searchType);
    const filterCallback = (d) => {
      return d && d.name.toLowerCase().includes(searchText?.toLowerCase());
    };
    const length = data.filter((d) => filterCallback(d)).length;
    return (
      <>
        <span style={{ marginLeft: '11px' }}>搜索</span>
        <a
          style={{
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            maxWidth: '300px',
            display: 'inline-block',
          }}>{`"${searchText}"`}</a>
        <span>
          {length}
          个结果
        </span>
      </>
    );
  }, [searchType, searchText, myTemplates]);

  return (
    <ConfigProvider>
      <div className={styles.container}>
        <OftenTemplates userId={userId} list={myTemplates} onClick={handleCreate} />
        {myTemplates.length > 0 && (
          <>
            <div className={styles.title}>
              <div className={styles.sort_wrapper} id="sort_wrapper">
                <span>我的模板</span>
                {searchText ? (
                  renderSearchText()
                ) : (
                  <Select
                    dropdownClassName={styles.dropClass}
                    className={styles.option}
                    getPopupContainer={() => document.getElementById('sort_wrapper')}
                    onChange={(e) => {
                      setSearchType(e);
                    }}
                    defaultValue={searchType}
                    value={searchType}
                    style={{ display: 'inline-block' }}
                    bordered={false}>
                    {searchOption.map((item) => (
                      <Option label={item.name} key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </div>
              <div>
                <Search
                  onBlur={(e) => setSearchText(e.target.value)}
                  onSearch={(e) => setSearchText(e)}
                  className={styles.search_input}
                  placeholder="搜索"
                  style={{ width: 226 }}
                />
                <EasyvButton
                  onClick={() => (window.location.href = BASENAME + '/resource')}
                  style={{ marginLeft: 16 }}
                  theme="default">
                  模板管理
                </EasyvButton>
              </div>
            </div>
            <div className={styles.group}>{renderTemplate()}</div>
          </>
        )}

        {recommendTemplates.length > 0 && (
          <>
            <div className={styles.title}>
              <span>推荐模板</span>
            </div>
            <div className={styles.group}>
              {recommendTemplates.map((item) => {
                return (
                  <TemplateItem
                    key={item.id}
                    thumb={item.thumb}
                    name={item.name}
                    info={item.info}
                    category={item.category}
                    type={item.measureType}
                    purchased={item.purchased}
                    onCreate={() => handleCreate(item.id)}
                    onPreview={() => {
                      setPreviewType(2);
                      setPreviewIndex(recommendTemplates.findIndex((p) => p.id === item.id));
                    }}
                  />
                );
              })}
            </div>
          </>
        )}

        {previewType !== null && previewIndex !== null && (
          <PreviewModal
            list={previewType === 1 ? myTemplates : recommendTemplates}
            current={previewIndex}
            visible
            onClick={handleCreate}
            onClose={() => {
              setPreviewType(null);
              setPreviewIndex(null);
            }}
          />
        )}
      </div>
    </ConfigProvider>
  );
}
const mapDispatchToProps = {
  updateVersion,
};

export default connect(null, mapDispatchToProps)(MarketTemplates);
