import React, { useState, useCallback, useEffect } from 'react';
import { Checkbox } from '@easyv/antd';
import classNames from 'classnames';
import isEqual from 'lodash/isEqual';
import { SortableElement, SortableHandle } from 'react-sortable-hoc';
import FilterHeader from '../../RightZoneBar/Filter/ItemHeader';
import FilterContent from '../../RightZoneBar/Filter/ItemContent';
import FilterPreview from './FilterTest';
import styles from './Item.less';
// import { cancelGroupLayers } from 'models/screen';
import message from 'components/message';

const DragHandle = SortableHandle(() => (
  <span className={styles.icon + ' ' + styles.sort}>
    <i className="icon iconfont icon-btn_sort" style={{ fontSize: 20 }} />
  </span>
));

const FilterItem = SortableElement(
  ({
    id,
    enable,
    name = '',
    callbackKeys = [],
    collapsedCode = false,
    content = '',
    componentId,
    usedComponents = [],
    originData,
    onPreviewContent,
    onDelete,
    onSubmit,
    onTrigger,
    drawerStates,
  }) => {
    const [collapsed, setCollapsed] = useState(!collapsedCode);
    const [editable, setEditable] = useState(false);
    const [localName, setLocalName] = useState(name);
    const [localCallbackKeys, setLocalCallbackKeys] = useState(callbackKeys);
    const [localContent, setLocalContent] = useState(content);
    const [previewVisible, setPreviewVisible] = useState(false);
    const seesKey = `${componentId}-${id}`;

    useEffect(() => {
      if (!editable && name !== localName) {
        if (localName) {
          onSubmit({
            id: id,
            name: localName,
          });
        } else {
          message.error('过滤器名称不能为空');
        }
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [editable]);

    const unsaved = !isEqual(localContent, content) || !isEqual(localCallbackKeys, callbackKeys);

    useEffect(() => {
      if (!drawerStates && unsaved) {
        // 关闭的时候 存储规则是 组件id+筛选规则id
        // localName、localCallbackKeys、localContent
        const filterItem = {
          localName,
          localCallbackKeys,
          localContent,
        };
        window.sessionStorage.setItem(seesKey, JSON.stringify(filterItem));
      } else if (drawerStates) {
        // 开启的时候
        let nweLocalContent: any = window.sessionStorage.getItem(seesKey);
        try {
          nweLocalContent = nweLocalContent && JSON.parse(nweLocalContent);
        } catch (err) {
          //
        }
        if (nweLocalContent) {
          nweLocalContent?.localName && setLocalName(nweLocalContent?.localName);
          nweLocalContent?.localContent && setLocalContent(nweLocalContent?.localContent);
          nweLocalContent?.localCallbackKeys &&
            setLocalCallbackKeys(nweLocalContent?.localCallbackKeys);
        }
      }
    }, [drawerStates]);

    const handleCancel = useCallback(() => {
      setCollapsed(true);
      setLocalContent(content);
      setLocalCallbackKeys(callbackKeys);
      removeSession();

      // 数据重置
      setLocalName(name);
      setLocalCallbackKeys(callbackKeys);
      setLocalContent(content);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [id, content, callbackKeys]);

    const removeSession = useCallback(() => {
      // 删除本地存储的未保存信息
      window.sessionStorage.removeItem(seesKey);
    }, []);
    const handleSubmit = useCallback(async () => {
      if (localContent) {
        if (unsaved) {
          const param: any = {
            id,
          };
          if (!isEqual(localContent, content)) {
            param.content = localContent;
          }
          if (!isEqual(localCallbackKeys, callbackKeys)) {
            param.callbackKeys = localCallbackKeys;
          }
          const result = await onSubmit(param);

          if (!result) {
            return;
          }
          // 删除本地存储的未保存信息
          removeSession();
        }

        setCollapsed(true);
      } else {
        message.error('过滤器内容不能为空');
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [id, localContent, localCallbackKeys]);

    const handleDelete = useCallback(() => {
      onDelete(id);
    }, [id, onDelete]);

    const handleTrigger = useCallback(
      (e) => {
        onTrigger(id, e.target.checked);
      },
      [id, onTrigger],
    );

    const handlePreview = useCallback(() => {
      setPreviewVisible(true);
    }, []);

    const handleClose = useCallback(() => {
      setPreviewVisible(false);
    }, []);

    return (
      <li className={styles.container} onMouseLeave={() => setPreviewVisible(false)}>
        <div className={styles.header}>
          <DragHandle />

          <label className={styles.label}>
            <Checkbox
              className={classNames('dark', styles.checkBoxContainer)}
              checked={enable}
              onChange={handleTrigger}
            />
          </label>

          <FilterHeader
            className={styles.right}
            collapsed={collapsed}
            editable={editable}
            unsaved={unsaved}
            name={localName}
            usedComponents={usedComponents}
            onCollapsedChange={setCollapsed}
            onNameChange={setLocalName}
            onEditChange={setEditable}
            onDelete={handleDelete}
          />
        </div>

        <div className={classNames(styles.content, { collapsed: collapsed })}>
          <FilterContent
            showTest={true}
            collapsed={collapsed}
            content={localContent}
            onPreviewContent={onPreviewContent}
            callbackKeys={localCallbackKeys}
            onContentChange={setLocalContent}
            onCallbackKeysChange={setLocalCallbackKeys}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onPreview={handlePreview}
          />
        </div>

        <FilterPreview
          visible={previewVisible}
          onClose={handleClose}
          originData={originData}
          content={localContent}
        />
      </li>
    );
  },
);

export default FilterItem;
