import React, { Component } from 'react';
import JSZip from 'jszip';
import ConfirmModal from '../../components/ConfirmModal';
import FileSelect from '../../components/FileSelect';
import ImportAssets from '../../components/ImportAssets';
import http from '../../utils/fetch';
import { api } from '../../constants/config';
import { transformScreenPackage } from 'services/screen';
import exportConfig from 'constants/export-config';
import { Tabs } from '@easyv/antd';
import styles from './importModal.less';
import Synchronous from '../screen-list/components/Synchronous';
import { actions } from 'containers/interaction-list/models/list';
import { connect } from 'react-redux';

// TODO 该功能与可视化应用导入可共用业务逻辑，后续抽离
const { TabPane } = Tabs;
const { extension } = exportConfig;

interface IProps {
  onComplete: () => void;
  onClose: () => void;
  getScreens: () => void;
  checkAuth: (code: string) => boolean;
  editionId: 'saas_basic' | 'saas_advanced' | 'saas_vip';
}
type tabTypes = '1' | '2';

interface IState {
  screens: { uid: string; name: string }[];
  tabActive: tabTypes;
}

class ImportModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      tabActive: window.appConfig.LOCAL ? '2' : '1',
      screens: []
    };
  }

  onFileSelect = (file) => {
    JSZip.loadAsync(file).then((zip) => {
      const files = Object.keys(zip.files);
      const isMultiZip = files[0].slice(files[0].lastIndexOf('.')) === extension.mobile;

      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)
              }));
            });
        });
      } else {
        this.setState((prev) => ({
          screens: prev.screens.concat(file)
        }));
      }
    });
  };

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

  onDataUpload = async (data, signal) => {
    data = {
      mobileConfig: JSON.parse(data.mobileConfig),
      pagesConfig: JSON.parse(data.pagesConfig),
      mapConfig: JSON.parse(data.mapConfig),
      info: data.info && JSON.parse(data.info)
    };

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

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

          return {
            ...d,
            ...result
          };
        })
      );
    }

    return http.post(api.interactionImport, data, { signal }).then((res) => {
      if (res) {
        return Promise.resolve(res);
      } else {
        return Promise.reject();
      }
    });
  };

  handleClose = () => {
    const { screens } = this.state;
    if (screens.length) {
      this.props.onComplete();
    } else {
      this.props.onClose();
    }
    this.setState({
      tabActive: '1'
    });
  };
  onAsync = () => {
    this.props.getScreens();
    this.handleClose();
  };

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

  render() {
    const { screens, tabActive } = this.state;
    const { editionId } = this.props;
    const isLocal = window.appConfig.LOCAL; //是否为本地部署
    // saas基础版和saas高级版只有同步应用的功能，没有导入应用的功能；本地部署版本的话没有同步应用的功能；saasVIP是可以导入和同步的
    return (
      <div className={styles.importModal}>
        <ConfirmModal
          visible={true}
          theme="black"
          destroyOnClose={true}
          getContainer={false}
          title={
            <Tabs className={styles.tabs} activeKey={tabActive} onChange={this.callback}>
              {isLocal || editionId === 'saas_vip' ? (
                <>
                  {this.props.checkAuth('screenSynchronization') && <TabPane tab="同步应用" key="1"></TabPane>}
                  <TabPane tab="导入终端应用" key="2"></TabPane>
                </>
              ) : (
                <TabPane tab="同步应用" key="1"></TabPane>
              )}
            </Tabs>
          }
          onClose={this.handleClose}
          footer={tabActive !== '1'}
          okText="完成"
          cancelText={''}
          onOk={this.handleClose}>
          {/* 注意这里不要改成条件判断渲染dom、通过用css控制显示和隐藏 */}
          <div style={{ display: tabActive === '2' ? 'block' : 'none' }}>
            <FileSelect onComplete={this.onFileSelect} accept={[extension.mobile]} />
            <div className="import-container">
              {screens.map((d) => {
                return (
                  <ImportAssets
                    key={d.uid}
                    file={d}
                    data={[
                      { name: 'mobileConfig', file: 'mobileConfig.json' },
                      {
                        name: 'pagesConfig',
                        file: 'pagesConfig.json'
                      },
                      {
                        name: 'mapConfig',
                        file: 'mapConfig.json'
                      },
                      { name: 'info', file: 'info.json', notRequired: true }
                    ]}
                    assets={['components', 'data']}
                    dataRequest={this.onDataUpload}
                    onRemove={this.onRemove}
                  />
                );
              })}
            </div>
          </div>
          <div style={{ display: tabActive === '2' ? 'none' : 'block' }}>
            <Synchronous onAsyncScreens={this.onAsync} />
          </div>
        </ConfirmModal>
      </div>
    );
  }
}

function mapStateToProps({ user }) {
  return {
    editionId: user.userInfo?.edition?.id
  };
}

export default connect(mapStateToProps, { getScreens: actions.getList })(ImportModal);
