import React, { Fragment, useEffect, useState, useCallback, useMemo } from 'react';
import { connect } from 'react-redux';
import { Input, ConfigProvider } from '@easyv/react-gui';
import Thumb from 'components/Thumb';
import Title from 'components/Title';
import DeleteConfirmModal from 'components/DeleteConfirmModal';
import CategoryEdit from './CategoryEdit';
import EditContainer from './EditContainer';
import ModuleSort from './ModuleSort';
import ExportContainer from './ExportContainer';
import ImportContainer from './ImportContainer';
import defaultThumb from 'images/favorite_default.jpg';
import { getModules, deleteModules, publishModules } from 'models/module';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvButton from 'components/EasyvButton';
import EasyvTable from 'components/EasyvTable';
import styles from '../style.less';
import { Space } from '@easyv/antd';
import {getAssetsUrl} from 'utils/utils';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';

const { Search } = Input;

function ModulePanel({ loading, list, categorys, getModules, deleteModules, publishModules, deadline }) {
  const [selected, setSelected] = useState([]);
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState<{ published?: any }>({});
  const [sorter, setSorter] = useState<{ order?: any }>({});

  useEffect(() => {
    getModules();
  }, []);

  const handleSelect = (keys) => {
    setSelected(keys);
  };

  const handleExportComplete = useCallback(() => {
    setSelected([]);
  }, []);

  const handleSearch = useCallback((e) => {
    setSearch(e.target.value);
  }, []);

  const handleTableChange = useCallback((_pagination, filters, sorter) => {
    setFilters(filters);
    setSorter(sorter);
  }, []);

  const { published = [] } = filters;
  const { order } = sorter;
  let filteredList = list.filter((d) => d.name.includes(search));
  if (published && published.length) {
    filteredList = filteredList.filter((d) => published.includes(d.published.toString()));
  }

  if (order) {
    filteredList.sort((a, b) =>
      order === 'descend' ? +new Date(b.updatedAt) - +new Date(a.updatedAt) : +new Date(a.updatedAt) - +new Date(b.updatedAt)
    );
  }

  const columns = useMemo(
    () => [
      {
        title: '组件名称',
        dataIndex: 'name',
        width: '15%'
      },
      {
        title: '缩略图',
        dataIndex: 'thumb',
        width: '15%',
        render: (text) => <Thumb src={text ? getAssetsUrl(`${text}`) : defaultThumb} style={{ width: 68, height: 44 }} />
      },
      {
        title: '分类',
        dataIndex: 'categoryId',
        width: '12%',
        render: (text) => {
          const category = categorys.find((d) => d.id === text);
          return category ? category.name : '未知分类';
        }
      },
      {
        title: '状态',
        dataIndex: 'published',
        width: '12%',
        filters: [
          { text: '已发布', value: true },
          { text: '未发布', value: false }
        ],
        render: (text) => (
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <i
              style={{
                width: 8,
                height: 8,
                borderRadius: '50%',
                marginRight: 8,
                background: text ? '#00A755' : '#BFBFBF'
              }}
            />
            {text ? '已发布' : '未发布'}
          </span>
        )
      },
      {
        title: '编辑时间',
        dataIndex: 'updatedAt',
        width: '20%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        dataIndex: 'options',
        render: (_text, record: any) => (
          <Space>
            <EditContainer price={record.price} needPaid={record.needPaid} id={record.id} name={record.name} thumb={record.thumb} category={record.category} published={record.published} />
            <ExportContainer list={[record.id]}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportContainer>
            {record.published ? (
              <EasyvTooltip title="下架">
                <i
                  onClick={() => publishModules({ ids: [record.id], publish: false })}
                  className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)}
                />
              </EasyvTooltip>
            ) : (
              <EasyvTooltip title="发布">
                <i
                  onClick={() => publishModules({ ids: [record.id], publish: true })}
                  className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
                />
              </EasyvTooltip>
            )}
            <DeleteConfirmModal title="删除组件" onOk={() => deleteModules([record.id])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ],
    [categorys, defaultThumb]
  );

  return (
    <Fragment>
      <Title title="素材库" />
      <PanelHeaderContainer>
        <div>
          <ConfigProvider>
            <Search className={styles.searchInput} onChange={handleSearch} placeholder="搜索组件名称" value={search} />
          </ConfigProvider>
          <EasyvButton
            style={{ marginLeft: 16 }}
            disabled={!selected.length}
            onClick={() => publishModules({ ids: selected, publish: false })}>
            批量下架
          </EasyvButton>
          <EasyvButton
            style={{ marginLeft: 12 }}
            disabled={!selected.length}
            onClick={() => publishModules({ ids: selected, publish: true })}>
            批量上架
          </EasyvButton>
          <ExportContainer list={selected} onComplete={handleExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selected.length}>
              批量导出
            </EasyvButton>
          </ExportContainer>
          <DeleteConfirmModal title="删除组件" onOk={() => deleteModules(selected)}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selected.length}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <div>
          <CategoryEdit />
          <ModuleSort />
          <ImportContainer onComplete={getModules}>
            <EasyvButton theme="primary">导入</EasyvButton>
          </ImportContainer>
        </div>
      </PanelHeaderContainer>

      <EasyvTable
        loading={loading}
        selectedRowKeys={selected}
        onRowSelectChange={handleSelect}
        dataSource={filteredList}
        rowKey={(d: any) => d.id}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
        onChange={handleTableChange}
        columns={columns}
      />
    </Fragment>
  );
}

const mapStateToProps = ({ modules, transfer }) => {
  return {
    loading: modules.loading,
    list: modules.list,
    categorys: modules.categorys,
    deadline: transfer.deadline
  };
};

const mapDispatchToProps = {
  getModules,
  deleteModules,
  publishModules
};

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