import React, { Component } from 'react';
import { connect } from 'react-redux';
import JSZip from 'jszip';
import message from 'components/message';
import ConfirmModal from 'components/ConfirmModal';
import FileSelect from 'components/FileSelect';
import ImportAssets from 'components/ImportAssets';
import exportConfig from 'constants/export-config';
import { importScreen, getScreens } from 'models/screens';
import { transformScreenPackage } from 'services/screen';
import { transformImportDataToHigherVersion4dot5 } from 'utils/patch';
import { Tabs } from '@easyv/antd';
import styles from './ImportScreensModal.less';
import Synchronous from './Synchronous';
import EasyvScrollContainer from 'components/EasyvScrollContainer';
const { TabPane } = Tabs;

interface IProps {
  disabled: boolean;
  onComplete: () => void;
  groupId: number | 'trash';
  importScreen: (data: unknown, signal: unknown) => Promise<unknown>;
  getScreensLIst: () => Promise<unknown>;
  children: React.ReactNode;
  editionId: 'saas_basic' | 'saas_advanced' | 'saas_vip';
  checkAuth?: (authCode: string) => boolean;
}
type tabTypes = '1' | '2';
interface IState {
  visible: boolean;
  screens: {
    uid: string;
    name: string;
  }[];
  currentScreenId: string;
  tabActive: tabTypes;
}

const { extension } = exportConfig;

class ImportScreensModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      tabActive: '2',
      currentScreenId: '',
      screens: [],
    };
  }

  componentDidMount() {
    this.resetTabActive();
  }

  resetTabActive = () => {
    this.setState({
      tabActive: window.appConfig.LOCAL ? '2' : '1',
    });
  };

  showModal = () => {
    if (this.props.disabled) {
      message.error('您的应用数已超出上限，请删除部分应用后再试');
      return;
    }

    this.setState({
      visible: true,
    });
  };

  onAsync = () => {
    this.props.getScreensLIst();
    this.hideModal();
  };

  hideModal = () => {
    this.resetTabActive();
    this.setState(
      {
        visible: false,
        screens: [],
      },
      () => {
        this.props.onComplete?.();
      },
    );
  };

  onFileSelect = (file) => {
    this.setState({
      currentScreenId: '',
    });
    JSZip.loadAsync(file).then((zip) => {
      const files = Object.keys(zip.files);
      const isMultiZip = files[0].slice(files[0].lastIndexOf('.')) === extension.screen;
      if (isMultiZip) {
        zip.forEach((d, i) => {
          zip
            .file(d)
            ?.async('blob')
            .then((res: any) => {
              res.name = d;
              res.uid = `rc-upload-${+new Date()}-${i}`;
              this.setState((prev) => ({
                screens: prev.screens.concat(res),
              }));
              if (!this.state.currentScreenId) {
                this.setState({
                  currentScreenId: res.uid,
                });
              }
            });
        });
      } else {
        this.setState((prev) => ({
          screens: prev.screens.concat(file),
        }));
        if (!this.state.currentScreenId) {
          this.setState({
            currentScreenId: file.uid,
          });
        }
      }
    });
  };

  onRemove = (id) => {
    this.setState((prev) => ({
      screens: prev.screens.filter((file) => file.uid !== id),
    }));
  };

  onComplete = (id)=>{
    if (id === this.state.currentScreenId) {
      const index = this.state.screens.findIndex((d) => d.uid === this.state.currentScreenId);
      const next = this.state.screens[index + 1];
      if (index > -1 && next) {
        this.setState({
          currentScreenId: next.uid,
        });
      }
    }
  }

  onDataUpload = async (data, signal) => {
    data = {
      groupId: this.props.groupId,
      screenConfig: JSON.parse(data.screenConfig),
      componentsConfig: JSON.parse(data.componentsConfig),
      sourceConfig: (data.sourceConfig && JSON.parse(data.sourceConfig)) || [],
      filterConfig: (data.filterConfig && JSON.parse(data.filterConfig)) || [],
      panelConfig: (data.panelConfig && JSON.parse(data.panelConfig)) || [],
      constantConfig: (data.constantConfig && JSON.parse(data.constantConfig)) || [],
      info: data.info && JSON.parse(data.info),
      componentContainerRelsConfig:
        data.componentContainerRelsConfig && JSON.parse(data.componentContainerRelsConfig),
      containersConfig: data.containersConfig && JSON.parse(data.containersConfig),
    };

    data = transformImportDataToHigherVersion4dot5(data);

    if (!window.appConfig.LOCAL && !data.info) {
      const result = await transformScreenPackage({
        from: 3.5,
        to: 3.6,
        data: {
          componentsConfig: data.componentsConfig,
          sourceConfig: data.sourceConfig,
          filterConfig: data.filterConfig,
          panelConfig: data.panelConfig,
        },
      });

      if (!result) {
        return Promise.reject();
      }

      data = {
        ...data,
        ...result,
      };
    }
    const result = await this.props.importScreen(data, signal);
    return result;
  };

  onTabChange = (key: tabTypes) => {
    this.setState({
      tabActive: key,
    });
  };

  render() {
    const { visible, screens, tabActive ,currentScreenId} = this.state;
    const isLocal = window.appConfig.LOCAL; //是否为本地部署

    // saas基础版和saas高级版只有同步项目的功能，没有导入项目的功能；本地部署版本的话没有同步项目的功能；saasVIP是可以导入和同步的
    return (
      <span className={styles.importModal}>
        <span onClick={this.showModal}>{this.props.children}</span>
        {visible && (
          <ConfirmModal
            visible={visible}
            destroyOnClose={true}
            getContainer={false}
            className={styles.content}
            theme="black"
            title={
              <Tabs className={styles.tabs} activeKey={tabActive} onChange={this.onTabChange}>
                {/* 基础版和高级版去掉导入功能 - v4.10 林树 */}
                {(this.props.checkAuth && this.props.checkAuth('importScreen')) || isLocal ? (
                  <>
                    {this.props.checkAuth?.('screenSynchronization') && (
                      <TabPane tab="同步应用" key="1"></TabPane>
                    )}
                    <TabPane tab="导入应用" key="2"></TabPane>
                  </>
                ) : (
                  <TabPane tab="同步应用" key="1"></TabPane>
                )}
              </Tabs>
            }
            onClose={this.hideModal}
            footer={tabActive !== '1'}
            okText="完成"
            cancelText={''}
            onOk={this.hideModal}>
            <div style={{ display: tabActive === '2' ? 'block' : 'none' }}>
              <FileSelect onComplete={this.onFileSelect} accept={[extension.screen]} />
              {screens.length ? (
                <EasyvScrollContainer className={styles.importContainer}>
                  {screens.map((d) => {
                    return (
                      <ImportAssets
                        key={d.uid}
                        currentScreenId={currentScreenId}
                        file={d}
                        data={[
                          { name: 'screenConfig', file: 'screenConfig.json' },
                          {
                            name: 'componentsConfig',
                            file: 'componentsConfig.json',
                          },
                          { name: 'sourceConfig', file: 'sourceConfig.json', notRequired: true },
                          { name: 'filterConfig', file: 'filterConfig.json' },
                          { name: 'panelConfig', file: 'panelConfig.json', notRequired: true },
                          {
                            name: 'constantConfig',
                            file: 'constantConfig.json',
                            notRequired: true,
                          },
                          { name: 'info', file: 'info.json', notRequired: true },
                          { name: 'containersConfig', file: 'containersConfig.json' },
                          {
                            name: 'componentContainerRelsConfig',
                            file: 'componentContainerRelsConfig.json',
                          },
                        ]}
                        assets={[
                          'components',
                          'data',
                          'screen',
                          'thumb',
                          'tenants',
                          'easyv-market',
                          '/data',
                        ]} // easyv-market 为了兼容素材广场的图片前缀 /data 为了兼容导出的时候 '/data/xxx' 和 'data/xxx'
                        dataRequest={this.onDataUpload}
                        onComplete={this.onComplete}
                        onRemove={this.onRemove}
                      />
                    );
                  })}
                </EasyvScrollContainer>
              ) : null}
            </div>

            <div style={{ display: tabActive === '2' ? 'none' : 'block' }}>
              <Synchronous onAsyncScreens={this.onAsync} />
            </div>
          </ConfirmModal>
        )}
      </span>
    );
  }
}
function mapStateToProps({ user }) {
  return {
    editionId: user.userInfo?.edition?.id,
  };
}

export default connect(mapStateToProps, { getScreensLIst: getScreens, importScreen })(
  ImportScreensModal,
);
