/*
 * @Author: your name
 * @Date: 2021-12-17 10:12:52
 * @Description:
 * @FilePath: \zl-business\src\components\Unit\colorPick\index.tsx
 */

import React, { useEffect, useState } from 'react';
import ChartColorPicker from '../RegularColorPicker/ColorPicker';

import Wrap from '../wrap/Wrap';
import { Popover } from 'antd';
import { returnClass } from '../unit';

import '../g.scss';
import 'zl-color-pick/dist/zl-color-pick.css';

function LabelColorPick(props: IColorPick) {
  const {
    title = 'label',
    value = '',
    size = 'large',
    change,
    paddingSize = 'normal',
    attrKey,
    wrapStyle = {
      padding: '6px 20px 6px 20px'
    },
    theme = 'white',
    fillType = '',
    isPure = true,
    isShowReset
  } = props;
  const dom = document; // document
  const [close, setClose] = useState(true);
  const [color, setColor] = useState<string | IGradient>('#526CFD');
  const [colorGradient, setColorGradient] = useState<IGradient>({
    current: 0,
    colorGroups: [],
    angle: 0
  });

  useEffect(() => {
    if ((value as IGradient)?.fillType !== 'gradient') {
      setColor(value);
    } else {
      const color = `linear-gradient(${
        (value as IGradient)?.angle + 90 || 90
      }deg, ${(value as IGradient)?.color[0] || '#526CFD'}, ${
        (value as IGradient)?.color[1] || '#526CFD'
      })`;
      setColor(color);
      setColorGradient({
        current: 0,
        colorGroups: (value as IGradient)?.color,
        angle: (value as IGradient)?.angle
      });
    }
  }, [value]);

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

  const isPopover = (e) => {
    if (
      !(
        elementContains(
          document.querySelector('.color-pick-select'),
          e.target
        ) ||
        elementContains(document.querySelector('.colorPopover'), e.target) ||
        elementContains(
          document.querySelector('.zl-large-screen-setting'),
          e.target
        )
      )
    ) {
      setClose(true);
    }
  };

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

  //确认事件
  const handleChange = (params) => {
    change(params);
    setClose(true);
  };

  const content = (
    <div>
      <ChartColorPicker
        theme={theme}
        type={
          (value as IGradient)?.fillType === 'gradient' ? 'gradient' : 'pure'
        }
        isPure={isPure}
        value={value}
        gradientConfig={
          typeof value === 'string'
            ? {
                current: 0,
                colorGroups: [],
                angle: 0
              }
            : colorGradient
        }
        footer={{ okText: '确认', cancelText: '取消' }}
        handleOk={(params) => handleChange(params)}
        handleCancel={(_) => {}}
        handleParams={() => {
          setClose(true);
        }}
      />
    </div>
  );

  return (
    <Wrap wrapStyle={wrapStyle}>
      <div className={returnClass(paddingSize)}>{title}</div>
      <div
        className={
          size === 'normal'
            ? 'zl-large-screen-setting-unit-content'
            : 'zl-large-screen-setting-unit-content-large'
        }
      >
        {isShowReset ? (
          <span className="reset-color-pick" onClick={() =>{
            change('resetColor')
          }}>
            重置
          </span>
        ) : (
          <></>
        )}

        <Popover
          placement="bottom"
          content={content}
          trigger="click"
          overlayClassName={`colorPopover ${
            theme !== 'white' ? 'dark' : 'white'
          }`}
          destroyTooltipOnHide={true}
          zIndex={1090}
          visible={!close}
        >
          <span
            onClick={() => {
              setClose(false);
            }}
            className="zl-label-color-btn"
            style={{ background: color as string }}
          />
        </Popover>
      </div>
    </Wrap>
  );
}

export default LabelColorPick;

export interface IColorPick {
  title: string;
  attrKey: string;
  value: IGradient | string;
  size?: string;
  change?: Function;
  paddingSize?: string;
  wrapStyle?: React.CSSProperties;
  theme?: string;
  fillType?: string;
  isPure?: boolean;
  isShowReset?: boolean;
}

export interface IGradient {
  fillType?: string;
  color?: string[];
  angle?: number;
  position?: number;
  current?: 0;
  colorGroups?: string[];
}
