/* eslint-disable react-hooks/exhaustive-deps */
import React, { Dispatch, useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { Table, Pagination, Space } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';
import { useTitle } from 'components/easyUse';
import SourceEdit from './SourceEdit';
import styles from './DataSourceList.less';
import { getSources, searchSources, changePage, deleteSource, getSource } from 'models/source';
import EasyvButton from 'components/EasyvButton';
import classNames from 'classnames';
import EasyvTooltip from 'components/EasyvTooltip';
import EasyvModal, { useActionModalRef, useConfirmRef } from 'components/EasyvModal';
import TransferScroll from 'containers/TransferScroll';
import EasyvNoData from 'components/EasyvNoData';
import { ReviseSquareOutlined, DeleteOutlined, EditOutlined } from '@easyv/react-icons';
import message from 'components/message';
import { DataSourceType, fetchAndDecode, uploadCsv } from 'components/EasyvCsvExcel/util';
import EasyvCsvExcel, { EasyvCsvExcelRef } from 'components/EasyvCsvExcel';
import debounce from 'lodash/debounce';
import { getAssetsUrl } from 'utils/utils';

const { Search } = Input;

function DataSourceList({
  loading,
  list,
  search,
  page,
  pageSize,
  spaceCurrent,
  dispatch,
  isImportExpired,
  deadline,
}: {
  loading: boolean;
  list: any[];
  search: string;
  page: number;
  spaceCurrent: number;
  pageSize: number;
  dispatch: Dispatch<any>;
  isImportExpired: boolean;
  deadline: Date | string;
}) {
  useTitle('我的数据');
  const csvEditModalRef = useActionModalRef();
  const csvEasyvCsvExcelRef = useRef<EasyvCsvExcelRef>(null);
  const deleteRef = useConfirmRef();
  const confirmRef = useConfirmRef();
  const [deleteId, setDeleteId] = useState<number>();
  const [actionData, setActionData] = useState<DataSourceType>();
  const [csvData, setCsvData] = useState();
  const [disabled, setDisabled] = useState(false);

  useEffect(() => {
    // 空间变化，分页重置
    dispatch(changePage(1));
  }, [spaceCurrent]);

  useEffect(() => {
    dispatch(getSources());
  }, []);

  const tableColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      width: '20%',
    },
    {
      title: '数据类型',
      dataIndex: 'type',
      width: '20%',
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: '20%',
    },
    {
      title: '修改时间',
      dataIndex: 'updatedAt',
      width: '20%',
    },
    {
      title: '操作',
      key: 'action',
      render: (row, { id }) => {
        return (
          <Space size={18}>
            <SourceEdit id={id}>
              <EasyvTooltip title="编辑">
                <EditOutlined className={styles.iconHover} />
              </EasyvTooltip>
            </SourceEdit>
            <EasyvTooltip title="删除">
              <DeleteOutlined
                onClick={() => {
                  setDeleteId(id);
                  deleteRef.current?.show();
                }}
                className={styles.iconHover}
              />
            </EasyvTooltip>
            {row.type === 'CSV文件' ? (
              <>
                <EasyvTooltip title="修改数据">
                  <ReviseSquareOutlined
                    style={disabled ? { pointerEvents: 'none' } : { pointerEvents: 'auto' }}
                    onClick={debounce(() => {
                      setDisabled(true);
                      setActionData(row);
                      const loading = message.loading('csv数据加载中...');
                      getSource(row.id)().then(async (dataBaseInfo: any) => {
                        if (!dataBaseInfo) {
                          loading();
                          setDisabled(false);
                          return;
                        }
                        const res: any = await fetchAndDecode(
                          getAssetsUrl(`${dataBaseInfo.filePath}`),
                        );
                        if (res.success) {
                          loading();
                          setCsvData(res.data);
                          setDisabled(false);
                          csvEditModalRef.current?.show();
                        } else {
                          loading();
                          setDisabled(false);
                          message.error(res.message);
                        }
                      });
                    }, 200)}
                    className={styles.iconHover}
                  />
                </EasyvTooltip>
              </>
            ) : null}
          </Space>
        );
      },
    },
  ];

  const handleSearchChange = (e) => {
    dispatch(searchSources(e.target.value));
  };

  const handlePageChange = (page) => {
    dispatch(changePage(page));
  };

  const totalList: DataSourceType[] = list.filter((d) => d.name.includes(search));
  const currentPageList = totalList.slice((page - 1) * pageSize, page * pageSize);

  return (
    <ConfigProvider>
      <div
        className={classNames(
          styles.wrapper,
          { [styles.migrate]: deadline },
          { [styles.notMigrate]: !deadline },
        )}>
        <TransferScroll type="all" />
        <div className={styles.header}>
          {!isImportExpired && (
            <SourceEdit>
              <EasyvButton
                theme="primary"
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i
                  className="icon iconfont icon-constant-custom"
                  style={{ position: 'relative', top: '1px' }}
                />
                添加数据源
              </EasyvButton>
            </SourceEdit>
          )}
          <Search
            className={styles.search_input}
            placeholder="搜索"
            value={search}
            style={{ width: 210 }}
            onChange={handleSearchChange}
          />
        </div>
        {totalList && totalList.length === 0 && <EasyvNoData text="暂无数据" />}
        {totalList && totalList.length > 0 && (
          <div className={styles.tableWrapper}>
            <Table
              columns={tableColumns}
              dataSource={currentPageList}
              rowKey={(record) => record.id}
              pagination={false}
              loading={loading}
              scroll={deadline ? { y: 'calc(100vh - 292px)' } : { y: 'calc(100vh - 250px)' }}
            />

            <div className="table-footer-pagination">
              <span>
                共<span className="count">{totalList.length}</span>
                条数据，每页显示：
                <span className="count">{pageSize}</span>条
              </span>
              <Pagination
                current={page}
                total={totalList.length}
                pageSize={pageSize}
                onChange={handlePageChange}
                showSizeChanger={false}
              />
            </div>
          </div>
        )}
      </div>
      <EasyvModal.Confirm
        ref={deleteRef}
        title="删除数据源"
        content="此操作执行后不可逆，是否确认将对应文件删除?"
        onOk={() => dispatch(deleteSource(deleteId))}
      />

      <EasyvModal.ActionModal
        width={1000}
        title={
          <span>
            修改数据<span style={{ color: '#B4B7C1', marginLeft: 16 }}>{actionData?.name}</span>
          </span>
        }
        ref={csvEditModalRef}
        maxHeight="none"
        onCancel={() => {
          if (csvEasyvCsvExcelRef.current?.getChangedStatus()) {
            confirmRef.current?.show();
            return;
          }
          csvEditModalRef.current?.close();
        }}
        footer={
          <div style={{ textAlign: 'center' }}>
            <EasyvButton
              theme="primary"
              disabled={disabled}
              onClick={debounce(() => {
                const loading = message.loading('正在保存数据...');
                setDisabled(true);
                getSource(actionData?.id)().then(async (dataBaseInfo: any) => {
                  if (dataBaseInfo) {
                    const res = await uploadCsv(
                      csvEasyvCsvExcelRef.current?.getData(),
                      dataBaseInfo.filePath,
                      actionData!,
                    );
                    if (res.success) {
                      loading();
                      message.success('更新成功');
                      setDisabled(false);
                      csvEditModalRef.current?.close();
                    } else {
                      loading();
                      setDisabled(false);
                      message.success(res.message);
                    }
                    return;
                  }
                  setDisabled(false);
                  loading();
                });
              }, 200)}>
              完成
            </EasyvButton>
          </div>
        }
        content={
          <EasyvCsvExcel
            containerId="containerId"
            contentId="contentId"
            ref={csvEasyvCsvExcelRef}
            data={csvData}
          />
        }
      />

      <EasyvModal.Confirm
        onOk={() => {
          getSource(actionData?.id)().then(async (dataBaseInfo: any) => {
            if (dataBaseInfo) {
              const res = await uploadCsv(
                csvEasyvCsvExcelRef.current?.getData(),
                dataBaseInfo.filePath,
                actionData!,
              );
              if (res.success) {
                message.success('更新成功');
                confirmRef.current?.close();
                csvEditModalRef.current?.close();
              } else {
                message.success(res.message);
              }
            }
          });
        }}
        onCancel={() => {
          confirmRef.current?.close();
          csvEditModalRef.current?.close();
        }}
        onOkBtnType="primary"
        okText="保存"
        content="修改会同步修改数据源文件，是否保存当前数据?"
        title="未保存"
        iconType="warning"
        ref={confirmRef}
      />
    </ConfigProvider>
  );
}

const mapStateToProps = ({ sources, user, transfer, space }) => {
  const { loading, list, search, page, pageSize, dispatch } = sources;
  const { current } = space;
  return {
    loading,
    spaceCurrent: current,
    list,
    search,
    page,
    pageSize,
    dispatch,
    isImportExpired: user.userInfo.isImportExpired,
    deadline: transfer.deadline,
  };
};

export default connect(mapStateToProps)(DataSourceList);
