import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { connect } from 'react-redux';
import { Input, ConfigProvider } from '@easyv/react-gui';
import Title from 'components/Title';
import EditContainer from './EditContainer';
import ExportContainer from './ExportContainer';
import ImportContainer from './ImportContainer';
import DeleteConfirmModal from 'components/DeleteConfirmModal';
import { publishThemesPack, deleteThemesPack, sortThemesPack, getThemesConfig } from 'models/theme';
import Space from 'components/Space';
import SortModal from './SortModal';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvButton from 'components/EasyvButton';
import EasyvTable from 'components/EasyvTable';
import styles from '../style.less';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';
import style from './index.less';
import { ThemeType, Type } from 'models/theme.types';

const { Search } = Input;

interface IProps {
  loading?: boolean;
  themeConfigList: ThemeType[];
  getThemesConfig: (param: Type) => void;
  publishThemesPack: (ids: number[], published: boolean) => void;
  deleteThemesPack: (param) => void;
  sortThemesPack: (param) => void;
  deadline: Date | string;
}

function ThemePanel({
  loading = false,
  themeConfigList,
  getThemesConfig,
  publishThemesPack,
  deleteThemesPack,
  sortThemesPack,
  deadline
}: IProps) {
  const [selected, setSelected] = useState([]);
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState<{ published?: boolean[] }>({});
  const [sorter, setSorter] = useState<{ order?: 'ascend' | 'descend' }>({ order: 'descend' });

  useEffect(() => {
    getThemesConfig(Type.SYSTEM);
  }, []);

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

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

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

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

  const { published = [] } = filters;
  const { order } = sorter;

  const len = selected.length;

  const resultThemeList = useMemo(() => {
    let _resultThemeList = themeConfigList;
    if (search) {
      _resultThemeList = _resultThemeList.filter((d) => d.name.includes(search));
    }
    if (published && published.length) {
      _resultThemeList = _resultThemeList.filter((d) => published.includes(d.published));
    }
    if (order) {
      _resultThemeList.sort((a, b) =>
        order === 'descend' ? +new Date(b.updatedAt) - +new Date(a.updatedAt) : +new Date(a.updatedAt) - +new Date(b.updatedAt)
      );
    }
    return _resultThemeList;
  }, [themeConfigList, order, published, search]);

  const columns = () => [
    {
      title: '主题包名称',
      dataIndex: 'name',
      width: '20%',
      render: (text, record: any) =>
        record.isDefault ? (
          <span>
            {text} <i className="icon iconfont icon-icon_default" style={{ color: '#00A755' }} />
          </span>
        ) : (
          text
        )
    },
    {
      title: '状态',
      dataIndex: 'published',
      width: '16%',
      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: '38%',
      sorter: true,
      showSorterTooltip: false,
      render: (text) => new Date(new Date(text).getTime() + 28800000).toLocaleString()
    },
    {
      title: '操作',
      dataIndex: 'options',
      render: (_text, record: ThemeType) => (
        <Space>
          <EditContainer model="edit" type={record.type} curEditThemeConfig={record}>
            <EasyvTooltip title="编辑">
              <i className={classNames('icon iconfont icon-custom ' + styles.iconHover)} />
            </EasyvTooltip>
          </EditContainer>
          <ExportContainer list={resultThemeList} ids={[record.id]}>
            <EasyvTooltip title="导出">
              <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
            </EasyvTooltip>
          </ExportContainer>
          {record.published ? (
            <EasyvTooltip title="下架">
              <i
                onClick={() => publishThemesPack([record.id], false)}
                className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)}
              />
            </EasyvTooltip>
          ) : (
            <EasyvTooltip title="发布">
              <i
                onClick={() => publishThemesPack([record.id], true)}
                className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
              />
            </EasyvTooltip>
          )}
          <DeleteConfirmModal title="删除主题包" onOk={() => deleteThemesPack([record.id])}>
            <EasyvTooltip title="删除">
              <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
            </EasyvTooltip>
          </DeleteConfirmModal>
        </Space>
      )
    }
  ];

  return (
    <ConfigProvider>
      <Title title="主题包管理" />
      <PanelHeaderContainer>
        <div className={style.selectTree} style={{ display: 'flex', alignItems: 'center' }}>
          <Search className={styles.searchInput} onChange={handleSearch} placeholder="搜索" value={search} />
          <EasyvButton style={{ marginLeft: 16 }} disabled={!len} onClick={() => publishThemesPack(selected, false)}>
            批量下架
          </EasyvButton>
          <EasyvButton style={{ marginLeft: 12 }} disabled={!len} onClick={() => publishThemesPack(selected, true)}>
            批量上架
          </EasyvButton>
          <ExportContainer list={resultThemeList} ids={selected} onComplete={handleExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!len}>
              批量导出
            </EasyvButton>
          </ExportContainer>
          <DeleteConfirmModal title="删除主题包" onOk={() => deleteThemesPack(selected)}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!len}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <Space size={8}>
          <SortModal data={resultThemeList} onComplete={sortThemesPack}>
            <EasyvButton style={{ marginRight: 4 }}>排序</EasyvButton>
          </SortModal>
          <EditContainer model="add" type={Type.SYSTEM}>
            <EasyvButton style={{ marginRight: 4 }}>新建</EasyvButton>
          </EditContainer>
          <ImportContainer onComplete={getThemesConfig}>
            <EasyvButton theme="primary">导入</EasyvButton>
          </ImportContainer>
        </Space>
      </PanelHeaderContainer>
      <EasyvTable
        loading={loading}
        selectedRowKeys={selected}
        onRowSelectChange={handleSelect}
        dataSource={resultThemeList}
        rowKey={(d: any) => d.id}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
        onChange={handleTableChange}
        columns={columns()}
      />
    </ConfigProvider>
  );
}

const mapStateToProps = ({ themes, transfer }) => {
  return {
    loading: themes.loading,
    deadline: transfer.deadline,
    themeConfigList: themes.themeConfigList || []
  };
};

const mapDispatchToProps = {
  publishThemesPack,
  deleteThemesPack,
  sortThemesPack,
  getThemesConfig
};

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