import React, { useRef, useState } from 'react';
import { connect } from 'react-redux';
import { ConfigProvider } from '@easyv/react-gui';
import { getSource } from 'models/source';
import EasyvButton from 'components/EasyvButton';
import EasyvModal, { useActionModalRef, useConfirmRef } from 'components/EasyvModal';
import message from 'components/message';
import {
  DataSourceType,
  fetchAndDecode,
  filterExcelDataIsEmptyColumn,
  uploadCsv,
} from 'components/EasyvCsvExcel/util';
import EasyvCsvExcel, { EasyvCsvExcelRef } from 'components/EasyvCsvExcel';
import debounce from 'lodash/debounce';
import { getAssetsUrl } from 'utils/utils';
import { ComponentItem } from '@/models/component.types';
import { EditFilled } from '@easyv/react-icons';
import styles from './table-view-edit.less';
import { getComponentData } from '@/models/component';
import EliminateShortcutKeyConflicts from '@/components/EasyvCsvExcel/EliminateShortcutKeyConflicts';

const TableViewEdit = ({ id, componentId, getComponentData }) => {
  const csvEditModalRef = useActionModalRef();
  const csvEasyvCsvExcelRef = useRef<EasyvCsvExcelRef>(null);
  const confirmRef = useConfirmRef();
  const [actionData, setActionData] = useState<DataSourceType>();
  const [csvData, setCsvData] = useState();
  const [disabled, setDisabled] = useState(false);

  const openModal = async () => {
    setDisabled(true);
    const loading = message.loading('csv数据加载中...');
    const dataBaseInfo: any = await getSource(id)();
    if (!dataBaseInfo) {
      loading();
      setDisabled(false);
      return;
    }
    setActionData(dataBaseInfo);
    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);
    }
  };

  const getCSVSourse = async (id: string) => {
    const dataBaseInfo: any = await getSource(id)();
    const res =
      dataBaseInfo?.filePath &&
      (await uploadCsv(
        filterExcelDataIsEmptyColumn(csvEasyvCsvExcelRef.current?.getData()),
        dataBaseInfo.filePath,
        actionData!,
      ));
    return res;
  };

  const upDateComponentData = () => {
    getComponentData(componentId);
  };

  return (
    <ConfigProvider>
      <div style={{ fontSize: '12px', margin: '-14px 0 0 80px' }}>
        <div
          className={styles.course}
          onClick={() => {
            openModal();
          }}>
          表格视图编辑
          <EditFilled className={styles.right} />
        </div>
      </div>
      <EasyvModal.ActionModal
        width={'60%'}
        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(async () => {
                const loading = message.loading('正在保存数据...');
                setDisabled(true);
                if (!actionData) {
                  loading();
                  message.error('参数异常');
                  return;
                }
                const result = await getCSVSourse(actionData?.id);
                if (result && result.success) {
                  loading();
                  message.success('更新成功');
                  setDisabled(false);
                  upDateComponentData();
                  csvEditModalRef.current?.close();
                } else {
                  loading();
                  setDisabled(false);
                  message.error(result.message);
                }
              }, 200)}>
              完成
            </EasyvButton>
          </div>
        }
        content={
          <EliminateShortcutKeyConflicts>
            <EasyvCsvExcel
              containerId="containerId"
              contentId="contentId"
              ref={csvEasyvCsvExcelRef}
              data={csvData}
            />
          </EliminateShortcutKeyConflicts>
        }
      />
      <EasyvModal.Confirm
        onOk={async () => {
          if (actionData) {
            const result = await getCSVSourse(actionData?.id);
            if (result) {
              if (result.success) {
                message.success('更新成功');
                upDateComponentData();
              } else {
                message.success(result.message);
              }
            }
            confirmRef.current?.close();
            csvEditModalRef.current?.close();
            // setEntrance(false);
          } else {
            message.error('参数异常');
          }
          confirmRef.current?.close();
          csvEditModalRef.current?.close();
        }}
        onCancel={() => {
          confirmRef.current?.close();
          csvEditModalRef.current?.close();
        }}
        onOkBtnType="primary"
        okText="保存"
        content="修改会同步修改数据源文件，是否保存当前数据?"
        title="未保存"
        iconType="warning"
        ref={confirmRef}
      />
    </ConfigProvider>
  );
};

const mapDispatchToProps = {
  getComponentData,
};

const mapStateToProps = ({ componentsById, createApp }) => {
  const { componentsChildSelected, layersSelected } = createApp;

  const componentId = componentsChildSelected || layersSelected[0];
  const current = componentsById[componentId] as ComponentItem;

  return {
    id: current.dataConfigs[current.dataType].config?.data_id,
    componentId,
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(TableViewEdit);
