import React, { Fragment, useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { Space } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';
import ExportConstantModal from './ExportConstantModal';
import ImportConstantModal from './ImportConstantModal';
import UpdateConstantModal from './UpdateConstantModal';
import SortConstantModal from './SortConstantModal';
import Thumb from '../../../../components/Thumb';
import { getConstants, sortConstant, publishConstants, deleteConstants } from 'models/constant';
import EasyvButton from 'components/EasyvButton';
import classNames from 'classnames';
import styles from '../style.less';
import EasyvTooltip from 'components/EasyvTooltip';
import { useTitle } from 'components/easyUse';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvTable from 'components/EasyvTable';
import { TableProps } from '@easyv/antd/lib/table';
// import EasyvProgress from 'components/EasyvProgress';
import {getAssetsUrl} from 'utils/utils';

const { Search } = Input;
const categorys = ['常规图表', '文字', '辅助图形', '指标', '地图', '交互', '定制组件', '其他', '第三方'];

interface IProps {
  deadline: Date | string;
  loading: boolean;
  constants: any[];
  getConstants: () => void;
  publishConstants: (param: { constants: string[]; publish: boolean }) => void;
  deleteConstants: (ids: string[]) => void;
  sortConstant: (orders: { name: string; list: any[] }[]) => Promise<any>;
}

interface IState {
  search: string;
  selectedRowKeys: string[];
  filters: {
    category?: string[];
    show?: string[];
  };
  sorter: {
    order?: 'ascend' | 'descend';
  };
  constants?: any[];
}

const ConstantPanel = (props: IProps) => {
  const { loading, constants = [], publishConstants, deleteConstants, getConstants, sortConstant, deadline } = props;
  const [search, setSearch] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [filters, setFilters] = useState<IState['filters']>({});
  const [sorter, setSorter] = useState<IState['sorter']>({});
  const [deleteModuleName, setDeleteModuleName] = useState<any>(); //单个删除的时候记录的moduleName
  const deleteRef = useConfirmRef(); //单个删除时的modal的ref
  const deleteBatchRef = useConfirmRef(); //批量删除时的ref
  useTitle('组件管理');

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

  const selectedLength = selectedRowKeys.length;

  // const handleImageError = (e) => {
  //   const img = e.target;
  //   img.src = defaultImg;
  // };

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

  const onRowSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys);
  };

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

  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 { category = [], 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 (category && category.length) {
      result = result.filter((d) => category.includes(d.category));
    }
    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 flatConstants = (constants) => {
    return Object.values(constants).reduce(
      (all: any[], item) => (Array.isArray(item) ? all.concat(item) : all.concat(flatConstants(item))),
      []
    );
  };

  const onOkDeleteModal = (isBatch: boolean) => {
    if (isBatch) {
      deleteConstants(selectedRowKeys);
      return;
    }
    deleteConstants(deleteModuleName);
  };

  const columns: TableProps<any>['columns'] = useMemo(
    () => [
      {
        title: '组件名称',
        dataIndex: 'name',
        width: '10%',
        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: '10%',
        render: (text) => <span>v{text}</span>
      },
      {
        title: '组件类别',
        dataIndex: 'category',
        width: '10%',
        filters: categorys.map((d) => ({ text: d, value: d }))
      },
      {
        title: '状态',
        dataIndex: 'show',
        width: '10%',
        filters: [
          { text: '已发布', value: '1' },
          { text: '未发布', value: '0' }
        ],
        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: 'updatedBy',
        width: '10%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        dataIndex: 'options',
        render: (
          _text,
          record: {
            moduleName: string;
            thumb: string;
            category: string;
            version: string;
            show: boolean;
          }
        ) => (
          <Space>
            <UpdateConstantModal data={record}>
              <EasyvTooltip title="编辑">
                <i className={classNames('icon iconfont icon-custom ' + styles.iconHover)} />
              </EasyvTooltip>
            </UpdateConstantModal>
            <ExportConstantModal list={[record.moduleName]}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportConstantModal>
            {record.show ? (
              <EasyvTooltip title="下架">
                <i
                  onClick={() => publishConstants({ constants: [record.moduleName], publish: false })}
                  className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)}
                />
              </EasyvTooltip>
            ) : (
              <EasyvTooltip title="发布">
                <i
                  onClick={() => publishConstants({ constants: [record.moduleName], publish: true })}
                  className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
                />
              </EasyvTooltip>
            )}
            <EasyvTooltip title="删除">
              <i
                className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)}
                onClick={() => {
                  setDeleteModuleName([record.moduleName]);
                  deleteRef.current?.show();
                }}
              />
            </EasyvTooltip>
          </Space>
        )
      }
    ],
    [categorys]
  );
  const resultConstants = filterConstant();
  return (
    <Fragment>
      <PanelHeaderContainer>
        <div>
          <ConfigProvider>
            <Search className={styles.searchInput} onChange={handleSearch} placeholder="搜索组件名称" value={search} />
          </ConfigProvider>
          <EasyvButton
            style={{ marginLeft: 16 }}
            disabled={!selectedLength}
            onClick={() => publishConstants({ constants: selectedRowKeys, publish: false })}>
            批量下架
          </EasyvButton>
          <EasyvButton
            style={{ marginLeft: 12 }}
            disabled={!selectedLength}
            onClick={() => publishConstants({ constants: selectedRowKeys, publish: true })}>
            批量上架
          </EasyvButton>
          <ExportConstantModal list={selectedRowKeys} onComplete={onExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedLength}>
              批量导出
            </EasyvButton>
          </ExportConstantModal>
          <EasyvButton onClick={() => deleteBatchRef.current?.show()} style={{ marginLeft: 12 }} disabled={!selectedLength}>
            批量删除
          </EasyvButton>
        </div>
        <div>
          <SortConstantModal data={constants.filter((d) => d.show)} onComplete={sortConstant}>
            <EasyvButton style={{ marginRight: 12 }}>组件排序</EasyvButton>
          </SortConstantModal>
          <ImportConstantModal onComplete={getConstants}>
            <EasyvButton theme="primary">导入</EasyvButton>
          </ImportConstantModal>
        </div>
      </PanelHeaderContainer>
      <EasyvTable
        columns={columns}
        dataSource={resultConstants}
        rowKey={(d: any) => d.moduleName}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
        onChange={onTableChange}
        loading={loading}
        selectedRowKeys={selectedRowKeys}
        onRowSelectChange={onRowSelectChange}
      />

      {/* TODO 这里可以写判断只让页面生成一个modal */}
      <EasyvModal.Confirm
        content="此操作执行后不可逆，是否确认将对应文件删除？"
        title="删除组件"
        onOk={() => onOkDeleteModal(false)}
        ref={deleteRef}
      />

      <EasyvModal.Confirm
        content="此操作执行后不可逆，是否确认将对应文件删除？"
        title="批量删除组件"
        onOk={() => onOkDeleteModal(true)}
        ref={deleteBatchRef}
      />
    </Fragment>
  );
};
function mapStateToProps({ constants, transfer }) {
  const { loading, list } = constants;
  const { deadline } = transfer;

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

const mapDispatchToProps = {
  getConstants,
  sortConstant,
  publishConstants,
  deleteConstants
};

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