import React, { useState, useEffect, useCallback, FC, useMemo } from 'react';
import { connect } from 'react-redux';
import { Space } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';
import Thumb from 'components/Thumb';
import DeleteConfirmModal from 'components/DeleteConfirmModal';
import ExportConstantModal from './ExportConstantModal';
import ImportConstantModal from './ImportConstantModal';
import UpdateConstantModal from './UpdateConstantModal';
import SortConstantModal from './SortConstantModal';
import { getConstants, sortConstant, deleteConstants } from 'models/tenant-constant';
import { useTitle } from 'components/easyUse';
import styles from './index.less';
import classNames from 'classnames';
import EasyvButton from 'components/EasyvButton';
import EasyvTooltip from 'components/EasyvTooltip';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import TransferScroll from 'containers/TransferScroll';
import EasyvTable from 'components/EasyvTable';
import EasyvNoData from 'components/EasyvNoData';
import {getAssetsUrl} from 'utils/utils';

const { Search } = Input;

const ConstantPanel: FC<{
  deadline: Date | string;
  loading: boolean;
  constants: any[];
  getConstants: () => Promise<void>;
  deleteConstants: (ids) => Promise<void>;
  sortConstant: () => Promise<void>;
}> = ({ deadline, loading, constants = [], getConstants, deleteConstants, sortConstant }) => {
  const [search, setSearch] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number|string)[]>([]);
  const [filters, setFilters] = useState<{ show?: string[] }>({});
  const [sorter, setSorter] = useState<{ order?: 'descend' | 'ascend' }>({});
  const [isActivate, setActivate] = useState(false); // 批量管理状态

  useTitle('组件开发');

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

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

  const onTableChange = (_pagination, filters, sorter) => {
    setFilters(filters);
    setSorter(sorter);
  };

  const filterConstant = () => {
    const sortedConstants = constants.concat().sort((a, b) => +new Date(b.updatedAt) - +new Date(a.updatedAt));
    sortedConstants.sort((a, b) => b.show - a.show);
    const { show = [] } = filters;
    const { order } = sorter;

    let result = sortedConstants.filter(
      (d) =>
        (d.name && d.name.toLowerCase().includes(search.toLowerCase())) ||
        (d.moduleName && d.moduleName.toLowerCase().includes(search.toLowerCase()))
    );

    if (show && show.length) {
      result = result.filter((d) => show.includes('' + d.show));
    }
    if (order) {
      result.sort((a, b) =>
        order === 'descend' ? +new Date(b.updatedAt) - +new Date(a.updatedAt) : +new Date(a.updatedAt) - +new Date(b.updatedAt)
      );
    }

    return result;
  };

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

  const selectedLength = selectedRowKeys.length;
  const resultConstants = filterConstant() || [];

  const checkAll = useCallback(() => {
    const allButton: any = document.querySelector('button[id=select-all]');
    allButton.blur();
    setSelectedRowKeys(resultConstants.map((d) => d.id));
  }, [resultConstants]);

  const columns = useMemo(() => {
    return [
      {
        title: '组件名称',
        dataIndex: 'name',
        width: '20%',
        render: (text, record: any) => <span title={record.moduleName}>{text}</span>
      },
      {
        title: '缩略图',
        dataIndex: 'thumb',
        width: '10%',
        render: (text) => <Thumb src={text ? getAssetsUrl(text) : undefined} style={{ width: 68, height: 44 }} />
      },
      {
        title: '组件版本号',
        dataIndex: 'version',
        width: '15%',
        render: (text) => <span>v{text}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'updatedAt',
        width: '20%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '开发者',
        dataIndex: 'developerName',
        width: '20%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        dataIndex: 'options',
        render: (_text, record: any) => (
          <Space size={18}>
            <UpdateConstantModal data={record}>
              <EasyvTooltip title="编辑">
                <i className={classNames('icon iconfont icon-custom ' + styles.iconHover)} />
              </EasyvTooltip>
            </UpdateConstantModal>
            <ExportConstantModal list={[record.id]} onComplete={onExportComplete}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportConstantModal>
            <DeleteConfirmModal title="删除组件" onOk={() => deleteConstants([record.id])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ];
  }, []);

  return (
    <ConfigProvider>
      <div className={classNames('panel', styles.panel)}>
        <TransferScroll type="all" />
        <PanelHeaderContainer>
          {isActivate ? (
            <>
              <div>已选择{selectedLength}个应用</div>
              <div>
                <EasyvButton id="select-all" theme="default" onClick={checkAll} style={{ marginRight: 16 }}>
                  全选
                </EasyvButton>
                <DeleteConfirmModal title="删除组件" onOk={() => deleteConstants(selectedRowKeys)}>
                  <EasyvButton theme="danger" style={{ marginRight: 8 }} disabled={!selectedLength}>
                    删除
                  </EasyvButton>
                </DeleteConfirmModal>
                <ExportConstantModal list={selectedRowKeys} onComplete={onExportComplete}>
                  <EasyvButton style={{ marginRight: 8 }} disabled={!selectedLength}>
                    导出
                  </EasyvButton>
                </ExportConstantModal>
                <EasyvButton
                  theme="default"
                  onClick={() => {
                    setActivate(false);
                    setSelectedRowKeys([]);
                  }}>
                  取消操作
                </EasyvButton>
              </div>
            </>
          ) : (
            <>
              <div style={{ fontSize: 16, color: '#fff' }}>组件列表</div>
              <div>
                <Search
                  className={styles.search_input}
                  style={{ width: 200, marginRight: 16 }}
                  onChange={handleSearch}
                  placeholder="搜索组件名称"
                  value={search}
                />

                <EasyvButton
                  theme="default"
                  onClick={() => {
                    setActivate(true);
                  }}
                  disabled={!resultConstants.length}
                  className={styles.management}
                  style={{ marginRight: 16 }}>
                  批量管理
                </EasyvButton>

                <SortConstantModal data={constants} onComplete={sortConstant}>
                  <EasyvButton theme="default" style={{ marginRight: 16 }}>
                    组件排序
                  </EasyvButton>
                </SortConstantModal>
                <ImportConstantModal onComplete={getConstants}>
                  <EasyvButton theme="default" style={{ marginRight: 16 }}>
                    组件导入
                  </EasyvButton>
                </ImportConstantModal>
                <EasyvButton theme="primary" onClick={() => window.open('https://www.npmjs.com/package/@easyv/cli')}>
                  下载开发者工具
                </EasyvButton>
              </div>
            </>
          )}
        </PanelHeaderContainer>
        {(resultConstants && resultConstants.length) || search ? (
          <>
            <EasyvTable
              loading={loading}
              selectedRowKeys={selectedRowKeys}
              onRowSelectChange={(v) => setSelectedRowKeys(v)}
              openSelect={isActivate}
              dataSource={resultConstants}
              rowKey={(d: any) => d.id}
              scroll={deadline ? { y: 'calc(100vh - 292px)' } : { y: 'calc(100vh - 250px)' }}
              onChange={onTableChange}
              columns={columns}
            />
          </>
        ) : (
          <EasyvNoData style={{ height: 'calc(100vh - 132px)' }} text="暂无数据" />
        )}
      </div>
    </ConfigProvider>
  );
};

function mapStateToProps({ tenantConstants, transfer }) {
  const { loading, list } = tenantConstants;

  return {
    constants: list,
    loading,
    deadline: transfer.deadline
  };
}

const mapDispatchToProps = {
  getConstants,
  sortConstant,
  deleteConstants
};

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