import React, { useState, useEffect, useLayoutEffect } from 'react';
import { Modal, Row, Col, Space, Form, Input, Select, message, Upload, Button } from 'antd';

import { ScissorOutlined } from '@ant-design/icons';

import { getAgent } from '@/services/agent';

import { postOrPutNotice } from '@/services/notice';

import { uploadFile } from '@/services/user';

// import ReactWEditor from 'wangeditor-for-react';

// 引入编辑器组件
import BraftEditor, { ControlType, ExtendControlType, ImageControlType } from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';

import { ContentUtils } from 'braft-utils';

import { baseUrl } from '@/utils/request';

import type { noticeModalProps } from './data';

import type { Dispatch } from 'umi';

import { useIntl } from 'react-intl';

import { Role } from '@/models/user';

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 },
};

// 定义rem基准值
const sizeBase = 23.4375;

interface IProps {
  dispatch: Dispatch;
  roleList: Role[];
}

interface EditorDemoProps {
  editorContent: string;
  changeContent: (content: string) => void;
}

class EditorDemo extends React.Component<EditorDemoProps> {
  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(null),
    editorInstance: null,
  };

  async componentDidMount() {
    // 假设此处从服务端获取html格式的编辑器内容
    const htmlContent = this.props.editorContent;

    console.log(htmlContent, 'htmlContenthtmlContenthtmlContent');

    // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
    this.setState({
      editorState: BraftEditor.createEditorState(htmlContent),
    });

    console.log(this.state.editorInstance.getValue(), '222');
  }

  submitContent = async () => {
    // 在编辑器获得焦点时按下ctrl+s会执行此方法
    // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
    // const htmlContent = this.state.editorState.toHTML()
    // const result = await saveEditorContent(htmlContent)
  };

  handleEditorChange = (editorState) => {
    console.log(editorState.toHTML(), 'editorState');

    this.setState({ editorState });

    this.props.changeContent(editorState.toHTML());
  };

  handleChange = ({ fileList }: { fileList: Record<string, any> }): void => {
    console.log(fileList, 'fileList');
    const len = fileList.length - 1;
    if (fileList[len]?.status === 'done') {
      if (fileList[len].response.code === 0) {
        console.log(fileList[len].response.data, ' fileList[len].response.data');

        this.setState({
          editorState: ContentUtils.insertMedias(this.state.editorState, [
            {
              type: 'IMAGE',
              url: fileList[len].response.data + `?imageView2/1/w/343/h/192`,
              width: '343px',
              height: '192px',
            },
          ]),
        });
      }
    }
  };

  circleImg = (mediaData) => {
    console.log(mediaData, 'mediaDatamediaData');

    const { url }: { url: string } = mediaData;
    if (url.includes('?imageView2')) {
      mediaData.url = mediaData.url.split('?imageView2')[0];
    } else {
      mediaData.url =
        mediaData.url +
        `?imageView2/1/w/${parseInt(mediaData.width)}/h/${parseInt(mediaData.height)}`;
    }
  };

  render() {
    const controls = [
      'bold',
      'italic',
      'underline',
      'text-color',
      'separator',
      'list-ul',
      'list-ol',
      'emoji',
      'text-indent',
      'headings',
      'clear',
      'hr',
      'blockquote',
      'font-size',
      'line-height',
    ];

    const extendControls: ExtendControlType[] = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload
            accept="image/*"
            action={`${baseUrl}/forum/file/uploadImage`}
            showUploadList={false}
            // customRequest={this.uploadHandler}
            onChange={this.handleChange}
          >
            <button
              type="button"
              className="control-item button upload-button"
              data-title="插入图片"
            >
              插入图片
            </button>
          </Upload>
        ),
      },
    ];

    const hooks = {
      'set-image-size': ({ width, height }) => {
        console.log(width, 'widthwidth');
        let _width = width;
        if (_width === undefined) {
          _width = '343rpx';
        }
        if (parseInt(_width) !== 343) {
          message.warning('图片宽度默认为343');
          return false;
        }

        return {
          width: _width,
          height: height,
        };
      },
    };

    const imageControls: ImageControlType[] = [
      // 'float-left',
      // 'float-right',
      // {
      //   text: '裁剪图片',
      //   render: (mediaData) => (
      //     <a>
      //       <ScissorOutlined color="#fff" onClick={() => this.circleImg(mediaData)} />
      //     </a>
      //   ),
      // },
      'size',
      'remove',
    ];

    const { editorState } = this.state;

    return (
      <div className="my-component">
        <BraftEditor
          hooks={hooks}
          imageResizable={false}
          style={{ border: '1px solid #d9d9d9', width: '375px' }}
          controls={controls}
          imageControls={imageControls}
          ref={(instance) => (this.state.editorInstance = instance)}
          extendControls={extendControls}
          value={editorState}
          onChange={this.handleEditorChange}
        />
      </div>
    );
  }
}

type NoticeModalProps = noticeModalProps | IProps;

const NoticeModal: React.FC<noticeModalProps & IProps> = ({
  GetNotice,
  type,
  closeModal,
  visible,
  curNoticeData,
  dispatch,
  roleList,
}) => {
  console.log(roleList, 'roleListroleList');

  const [form] = Form.useForm();

  const [label, setLabel] = useState('');

  const [content, setContent] = useState('');

  // editContent 反填
  const [editContent, setEditContent] = useState<string>('');

  // 反填表单时的值
  const [editForm, setEditForm] = useState({});

  useEffect(() => {
    onFill();
    dispatch({
      type: 'user/getRoleList',
      payload: {
        curPage: 1,
        passSize: 100,
      },
    });
  }, []);

  // 新增或者编辑公告
  const PostOrPutNotice = async (record: any): Promise<void> => {
    const { code, data } = await postOrPutNotice({ ...record });
    if (code === 0 && data) {
      message.success(type === 1 ? '编辑成功' : '新增成功');
    } else {
      message.success(type === 1 ? '编辑失败' : '新增失败');
    }
    closeModal();
    GetNotice();
  };

  // 反填表单
  const onFill = (): void => {
    console.log(curNoticeData, '反填表单');
    const $par = { ...curNoticeData };
    form.setFieldsValue($par);
    setEditForm($par);
    setEditContent(curNoticeData.content);
  };

  const onFinish = (values: any) => {
    console.log(values, 'values');
    console.log(content, 'contentcontent');

    if (content === '<p></p>') {
      message.error('请填写公告内容');
      return;
    }
    let $par;
    if (type === 1) {
      $par = {
        ...editForm,
        ...values,
        userIds: ['ALL'],
        roles: values.roles,
        type: 'ANN',
        methodType: type,
        content,
      };
    } else {
      $par = {
        ...values,
        userIds: ['ALL'],
        roles: values.roles,
        type: 'ANN',
        methodType: type,
        content,
      };
    }

    console.log($par);

    PostOrPutNotice($par);
  };

  // 提交表单
  const onsubmit = () => form.submit();

  // 设置标题
  const changeLabel = (e: React.ChangeEvent<HTMLInputElement>): void => setLabel(e.target.value);

  // 内容
  const changeContent = (content: string): void => setContent(content);

  return (
    <Modal
      width="700px"
      visible={visible}
      title="发布公告"
      onOk={() => onsubmit()}
      onCancel={closeModal}
    >
      <Form {...layout} form={form} onFinish={onFinish}>
        <Form.Item
          name="roles"
          label="可看人员:"
          rules={[{ required: true, message: '请选择可看人员' }]}
        >
          <Select style={{ width: '375px' }} mode="multiple">
            {roleList.length &&
              roleList.map((item: Record<string, any>) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.label}
                </Select.Option>
              ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="label"
          label="公告标题:"
          rules={[{ required: true, message: '请填写公告标题' }]}
        >
          <Input style={{ width: '375px' }} onChange={changeLabel} maxLength={80}></Input>
        </Form.Item>
        <Form.Item name="content" label="公告内容:">
          <EditorDemo key={editContent} changeContent={changeContent} editorContent={editContent} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default NoticeModal;
