/* eslint-disable react-hooks/exhaustive-deps */
import React, { Fragment, useState, useEffect, useCallback, useMemo } from 'react';
import { connect } from 'react-redux';
import { TreeSelect } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';
import Thumb from 'components/Thumb';
import Title from 'components/Title';
import EditContainer from './EditContainer';
import ExportContainer from './ExportContainer';
import ImportContainer from './ImportContainer';
import DeleteConfirmModal from 'components/DeleteConfirmModal';
import { getConstants } from 'models/constant';
import { getThemes, publishThemes, deleteThemes, sortThemes } 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 {getAssetsUrl} from 'utils/utils';

const { Search } = Input;
const { TreeNode } = TreeSelect;
const categorys = ['常规图表', '文字', '辅助图形', '指标', '地图', '交互', '其他', '定制组件'];
const chartTypes = ['柱形图', '折线图', '饼图', '散点图', '其他图'];

interface IProps {
  loading?: boolean;
  themes: any;
  constants: any;
  getThemes: () => void;
  getConstants: () => void;
  publishThemes: (param) => void;
  deleteThemes: (param) => void;
  sortThemes: (param) => void;
  deadline: Date | string;
}

function ThemePanel({
  loading = false,
  themes = [],
  constants = [],
  getThemes,
  getConstants,
  publishThemes,
  deleteThemes,
  sortThemes,
  deadline
}: IProps) {
  const [selected, setSelected] = useState([]);
  const [search, setSearch] = useState('');
  const [components, setComponents] = useState<any[]>([]);
  const [filters, setFilters] = useState<{ published?: boolean[] }>({});
  const [sorter, setSorter] = useState<{ order?: any }>({});

  useEffect(() => {
    getConstants();
    getThemes();
  }, []);

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

  const handleConstantsFilter = useCallback((value) => {
    setComponents(value);
  }, []);

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

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

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

  const { published = [] } = filters;
  const { order } = sorter;
  const len = selected.length;
  const resultConstants = components.length
    ? constants.filter((d: any) => components.includes(d.category) || components.includes(d.type) || components.includes(d.moduleName))
    : constants;
  let resultThemes = themes.filter(
    (d) => d.from === d.moduleName && d.name.includes(search) && resultConstants.find((v) => v.moduleName === d.from)
  );
  if (published && published.length) {
    resultThemes = resultThemes.filter((d) => published.includes(d.published));
  }

  if (order) {
    resultThemes.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: '16%',
        render: (text, record: any) =>
          record.isDefault ? (
            <span>
              {text} <i className="icon iconfont icon-icon_default" style={{ color: '#00A755' }} />
            </span>
          ) : (
            text
          )
      },
      {
        title: '缩略图',
        dataIndex: 'thumb',
        width: '12%',
        render: (text) => <Thumb src={text ? getAssetsUrl(`${text}`) : undefined} style={{ width: 68, height: 44 }} />
      },
      {
        title: '所属组件',
        dataIndex: 'from',
        width: '12%',
        render: (text, record: any) => (
          <span>
            {constants.find((d) => d.moduleName === text).name}
            {record.moduleName !== record.from ? `(${record.moduleName})` : ''}
          </span>
        )
      },
      {
        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 id={record.id} name={record.name} thumb={record.thumb} published={record.published} isDefault={record.isDefault}>
              <EasyvTooltip title="编辑">
                <i className={classNames('icon iconfont icon-custom ' + styles.iconHover)} />
              </EasyvTooltip>
            </EditContainer>
            <ExportContainer list={[record.id]}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportContainer>
            {record.published ? (
              <EasyvTooltip title="下架">
                <i
                  onClick={() => publishThemes({ ids: [record.id], publish: false })}
                  className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)}
                />
              </EasyvTooltip>
            ) : (
              <EasyvTooltip title="发布">
                <i
                  onClick={() => publishThemes({ ids: [record.id], publish: true })}
                  className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
                />
              </EasyvTooltip>
            )}
            <DeleteConfirmModal title="删除主题" onOk={() => deleteThemes([record.id])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ],
    [constants]
  );

  return (
    <Fragment>
      <Title title="主题管理" />
      <PanelHeaderContainer>
        <div className={style.selectTree} style={{ display: 'flex', alignItems: 'center' }}>
          <TreeSelect
            showSearch
            allowClear
            treeCheckable={true}
            showCheckedStrategy={TreeSelect.SHOW_PARENT}
            value={components}
            placeholder="选定组件范围"
            style={{ width: 200, marginRight: 16 }}
            onChange={handleConstantsFilter}
            treeNodeFilterProp="title"
            dropdownStyle={{ maxHeight: 500, overflowY: 'auto', background: '#3D404C' }}
            dropdownClassName={style.themeSelect}>
            {categorys.map((d) => {
              const children = constants.filter((v) => v.category === d);
              if (d === '常规图表') {
                return (
                  <TreeNode value={d} title={d} key={d}>
                    {chartTypes.map((v) => {
                      const secondChildren = children.filter((o) => (v === '其他图' ? o.type === '其他' : o.type === v));
                      return (
                        <TreeNode value={v} title={v} key={v}>
                          {secondChildren.map((o: any) => {
                            return <TreeNode value={o.moduleName} title={o.name} key={o.moduleName} />;
                          })}
                        </TreeNode>
                      );
                    })}
                  </TreeNode>
                );
              } else {
                return (
                  <TreeNode value={d} title={d} key={d}>
                    {children.map((v: any) => {
                      return <TreeNode value={v.moduleName} title={v.name} key={v.moduleName} />;
                    })}
                  </TreeNode>
                );
              }
            })}
          </TreeSelect>
          <ConfigProvider>
            <Search className={styles.searchInput} onChange={handleSearch} placeholder="搜索主题名称" value={search} />
          </ConfigProvider>
          <EasyvButton style={{ marginLeft: 16 }} disabled={!len} onClick={() => publishThemes({ ids: selected, publish: false })}>
            批量下架
          </EasyvButton>
          <EasyvButton style={{ marginLeft: 12 }} disabled={!len} onClick={() => publishThemes({ ids: selected, publish: true })}>
            批量上架
          </EasyvButton>
          <ExportContainer list={selected} onComplete={handleExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!len}>
              批量导出
            </EasyvButton>
          </ExportContainer>
          <DeleteConfirmModal title="删除主题" onOk={() => deleteThemes(selected)}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!len}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <Space size={8}>
          <SortModal data={themes} constants={constants} onComplete={sortThemes}>
            <EasyvButton style={{ marginRight: 4 }}>主题排序</EasyvButton>
          </SortModal>
          <ImportContainer onComplete={getThemes}>
            <EasyvButton theme="primary">导入</EasyvButton>
          </ImportContainer>
        </Space>
      </PanelHeaderContainer>
      <EasyvTable
        loading={loading}
        selectedRowKeys={selected}
        onRowSelectChange={handleSelect}
        dataSource={resultThemes}
        rowKey={(d: any) => d.id}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
        onChange={handleTableChange}
        columns={columns}
      />
    </Fragment>
  );
}

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

const mapDispatchToProps = {
  getThemes,
  getConstants,
  publishThemes,
  deleteThemes,
  sortThemes
};

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