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 DeleteConfirmModal from '../../../../components/DeleteConfirmModal';
import ExportConstantModal from './ExportConstantModal';
import ImportConstantModal from './ImportConstantModal';
import UpdateConstantModal from './UpdateConstantModal';
import SortConstantModal from './SortConstantModal';
import Thumb from '../../../../components/Thumb';
import { getMobileConstants, sortMobileConstant, publishMobileConstants, deleteMobileConstants } from 'models/mobile-constant';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';
import styles from '../style.less';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvButton from 'components/EasyvButton';
import EasyvTable from 'components/EasyvTable';
import { useTitle } from 'components/easyUse';
import {getAssetsUrl} from 'utils/utils';


const { Search } = Input;
const categorys = ['常规组件', '交互组件'];
interface IProps {
  loading: boolean;
  constants: any[];
  deadline: Date | string;
  getMobileConstants: () => void;
  publishMobileConstants: (param: { constants: string[]; publish: boolean }) => void;
  deleteMobileConstants: (ids: string[]) => void;
  sortMobileConstant: (orders: { name: string; list: any[] }[]) => Promise<any>;
}

const MobileConstantPanel = React.memo((props: IProps) => {
  const { getMobileConstants, constants = [], loading, publishMobileConstants, deleteMobileConstants, deadline } = props;
  const [search, setSearch] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [filters, setFilters] = useState<any>({});
  const [sorter, setSorter] = useState<any>({});
  useTitle('终端组件管理');

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

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

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

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

  const onTableChange = (_pagination, f, s) => {
    setFilters(f);
    setSorter(s);
  };

  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.toLowerCase().includes(search.toLowerCase()) || 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 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: any) => (
          <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={() => publishMobileConstants({ constants: [record.moduleName], publish: false })}
                  className={classNames('icon iconfont icon-xiajia ' + styles.iconHover)}
                />
              </EasyvTooltip>
            ) : (
              <EasyvTooltip title="发布">
                <i
                  onClick={() => publishMobileConstants({ constants: [record.moduleName], publish: true })}
                  className={classNames('icon iconfont icon-btn_publishhomepage ' + styles.iconHover)}
                />
              </EasyvTooltip>
            )}
            <DeleteConfirmModal title="删除组件" onOk={() => deleteMobileConstants([record.moduleName])}>
              <EasyvTooltip title="删除">
                <i className={classNames('icon iconfont icon-btn_delete ' + styles.iconHover)} />
              </EasyvTooltip>
            </DeleteConfirmModal>
          </Space>
        )
      }
    ],
    [categorys]
  );

  return (
    <Fragment>
      <PanelHeaderContainer>
        <div>
          <ConfigProvider>
            <Search className={styles.searchInput} onChange={handleSearch} placeholder="搜索组件名称" value={search} />
          </ConfigProvider>
          <EasyvButton
            style={{ marginLeft: 16 }}
            disabled={!selectedRowKeys.length}
            onClick={() => publishMobileConstants({ constants: selectedRowKeys, publish: false })}>
            批量下架
          </EasyvButton>
          <EasyvButton
            style={{ marginLeft: 12 }}
            disabled={!selectedRowKeys.length}
            onClick={() => publishMobileConstants({ constants: selectedRowKeys, publish: true })}>
            批量上架
          </EasyvButton>
          <ExportConstantModal list={selectedRowKeys} onComplete={onExportComplete}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length}>
              批量导出
            </EasyvButton>
          </ExportConstantModal>
          <DeleteConfirmModal title="批量删除组件" onOk={() => deleteMobileConstants(selectedRowKeys)}>
            <EasyvButton style={{ marginLeft: 12 }} disabled={!selectedRowKeys.length}>
              批量删除
            </EasyvButton>
          </DeleteConfirmModal>
        </div>
        <div>
          <SortConstantModal data={constants.filter((d) => d.show)} onComplete={props.sortMobileConstant}>
            <EasyvButton style={{ marginRight: 12 }}>组件排序</EasyvButton>
          </SortConstantModal>
          <ImportConstantModal onComplete={getMobileConstants}>
            <EasyvButton theme="primary">导入</EasyvButton>
          </ImportConstantModal>
        </div>
      </PanelHeaderContainer>
      <EasyvTable
        columns={columns}
        loading={loading}
        selectedRowKeys={selectedRowKeys}
        onRowSelectChange={onRowSelectChange}
        dataSource={filterConstant() || []}
        rowKey={(d: any) => d.moduleName}
        scroll={deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
        onChange={onTableChange}
      />
    </Fragment>
  );
});

function mapStateToProps({ mobileConstants, transfer }) {
  return {
    constants: mobileConstants.list,
    loading: mobileConstants.loading,
    deadline: transfer.deadline
  };
}

const mapDispatchToProps = {
  getMobileConstants,
  sortMobileConstant,
  publishMobileConstants,
  deleteMobileConstants
};

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