/* eslint-disable global-require */
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Select, Space, TreeSelect, Empty, Switch, Button, message } from 'antd';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import {
  DeleteOutlined,
  PictureOutlined,
  DesktopOutlined,
  FolderFilled,
  FileOutlined,
  MobileOutlined,
} from '@ant-design/icons';
import { AddPlatformStatus } from '@/services/messagemanage/messagemanage';
import { GetMessageIcon } from '@/services/messagemanage/messagemanage';
import styles from './PlatformConfig.less';
import PreviewModal from '../../schemeDetail/PreviewModal';
const { Option } = Select;
const { TreeNode } = TreeSelect;
const typeList = [
  { name: '通用报警', value: 1 },
  { name: '工单通知', value: 2 },
  { name: '系统通知', value: 3 },
  { name: '自定义', value: 4 },
];
const modules = {
  // toolbar: { container: '#toolbar' },
  toolbar: [
    [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],
    [{ color: [] }, { background: [] }],
    [{ font: [] }],
    [{ align: [] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
    ['clean'], // 清空
  ],
};
const defaultWebIcon = require('../../../../../assets/images/icons/imgNone.png'); // 默认图标
const PlatformConfig = props => {
  const { menuWebList, menuMoblieList, formValue, id } = props;
  const [iconMaskShow, setIconMaskShow] = useState(false);
  const [previewModal, setPreviewModal] = useState(false); // 图片选择
  const [imgDataList, setImgDataList] = useState([]);
  const [editor, setEditor] = useState(null);
  // 编辑器内容
  const [html, setHtml] = useState();
  const toolbarConfig = {};
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {},
      lineHeightList: ['1', '1.5', '2', '2.5'],
    },
  };
  const [form] = Form.useForm();
  useEffect(() => {
    getMessageIcon();
    getFormData();
  }, []);
  const getFormData = () => {
    console.log(formValue, 'formValue');
    if (formValue) {
      form.setFieldsValue({
        ...formValue,
        PlatformIcon: `${window.location.origin}/${formValue.PlatformIcon}`,
        PlatformStatus: formValue.PlatformStatus === 1,
      });
      setHtml(formValue.PlatformContent);
      if (!formValue?.PlatformIcon) {
        form.setFieldsValue({ PlatformIcon: defaultWebIcon });
      }
    }
  };
  // 获取图片库
  const getMessageIcon = () => {
    GetMessageIcon().then(res => {
      setImgDataList(res.data);
    });
  };
  const callBackSubmit = value => {
    console.log(value, 'lvaue');
    form.setFieldsValue({ PlatformIcon: `${window.location.origin}/${value}` });
  };
  // 监听表单
  const changeValue = (changedFields, allFields) => {
    // if (Object.keys(changedFields)[0] === 'PlatformContent') {
    //   let regex = /\{@(.+?)\}/g;
    //   let originalList = allFields.lines || [];
    //   let list = changedFields.PlatformContent.getHtml()
    //     .match(regex)
    //     ?.map(item => {
    //       let Name = item.substring(2, item.length - 1);
    //       let orgItem = originalList.find(ele => ele.Name === Name);
    //       return {
    //         Name,
    //         Description: orgItem ? orgItem.Description : '',
    //         DefaultValue: orgItem ? orgItem.DefaultValue : '',
    //       };
    //     });
    //   if (list) {
    //     form.setFieldsValue({ lines: list });
    //   } else {
    //     form.setFieldsValue({ lines: [] });
    //   }
    // }
  };
  const mapTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    let icon;
    let value = org.id;
    if (org.menuType === 'Web4singleStation') {
      value = org.stationID;
      icon = <DesktopOutlined />;
    }
    if (org.menuType === 'Web4MenuGroup') {
      value = org.id;
      icon = <FolderFilled />;
    }
    if (org.menuType === 'Web4Menu') {
      icon = <FileOutlined style={{ color: '#1890ff' }} />;
      value = org.pageUrl;
    }

    return (
      <TreeNode
        value={value}
        title={org.text}
        key={value}
        icon={icon}
        disabled={org.menuType !== 'Web4Menu'}
      >
        {haveChildren ? org.children.map(item => mapTree(item)) : null}
      </TreeNode>
    );
  };
  const mapAppTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    let icon;
    let value = org.id;

    if (org.menuType === 'MiniAppsingleStation') {
      value = org.stationID;
      icon = <MobileOutlined />;
    }
    if (org.menuType === 'MiniAppMenuGroup' || org.menuType === '"MiniAppMenuGroupTwo"') {
      value = org.id;
      icon = <FolderFilled />;
    }
    if (org.menuType === 'MiniAppMenuThree' || org.menuType === 'MiniAppMenu') {
      icon = <FileOutlined style={{ color: '#1890ff' }} />;
      value = org.pageUrl || org.id;
    }

    return (
      <TreeNode
        value={value}
        title={org.text}
        icon={icon}
        key={value}
        disabled={org.menuType !== 'MiniAppMenuThree' && org.menuType !== 'MiniAppMenu'}
      >
        {haveChildren ? org.children.map(item => mapAppTree(item)) : null}
      </TreeNode>
    );
  };
  const editorChange = editor => {
    let regex = /\{@(.+?)\}/g;
    let originalList = form.getFieldValue('lines') || [];
    let list = editor
      .getHtml()
      .match(regex)
      ?.map(item => {
        let Name = item.substring(2, item.length - 1);
        let orgItem = originalList.find(ele => ele.Name === Name);
        return {
          Name,
          Description: orgItem ? orgItem.Description : '',
          DefaultValue: orgItem ? orgItem.DefaultValue : '',
        };
      });
    if (list) {
      form.setFieldsValue({ lines: list });
    } else {
      form.setFieldsValue({ lines: [] });
    }
    setHtml(editor.getHtml());
  };
  const onFinish = () => {
    if (!id) {
      message.error('请保存基础信息');
      return;
    }
    form.validateFields().then(values => {
      console.log(values, 'values');
      let value = JSON.parse(JSON.stringify(values));
      console.log(value);
      let PlatformIcon =
        value.PlatformIcon === defaultWebIcon ? '' : new URL(value.PlatformIcon).pathname;
      PlatformIcon = PlatformIcon.substring(1);
      console.log(PlatformIcon, 'PlatformIcon');
      if (value)
        AddPlatformStatus({
          ...value,
          PlatformIcon,
          PlatformStatus: value.PlatformStatus ? 1 : 0,
          PlatformContent: html,
          id,
        }).then(res => {
          if (res.code === 0) {
            message.success('保存成功');
          } else {
            message.error(res.msg);
          }
        });
    });
  };
  return (
    <div>
      <Form
        form={form}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onValuesChange={changeValue}
        labelAlign="left"
      >
        <div style={{ display: 'flex' }}>
          {/* <Form.Item
            label="消息类型"
            name="PlatformType"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            style={{ width: '400px', marginRight: '15px', display: 'block' }}
          >
            <Select placeholder="请选择消息类型" allowClear>
              {typeList.map(item => (
                <Option value={item.value} key={item.value}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item> */}
          <Form.Item
            label="消息标题"
            name="PlatformTitle"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Input placeholder="请填写消息标题" />
          </Form.Item>
          <Form.Item
            label="是否开启"
            name="PlatformStatus"
            valuePropName="checked"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>
        </div>
        <Form.Item
          label="网页跳转路径"
          name="PlatformWebUrl"
          style={{ display: 'block', width: '1200px' }}
        >
          <TreeSelect
            showSearch
            treeNodeFilterProp="title"
            treeNodeLabelProp="value"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择功能路径"
            allowClear
            treeDefaultExpandAll
            treeIcon
          >
            {menuWebList ? (
              menuWebList.map(item => mapTree(item))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </TreeSelect>
        </Form.Item>
        <Form.Item
          label="APP跳转路径"
          name="PlatformAppUrl"
          style={{ display: 'block', width: '1200px' }}
        >
          <TreeSelect
            showSearch
            treeNodeFilterProp="title"
            treeNodeLabelProp="value"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择功能路径"
            allowClear
            treeDefaultExpandAll
            treeIcon
          >
            {menuMoblieList ? (
              menuMoblieList.map(item => mapAppTree(item))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </TreeSelect>
        </Form.Item>
        <Form.Item
          label="视频地址"
          name="PlatformVideoUrl"
          style={{ display: 'block', width: '1200px' }}
        >
          <Input placeholder="请填写视频地址" />
        </Form.Item>
        <Form.Item label="图标" style={{ display: 'block' }}>
          <div
            className={styles.formImg}
            onMouseEnter={() => {
              if (form.getFieldValue('PlatformIcon') !== defaultWebIcon) {
                setIconMaskShow(true);
              }
            }}
            onMouseLeave={() => setIconMaskShow(false)}
          >
            <div className={styles.mask} style={{ display: iconMaskShow ? 'flex' : 'none' }}>
              <DeleteOutlined
                className={styles.icon}
                onClick={() => form.setFieldsValue({ PlatformIcon: defaultWebIcon })}
              />
              <PictureOutlined className={styles.icon} onClick={() => setPreviewModal(true)} />
            </div>
            <Form.Item name="PlatformIcon" valuePropName="src" initialValue={defaultWebIcon}>
              <img alt="" onClick={() => setPreviewModal(true)} />
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item
          label="内容"
          style={{ display: 'block', width: '1200px', height: '350px', marginBottom: '45px' }}
        >
          <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: '1px solid #ccc' }}
            />
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={editor => editorChange(editor)}
              mode="default"
              style={{ height: '250px', overflowY: 'hidden' }}
            />
          </div>
          {/* <ReactQuill
            style={{ height: '150px' }}
            placeholder="请输入内容"
            modules={modules}
            theme="snow" // 主题
          /> */}
        </Form.Item>
        <Form.List name="lines">
          {fields => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Space
                  key={key}
                  style={{
                    display: 'flex',
                    marginBottom: 8,
                  }}
                  align="baseline"
                >
                  <Form.Item
                    {...restField}
                    label="参数名"
                    name={[name, 'Name']}
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                  >
                    <Input readOnly />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'Description']}
                    label="含义"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    rules={[
                      {
                        required: true,
                        message: '请填写含义',
                      },
                    ]}
                  >
                    <Input placeholder="请填写含义" />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'DefaultValue']}
                    label="默认值"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                  >
                    <Input placeholder="请填写默认值" />
                  </Form.Item>
                  {/* <MinusCircleOutlined onClick={() => remove(name)} /> */}
                </Space>
              ))}
              {/* <Form.Item>
                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                  Add field
                </Button>
              </Form.Item> */}
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" onClick={onFinish}>
            保存
          </Button>
        </Form.Item>
      </Form>
      <PreviewModal
        visible={previewModal}
        onCancel={() => {
          setPreviewModal(false);
        }}
        keepImgeUrl={form.getFieldValue('PlatformIcon')?.replace(`${window.location.origin}/`, '')}
        imgDataList={imgDataList}
        callBackSubmit={callBackSubmit}
      />
    </div>
  );
};

export default PlatformConfig;