import React, { useMemo } from 'react';
import { Controlled } from 'react-codemirror2';
import { useState } from 'react';
import { Button, message, Popover, Modal } from 'antd';
import { saveAs } from 'file-saver';
import styles from './index.less';
import { isDev, useGetRect } from 'editorUtils/tool';
import { SaveOutlined, CodeOutlined, DeleteOutlined, SketchOutlined } from '@ant-design/icons';
import { useHotkeys } from 'react-hotkeys-hook';
import { connect } from 'dva';
import { StateWithHistory } from 'redux-undo';
import PageForm from './PageForm';

require('codemirror/mode/xml/xml');
require('codemirror/mode/javascript/javascript');

const serverUrl = isDev ? 'http://localhost:3000' : 'http://localhost:3000';

const IdeTemplateEditor = ({
  location,
  dispatch,
  ideTemplateEditor
}) => {

  const { htmlContent, isNewPage, __pageConfig, theme, pageId, pageConfig, previewUrl } = ideTemplateEditor;

  console.log(htmlContent, '@@@')
  const [isUpdate, setUpdate] = useState(false);
  const [cursor, setCursor] = useState<CodeMirror.Position>({ line: 1, ch: 1 });
  const [data, setData] = useState<{ data: string }>({ data: htmlContent });
  const handleChange = (
    _editor: CodeMirror.Editor,
    _data: CodeMirror.EditorChange,
    value: string,
  ) => {
    // setData({ data: value });
    dispatch({
      type: 'ideTemplateEditor/updateState',
      payload: {
        htmlContent: value
      }
    })
  };
  const fetchPage = (_htmlContent) => {
    dispatch({
      type: 'ideTemplateEditor/updatePreview',
      payload: {
        id: pageId,
        html: _htmlContent || htmlContent
      }
    })
  };
  const downLoadHtml = () => {
    var file = new File([data.data], `${Date.now()}.html`, { type: 'text/html;charset=utf-8' });
    saveAs(file);
  };

  const onCursorChange = (_editor: CodeMirror.Editor, data1: CodeMirror.Position) => {
    const { line, ch } = data1;
    setCursor({ line, ch });
  };

  useHotkeys<HTMLDivElement>(
    'ctrl+s',
    event => {
      fetchPage();
      event.preventDefault();
    },
    [data],
  );

  const editHotKey = useMemo(() => {
    return (editor: CodeMirror.Editor, event: KeyboardEvent) => {
      if (event.ctrlKey && event.key === 's') {
        fetchPage(editor.getValue());
        event.preventDefault();
      }
    };
  }, [fetchPage]);

  const CodeMirrorRender = useMemo(() => {
    return (
      <Controlled
        className={theme === 'wap' ? styles.codeWrap : styles.codePcWrap}
        value={htmlContent}
        options={{
          mode: 'xml',
          theme: 'material',
          lineNumbers: true,
        }}
        onBeforeChange={handleChange}
        cursor={cursor}
        onCursor={onCursorChange}
        onKeyDown={editHotKey}
      />
    );
  }, [cursor, htmlContent, editHotKey]);

  const rect = useGetRect();
  const height = useMemo(() => {
    let res = rect.height - 42 - 1; //-1防止差值产生滚动条
    return res < 694 ? 694 : res;
  }, [rect.height]);

  const phoneHeight = useMemo(() => {
    //let res = rect.height - 42 - 30 - 1; //30是其上边距
    //return res < 694 ? 694 : res;
    return 694; //大屏幕过长，维持高度，需要变高另外处理
  }, []);
  const iframeHeight = useMemo(() => {
    return phoneHeight - 30 - 12 - 12; //上边距30 上下padding 12
  }, [phoneHeight]);


  const onSave = (values, flag) => {
    dispatch({
      type: 'ideTemplateEditor/updateState',
      payload: {
        pageConfig: values
      }
    })
    if (flag) {
      dispatch({
        type: 'ideTemplateEditor/updateState',
        payload: {
          __pageConfig: values
        }
      })
    }
  }
  const delPage = () => {
    if (isNewPage) {
      Modal.confirm({
        width: 600,
        title: '删除',
        content: '是否要删除？',
        cancelText: '取消',
        okText: '确认',
        onOk: () => {
          dispatch({
            type: 'ideTemplateEditor/delPage',
            payload: {
              type: theme === 'wap' ? 'wap' : 'pc',
              id: pageId
            }
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      })
    } else {
      return false;
    }
  }
  const savePage = () => {
    dispatch({
      type: 'ideTemplateEditor/savePage',
      payload: {
        client: theme === 'wap' ? 'wap' : 'pc',
        content: htmlContent,
        html_param: JSON.stringify({
          pageConfig: pageConfig
        }),
        id: pageId,
        param: {
          online_consult: pageConfig?.online_consult,
          sub_status: pageConfig?.sub_status
        },
        sub_status: pageConfig?.sub_status,
        type: 3
      }
    });
  }
  return (
    <div className={styles.wrap}>
      <div className={styles.header}>
        <div className={styles.logoArea}>
          <div className={styles.logo} title="LWJ-Editor">
            <a>
              <img style={{ width: 120 }} src='https://static.liweijia.com/liweijia/pc/common/images/logo.svg' alt="LWJ-Editor" />
            </a>
          </div>
          <div className={styles.logoText}>| 在线代码编辑器</div>
        </div>
        <div className={styles.operationBar}>
        {theme === 'wap' && <Button
            type="primary"
            title="保存（ctrl+s）"
            onClick={() => fetchPage()}
            style={{ marginRight: '10px' }}
          >
            <SaveOutlined />
          </Button>}

          <Button type="primary" ghost onClick={savePage} style={{ marginRight: '12px' }}>
            <SketchOutlined />
          保存页面
        </Button>
        </div>
      </div>
      <div className={styles.contentWrap} style={{ height: `${height}px`, position: 'relative' }}>
        <div className={theme === 'wap' ? styles.codeWrap : styles.codePcWrap} style={{ height: `${height}px`, position: 'relative' }}>
          {CodeMirrorRender}
        </div>

        {theme === 'wap' && <div key={previewUrl} className={styles.previewWrap} style={{ height: `${phoneHeight}px` }}>
          <iframe
            title="preview"
            src={previewUrl}
            style={{
              width: '100%',
              height: `${iframeHeight}px`,
              margin: 0,
              padding: 0,
              border: 'none',
            }}
          ></iframe>
        </div>}
      </div>
    </div>
  );
}

export default connect((state: StateWithHistory<any>) => {
  return { ideTemplateEditor: state.ideTemplateEditor };
})(IdeTemplateEditor);
