import React, { useMemo, useState, useEffect, useRef } from 'react';

import Wrap from '../wrap/Wrap';
import ChartColorPicker from '../RegularColorPicker/ColorPicker';

import { Popover } from 'antd';

import '../g.scss';
const dom = document; // document
let close = true; // 关掉弹框
let openIndex = -1; // 当前显示弹框index
function ChartColorPick(props: IChartColorPick) {
  const { title = '', change, value, theme } = props;
  const [showColorPickIndex, setShowColorPickIndex] = useState(1); //显示颜色拾取器
  useEffect(() => {
    dom.addEventListener('mousedown', isPopover);
    return () => {
      dom?.removeEventListener('mousedown', isPopover);
    };
  }, []);

  useEffect(() => {
    dom.addEventListener('mousedown', isPopover);
    return () => {
      dom?.removeEventListener('mousedown', isPopover);
    };
  }, [showColorPickIndex]);

  // 判断父元素是否包含某个元素
  const elementContains = (parent, child) =>
    parent !== child && parent?.contains(child);

  // 是否关闭弹框
  const isPopover = (e) => {
    if (openIndex > -1) {
      if (
        e.target &&
        !(
          (document.querySelector('.color-pick-select') &&
            elementContains(
              document.querySelector('.color-pick-select'),
              e.target
            )) ||
          (document.querySelector('.colorPopover') &&
            elementContains(
              document.querySelector('.colorPopover'),
              e.target
            )) ||
          (document.querySelector('.zl-large-screen-setting') &&
            elementContains(
              document.querySelector('.zl-large-screen-setting'),
              e.target
            ))
        )
      ) {
        close = true;
        openIndex = -1;
        setShowColorPickIndex(showColorPickIndex + 1);
      }
    }
  };

  // 切换显示
  const changeColorPickIndex = (index: number) => {
    setShowColorPickIndex(showColorPickIndex + 1);
    close = false;
    openIndex = index;
  };

  // 回调函数，更新最终返回参数
  const handleParams = (params) => {
    if (!params?.visible) {
      setShowColorPickIndex(showColorPickIndex + 1);
      close = true;
      openIndex = -1;
    }
  };

  // 回调函数，更新最终返回参数
  const handleChange = (params, index: number) => {
    change({ value: params, index });
    setShowColorPickIndex(showColorPickIndex + 1);
    close = true;
    openIndex = -1;
  };

  // 图表系列颜色弹层
  const pickChartContent = (
    fillType: string,
    isPure: boolean,
    color: any,
    index: number
  ) => {
    if (typeof color !== 'string') {
      color.colorGroups = [];
      color.colorGroups[0] =
        color?.colorStops[0]?.color || color?.colorStops[0] || color[0];
      color.colorGroups[1] =
        color?.colorStops[1]?.color || color?.colorStops[1] || color[1];
    }
    return (
      <div>
        <ChartColorPicker
          theme={theme}
          type={fillType}
          isPure={isPure}
          value={color}
          gradientConfig={
            typeof color === 'string'
              ? {
                  current: 0,
                  colorGroups: [],
                  angle: 0
                }
              : color
          }
          footer={{ okText: '确认', cancelText: '取消' }}
          handleOk={(params) => handleChange(params, index)}
          handleCancel={(_) => {}}
          handleParams={handleParams}
        />
      </div>
    );
  };

  // 生成颜色
  const buildBgColor = (colors) => {
    if (typeof colors === 'string') {
      return colors;
    } else {
      return commonGradientStyle(colors);
    }
  };
  // 更加渐变色对象生成button样式
  const commonGradientStyle = (colors) => {
    const { colorStops, angle = 0 } = colors || {};
    const [start, end] = colorStops || ['', ''];
    return `linear-gradient(${angle + 90}deg, ${start?.color || start} , ${
      end?.color || end
    } )`;
  };

  const Dom = useMemo(() => {
    return (
      <Wrap>
        <div className="chart-color-pick">
          {value?.map((item, index) => {
            const styleName =
              typeof item?.color === 'string'
                ? 'background'
                : 'backgroundImage';
            return (
              // <Tooltip placement="top" title={item?.title} key={item?.key}>
              <Popover
                placement="bottom"
                content={pickChartContent(
                  item?.fillType,
                  item?.isPure,
                  item?.color,
                  index
                )}
                trigger="click"
                visible={openIndex === index && !close}
                zIndex={1090}
                overlayClassName={`colorPopover ${
                  theme !== 'white' ? 'dark' : 'white'
                }`}
                key={item?.key}
                destroyTooltipOnHide={true}
              >
                <div
                  className="zl-ls-board-chart-color-wrap"
                  onClick={() => changeColorPickIndex(index)}
                >
                  <div
                    className="zl-ls-board-chart-color"
                    style={{
                      [styleName]: buildBgColor(item?.color)
                    }}
                  ></div>
                  <span className="zl-ls-board-chart-title" title={item?.title}>
                    {item?.title}
                  </span>
                </div>
              </Popover>
              // </Tooltip>
            );
          })}
        </div>
      </Wrap>
    );
  }, [title, value, showColorPickIndex]);

  return Dom;
}

export default ChartColorPick;

export interface IChartColorPick {
  title?: string;
  theme?: string;
  change?: Function;
  value?: IChartColors[];
}

export interface IChartColors {
  title?: string;
  key?: string | number;
  color?: string;
  fillType?: string;
  isPure?: boolean;
}
