import React, { useState } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { Layout } from '@easyv/antd';
import TemplateHeader from './components/TemplateHeader';
import TemplateList from './components/TemplateList';
import MarketTemplates from './components/MarketTemplates';
import Title from '../../components/Title';
import { addScreen } from 'models/screens';
import style from './index.less';
import message from 'components/message';

const SUPPORT_NONE = 0;
const SUPPORT_ALL = 1;

function ScreenCreate({ userId, userType, addScreen }) {
  const [loading, setLoading] = useState(false);
  const history = useHistory();

  const onCreateScreen = async (screenId) => {
    if (loading) {
      return;
    }
    const hide = message.loading('创建中...', 0);
    setLoading(true);
    const result = await addScreen(screenId);
    hide();
    result && message.success('创建成功');
    setLoading(false);
    hide();
    if (result) {
      history.push(`/create/${result.id}`);
    }
  };

  return (
    <Layout style={{ height: '100vh', cursor: loading ? 'no-drop' : 'auto' }}>
      <Title title="选择模板" />
      <TemplateHeader />
      <div className={style.container} style={{ pointerEvents: loading ? 'none' : 'auto' }}>
        <div className={style.body}>
          {window.appConfig.LOCAL ? (
            <TemplateList userId={userId} onClick={onCreateScreen} />
          ) : (
            <MarketTemplates userId={userId} userType={userType} onClick={onCreateScreen} />
          )}
        </div>
      </div>
    </Layout>
  );
}

function mapStateToProps({ templates, user }) {
  const { edition = {} } = user.userInfo;
  const { supportTemplate = 1, templateIds = [] } = edition;

  let templateList = templates.list.filter((d) => d.published);
  if (!window.appConfig.LOCAL) {
    templateList =
      supportTemplate === SUPPORT_NONE
        ? templateList.map((d) => ({ ...d, lock: true }))
        : supportTemplate === SUPPORT_ALL
        ? templateList
        : templateList.map((d) => ({ ...d, lock: !templateIds.includes(d.id) }));
  }

  return {
    categorys: [{ id: 0, name: '全部' }].concat(templates.categorys),
    userId: user.userInfo.userId,
    userType: user.userInfo.edition && user.userInfo.edition.id,
    templates: templateList
  };
}

const mapDispatchToProps = {
  addScreen
};

export default connect(mapStateToProps, mapDispatchToProps)(ScreenCreate);
