import React, { useRef, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { connect } from 'react-redux';
import EasyGUI, { Utils } from '@easyv/react-gui';
import { updateComponentConfig } from 'models/component';
import { hideComponentEditModal, updateFocusMode } from 'models/create-app';
import styles from './index.less';
import { Switch, Tooltip, Space } from '@easyv/antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import ModelToReplace from '../ModelToReplace';
import classNames from 'classnames';
import message from 'components/message';
import { useAuth } from 'components/easyUse';
import { modules } from 'constants/authority';

const { getConfig } = Utils;
const cameraText = {
  0: '未选中任何场景镜头',
  1: (
    <>
      当前场景镜头<span style={{ color: '#fe384b' }}>未保存</span>
    </>
  ),
  2: (
    <>
      当前场景镜头<span style={{ color: '#167dff' }}>已保存</span>
    </>
  ),
};

interface ModalPathType {
  path: string[];
  value: {
    data: {
      accept: string;
      type: string;
    };
  };
}

function ComponentEditModal(props) {
  const {
    modalEdit,
    componentsById,
    updateConfig,
    hideComponentEditModal,
    updateFocusMode,
    focusMode,
  } = props;
  const component = componentsById[modalEdit];
  const easyvConfirm = useConfirmRef();
  const [modelPath, setModelPath] = useState<ModalPathType>({} as ModalPathType);
  const [visible, setVisible] = useState(false);
  const [cameraState, setCameraState] = useState(0); // 1->未保存;2->已保存；0->未选中任何场景镜头
  const { checkAuth } = useAuth();

  useEffect(() => {
    sessionStorage.removeItem('camera');
    // 用户动了镜头
    const cameraEvent = () => {
      setCameraState(1);
    };
    const collectCameraState = () => {
      // 用户点击来镜头
      sessionStorage.removeItem('camera');
      setCameraState(2);
    };
    document.addEventListener('saveCamera', collectCameraState);
    document.addEventListener('cameraEvent', cameraEvent);
    return () => {
      document.removeEventListener('cameraEvent', cameraEvent);
      document.removeEventListener('saveCamera', collectCameraState);
    };
  }, []);

  if (!component) {
    return null;
  }
  const { config, id } = component;
  const modalConfig = getConfig(config, 'modal');

  const handleFieldsChange = (updates) => {
    const newConfig = Utils.updateArrayConfig(config, updates);

    return updateConfig({
      componentId: id,
      updateData: {
        config: newConfig,
      },
    });
  };

  const handleSwitchChange = (checked) => {
    updateFocusMode({
      focusMode: checked,
    });
  };

  const onClose = () => {
    // 清除场景模式标记
    sessionStorage.removeItem('camera');
    easyvConfirm.current?.close();
    updateFocusMode(false);
    hideComponentEditModal(null);
  };

  const onCustomEvents = (updates) => {
    setModelPath(updates);
    setVisible(true);
  };

  const onModelToReplaceChange = ({ content, visible }) => {
    const { path } = modelPath;
    // content
    setVisible(visible);

    if (!visible && path && content) {
      //  update
      const result = handleFieldsChange([
        {
          path,
          value: content,
        },
      ]);
      result && message.success('替换成功');
    }
  };

  return (
    <SpaceModal>
      {/* 导出提示框 */}
      <EasyvModal.Confirm
        title="镜头未保存"
        iconType="warning"
        onOkBtnType="primary"
        content={'当前场景镜头未保存，确认退出吗？'}
        ref={easyvConfirm}
        onOk={() => {
          onClose();
        }}
        onCancel={() => {
          easyvConfirm.current?.close();
        }}
      />
      <div
        className={styles.back}
        onClick={() => {
          const camera = sessionStorage.getItem('camera');
          if (camera) {
            easyvConfirm.current?.show();
          } else {
            onClose();
          }
        }}>
        <i className="icon iconfont icon-btn_arrowsleft" />
        <span>返回主编辑视图</span>
      </div>
      <div className={styles.focusMode}>
        <Space>
          <span>
            专注模式{' '}
            <Tooltip
              overlayStyle={{
                maxWidth: 160,
              }}
              title="专注模式关闭时，场景管理同时渲染画布以及背景图，作为场景镜头编辑的参照">
              <QuestionCircleOutlined className={classNames(styles.icon, 'whiteHover')} />
            </Tooltip>
          </span>
          <Switch checked={focusMode} onChange={handleSwitchChange} />
        </Space>
      </div>
      <div className={styles.config}>
        <div className={styles.title}>
          <span>{modalConfig[0]._displayName || modalConfig[0].displayName}</span>
          <span className={styles.status}>{cameraText[cameraState]}</span>
        </div>
        <div className={styles.content}>
          <EasyGUI
            config={modalConfig}
            onCustomEvents={checkAuth(modules.resource) ? onCustomEvents : null}
            onFieldsChange={handleFieldsChange}
          />
        </div>
      </div>
      {modelPath.value?.data && (
        <ModelToReplace
          accept={modelPath.value.data?.accept}
          visible={visible}
          onChange={onModelToReplaceChange}
        />
      )}
    </SpaceModal>
  );
}

const createContainer = () => {
  const div = document.createElement('div');
  return div;
};

function SpaceModal({ children }) {
  const rootRef = useRef(createContainer());

  useEffect(() => {
    document.body.appendChild(rootRef.current);
    return () => {
      document.body.removeChild(rootRef.current);
    };
  }, []);

  return createPortal(children, rootRef.current);
}

const mapStateToProps = ({ createApp, componentsById }) => {
  const { modalEdit, focusMode } = createApp;

  return {
    modalEdit,
    componentsById,
    focusMode,
  };
};

const mapDispatchToProps = {
  updateConfig: updateComponentConfig,
  hideComponentEditModal: hideComponentEditModal,
  updateFocusMode,
};

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