import React, { useState, useEffect,useCallback } from 'react';
import GradientColorPicker from './GradientColorPicker';
import TypeSelect from './TypeSelect';
import CommonColorPicker from './CommonColorPicker';
// import { ColorGetPoint } from './ColorGetPoint'
import useEyeDropper from 'use-eye-dropper'
import Footer from './Footer';
import { Divider ,message} from 'antd';
import './index.scss';
import Icon from 'src/components/Icon/index';

/**
 * 颜色拾取器组件
 * @param theme 主题字段
 * @param type 填充类型
 * @param value 色值
 * @param handlePopoverVisible Popover显隐回调函数
 * @param handleOk 确认修改回调函数
 * @param handleCancel 取消修改回调函数
 * @param gradientConfig 渐变配置项
 * @param footer 底部配置
 * @param gradientDisabled 禁用渐变色
 * @return {*}
 * @constructor
 */
const ColorPicker = ({
  theme = 'white',
  type,
  isPure = true, // 用于不需要渐变的颜色控件
  value = '',
  handleOk,
  handleCancel,
  handleParams,
  gradientConfig = { current: 0, colorGroups: [], angle: 0 },
  footer
}: IColorPicker) => {
  // 底部操作区配置
  const { okText = '确定', cancelText = '取消' } = footer || {};
  // 渐变填充区域配置
  let {
    current = 0,
    colorGroups,
    angle = 0
  } = gradientConfig || { current: 0, colorGroups: [], angle: 0 };
  // 默认颜色组
  let defaultColorGroups = new Array(2).fill('#5B8FF9');
  if (Array.isArray(colorGroups) && colorGroups.length > 0) {
    defaultColorGroups = defaultColorGroups?.map(
      (item, index) => colorGroups?.[index] ?? item
    );
  }
  const { open, close, isSupported } = useEyeDropper()
  // 当前颜色填充类型
  const [fillType, setFillType] = useState<string>(type);

  // 纯色颜色状态
  const [pureColor, setPureColor] = useState<string | IGradient>(value);

  // 渐变色状态 Array gradientColor[0]--开始色 gradientColor[1]--结束色
  const [gradientColor, setGradientColor] =
    useState<string[]>(defaultColorGroups);

  // 渐变色状态 angle--角度
  const [gradientAngle, setGradientAngle] = useState<number>(angle);

  // 渐变色选中设置（开始点或结束点）
  const [activePos, setActivePos] = useState<number>(current);
  const [error, setError] = useState()

//   const colorChange = (color: string) => {
//     onColorChange(color)
// }

// const colorPickerPoint = new ColorGetPoint(colorChange)
// const picker = () => {
  // if (colorPickerPoint) {
  //   colorPickerPoint.open()
  // }
  // }
  const pickColor = useCallback(() => {
    const ua=navigator.userAgent.toLocaleLowerCase();
    if (ua.indexOf("chrome") > -1 || ua.indexOf('opr') > -1) {
    const openPicker = async () => {
      try {
        const color = await open()
        setPureColor(color.sRGBHex)
      } catch (e) {
        if (!e.canceled) setError(e)
      }
    }
    openPicker()
    } else {
      message.warning('该浏览器暂不支持拾色')
      return;
    }
  }, [open])

  // 初始化状态变量
  const initState = () => {
    setFillType(type);
    setPureColor(value);
    setGradientColor(defaultColorGroups);
    setGradientAngle(angle);
    setActivePos(current);
  };

  // 纯色和渐变色改变时触发
  const onGradientChange = ({ angle, position }: IGradient) => {
    typeof position === 'number' && setActivePos(position);
    typeof angle === 'number' && setGradientAngle(angle);
  };

  // 公共颜色区域，选中时触发
  const onColorChange = (val: string) => {
    let colorParam: string | string[] = val;
    if (fillType === 'gradient') {
      // 获取修改后的渐变色组
      const colorGroup = gradientColor.map((item, index) => {
        if (typeof item !== 'string') {
          item = '#5B8FF9';
        }
        if (activePos === index) {
          item = val;
        }
        return item;
      });
      // 当所选类型为gradient 设置渐变色相关变量
      setGradientColor(colorGroup);
      colorParam = colorGroup;
    } else {
      // 设置纯色
      setPureColor(val);
    }

    if (!footer) {
      typeof handleParams === 'function' &&
        handleParams({ params: { ...getParams, color: colorParam } });
    }
  };

  // 选择颜色填充类型
  const onSelectFillType = (label: string) => {
    setFillType(label);
    setPureColor(value);
    setGradientColor(defaultColorGroups);
  };

  // 获取最终返回参数
  const getParams = {
    gradient: {
      fillType: fillType,
      color: gradientColor,
      current: activePos,
      angle: gradientAngle
    },
    pure: {
      fillType: fillType,
      color: pureColor
    }
  }[fillType] || {
    color: pureColor
  };

  // 确认操作
  const onOk = () => {
    typeof handleOk === 'function' && handleOk(getParams);
    typeof handleParams === 'function' && handleParams({ visible: false });
  };

  // 取消操作
  const onCancel = () => {
    initState();
    typeof handleCancel === 'function' && handleCancel();
    typeof handleParams === 'function' && handleParams({ visible: false });
  };

  // 组件挂载时，根据入参初始化相关变量
  useEffect(() => {
    initState();
  }, []);

  useEffect(() => {
    initState();
  }, [type, value]);

  useEffect(() => {
    initState();
  }, [JSON.stringify(gradientConfig)]);

  return (
    <div className={`colorPicker ${theme !== 'white' ? 'dark' : 'white'}`}>
      {fillType && !isPure ? (
        <TypeSelect
          // theme="white"
          // // dark={theme !== 'white'}
          // dark={false}
          theme={theme !== 'white' ? 'dark' : 'white'}
          dark={theme !== 'white'}
          value={fillType}
          handleSelect={onSelectFillType}
        />
      ) : null}
      {fillType === 'gradient' ? (
        <GradientColorPicker
          current={activePos}
          color={gradientColor}
          angle={gradientAngle}
          handleChange={onGradientChange}
        />
      ) : null}
      {fillType && !isPure && <Divider className="divider" />}
      <CommonColorPicker
        dark={theme !== 'white'}
        // dark={false}
        value={(fillType === 'gradient' ? gradientColor[activePos] : pureColor) as string}
        handleChange={onColorChange}
      /> 
      {/* <Icon name='icon-xiguan' classname='penpoint' style={{ color: theme === 'white' ? 'black' : 'white' }} click={pickColor}/> */}
      {footer ? (
        <>
          <Divider className="divider" />
          <Footer
            okText={okText}
            cancelText={cancelText}
            onOk={onOk}
            onCancel={onCancel}
          />
        </>
      ) : null}
    </div>
  );
};

export default ColorPicker;


export interface IColorPicker {
  theme?: string;
  type?: string;
  isPure?: boolean;
  value: string |IGradient;
  handleOk: Function;
  handleCancel?: Function;
  handleParams: Function;
  gradientConfig?: IGradient;
  footer?: IFooter;
}

export interface IFooter {
  okText?: string;
  cancelText?: string;
}

// export interface IGradientConfig {
//   current: number;
//   colorGroups: string[];
//   angle: number;
// }

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