import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { Input, ConfigProvider } from '@easyv/react-gui';
import message from 'components/message';
import NewTemplate from './NewTemplate';
import EditTemplate from './EditTemplate';
import DeleteConfirmModal from '../../../../components/DeleteConfirmModal';
import ExportTemplatesModal from './ExportTemplatesModal';
import ImportTemplatesModal from './ImportTemplatesModal';
import CategoryEdit from './CategoryEdit';
import TemplateSort from './TemplateSort';
import { Space } from '@easyv/antd';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';
import { getTemplates, sortTemplate, getCategorys, publish, deleteTemplates } from 'models/template';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvButton from 'components/EasyvButton';
import EasyvTable from 'components/EasyvTable';
import styles from '../style.less';

const { Search } = Input;
const THUMB_OSS_SUFFIX = '?x-oss-process=image/resize,m_pad,w_78,h_44,color_181b24';

interface IProps {
  templates: any[];
  categorys: any[];
  loading: boolean;
  deadline: Date | string;
  getCategorys: () => void;
  getTemplates: () => void;
  deleteTemplates: (params) => Promise<any>;
  templatePublish: (param) => Promise<any>;
}

// TODO 后续增加类型约束，暂时any
const TemplatePanel = (props: IProps) => {
  const { getTemplates, templatePublish, templates, categorys, loading, deadline } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [sorter, setSorter] = useState<any>({});
  const [filter, setFilter] = useState<any>({});
  const [keyword, setKeyword] = useState('');
  useEffect(() => {
    document.title = '模板管理';
    query();
    props.getCategorys();
  }, []);

  const query = () => {
    getTemplates?.();
  };

  const handleImageError = (e) => {
    const img = e.target;
    img.style.display = 'none';
  };

  const onSelect = (record, selected) => {
    if (selected) {
      setSelectedRowKeys([record.id].concat(selectedRowKeys));
    } else {
      setSelectedRowKeys(selectedRowKeys.filter((id) => id !== record.id));
    }
  };

  const getFilterList = () => {
    const filteredList = templates.filter((item) => {
      if (filter.category && !~filter.category.indexOf(item.categoryId + '')) return false;
      if (filter.published && !~filter.published.indexOf(item.published + '')) return false;
      if (keyword && !~item.name.toLowerCase().indexOf(keyword)) return false;
      return true;
    });

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

    return filteredList;
  };

  const onSelectAll = (selected) => {
    setSelectedRowKeys(selected ? getFilterList().map((item) => item.id) : []);
  };

  const handleSearch = (e) => {
    const value = e.target.value && e.target.value.trim();
    setKeyword(value);
  };

  const deleteTemplates = (ids) => {
    props?.deleteTemplates({ templates: ids }).then((res) => {
      if (res) {
        message.success('删除成功');
        query();
        setSelectedRowKeys([]);
      } else {
        message.error('删除失败');
      }
    });
  };

  const onExportComplete = () => {
    setSelectedRowKeys([]);
  };

  const onTableChange = (_pagination, filter, sorter) => {
    setSorter(sorter);
    setFilter(filter);
  };

  const batchPublish = (keys) => {
    templatePublish?.({ keys, isPublish: true }).then(() => {
      setSelectedRowKeys([]);
      query();
    });
  };

  const batchUnpublish = (keys) => {
    templatePublish?.({ keys, isPublish: false }).then(() => {
      setSelectedRowKeys([]);
      query();
    });
  };
  const rowSelection = {
    columnWidth: 60,
    selectedRowKeys,
    onSelect: onSelect,
    onSelectAll: onSelectAll
  };

  const filterList = getFilterList() || [];

  const columns = useMemo(
    () => [
      {
        title: '序号',
        width: 60,
        dataIndex: 'index',
        render: (_text, _record, index) => <span>{index + 1}</span>
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '封面图',
        width: 120,
        dataIndex: 'thumb',
        render: (text) => (
          <img
            style={{ maxHeight: '44px' }}
            src={`${text}${/fs/i.test(window.appConfig.UPLOAD_MODE) ? THUMB_OSS_SUFFIX : ''}`}
            onError={handleImageError}
          />
        )
      },
      {
        title: '比例/分辨率',
        dataIndex: 'info'
      },
      {
        title: '分类',
        width: 120,
        dataIndex: 'category',
        filters: categorys.map((item) => ({ text: item.name, value: item.id }))
      },
      {
        title: '状态',
        dataIndex: 'published',
        width: '8%',
        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: 'usedTime',
        width: 120,
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '编辑时间',
        dataIndex: 'updatedAt',
        width: 180,
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        dataIndex: 'options',
        render: (_text, record: any) => (
          <Space>
            <EditTemplate data={record} onComplete={query}>
              <EasyvTooltip title="编辑">
                <i className={classNames('icon iconfont icon-custom ' + styles.iconHover)} />
              </EasyvTooltip>
            </EditTemplate>
            <ExportTemplatesModal list={[{ id: record.id, name: record.name }]}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportTemplatesModal>
            {record.published ? (
              <EasyvTooltip title="下架">
                <i onClick={() => batchUnpublish([record.id])} className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)} />
              </EasyvTooltip>
            ) : (
              <EasyvTooltip title="发布">
                <i
                  onClick={() => batchPublish([record.id])}
                  className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
                />
              </EasyvTooltip>
            )}
            <DeleteConfirmModal title="删除模板" onOk={() => deleteTemplates([record.id])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ],
    [categorys]
  );

  return (
    <div>
      <PanelHeaderContainer>
        <div>
          <ConfigProvider>
            <Search
              className={styles.searchInput}
              onChange={handleSearch}
              placeholder="搜索模板名称"
              value={keyword}
              onSearch={() => {
                // setCurrent(1);
                query();
              }}
            />
          </ConfigProvider>
          <EasyvButton style={{ marginLeft: 16 }} disabled={!selectedRowKeys.length} onClick={() => batchPublish(selectedRowKeys)}>
            批量上架
          </EasyvButton>
          <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length} onClick={() => batchUnpublish(selectedRowKeys)}>
            批量下架
          </EasyvButton>
          <ExportTemplatesModal list={templates.filter((item: any) => ~selectedRowKeys.indexOf(item.id))} onComplete={onExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length}>
              批量导出
            </EasyvButton>
          </ExportTemplatesModal>
          <DeleteConfirmModal onOk={() => deleteTemplates(selectedRowKeys)}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <div>
          <CategoryEdit />
          <TemplateSort />
          <ImportTemplatesModal onComplete={query}>
            <EasyvButton style={{ marginRight: 12 }}>导入</EasyvButton>
          </ImportTemplatesModal>
          <NewTemplate categorys={categorys} onComplete={query}>
            <EasyvButton theme="primary" style={{ marginRight: 12 }}>
              新建
            </EasyvButton>
          </NewTemplate>
        </div>
      </PanelHeaderContainer>
      <EasyvTable
        loading={loading}
        rowSelection={rowSelection}
        onChange={onTableChange}
        dataSource={filterList}
        rowKey={(d) => d.id}
        columns={columns}
        onRowSelectChange={(v) => setSelectedRowKeys(v)}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
      />
    </div>
  );
};

function mapStateToProps({ templates, transfer }) {
  const { list, loading, categorys, pagination } = templates;
  return {
    templates: list,
    pagination,
    categorys,
    loading,
    deadline: transfer.deadline
  };
}

const mapDispatchToProps = {
  getTemplates,
  sortTemplate,
  getCategorys,
  deleteTemplates,
  templatePublish: publish
};

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