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

import Wrap from '../wrap/Wrap';
import FooterBtn from '../FooterBtn/index';
import LabelColorPick from '../colorPick/index';
import LabelSelect from '../LabelSelect/index';
import ChartColorPicker from '../RegularColorPicker/ColorPicker';
import ToInput from './twoInput';
import { Popover, InputNumber } from 'antd';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';

import '../g.scss';

const LabelPopoverTab = (props: IProps) => {
  const {
    wrapStyle = { padding: '6px 20px 6px 20px' },
    title,
    tabTitle,
    tableList,
    attrKey,
    change,
    quantileValue,
    showColor,
    selectList,
    selectValue,
    linearValue,
    theme = 'white',
    fillType = '',
    isPure = false,
    tabActiveValue = 'linear',
    isShowTab = false,
    quantizeSelectList,
    quantizeSelectValue,
    quantizeValueList,
    quantizeNum
  } = props;
  const dom = document; // document
  const [isVisible, setIsVisible] = useState(false); //显隐
  const [current, setCurrent] = useState(tabActiveValue || 'linear'); //当前选中
  const [close, setClose] = useState(true);
  const [close2, setClose2] = useState(true);
  const [numValue, setNumValue] = useState(quantizeNum);

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

  useEffect(() => {
    // 弹窗开启时更新当前选中
    if (isShowTab) {
      setCurrent(tabActiveValue || 'linear');
    }
  }, [isShowTab]);

  useEffect(() => {
    setNumValue(quantizeNum);
  }, [quantizeNum]);

  const colorType = () => {
    if (showColor?.length > 1) {
      return {
        backgroundImage: `linear-gradient(to right, ${showColor[0]},${showColor[1]} )`
      };
    } else {
      return {
        background: showColor[0]
      };
    }
  };

  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
        )
      )
    ) {
      setClose2(true);
      setClose(true);
    }
  };

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

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

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

  const content = (
    <div className="zl-ls-tab-wrap">
      <div className="zl-ls-tab-wrap-top">
        <div className="zl-ls-tab-content">
          <div className="zl-ls-tab-content-wrap">
            <span>{title}</span>
            <div className="zl-large-screen-component-tabs-wrapper">
              {tableList?.length > 0 &&
                tableList?.map((item, index) => {
                  return (
                    <div
                      key={index}
                      className="zl-large-screen-component-tabs-item"
                      onClick={() => {
                        change(item?.key, 'tableClick');
                        setCurrent(item?.key);
                      }}
                    >
                      <span
                        className={`zl-large-screen-component-tabs-item-small ${
                          current === item?.key
                            ? 'zl-large-screen-tas-active'
                            : ''
                        }`}
                      >
                        {item?.title}
                      </span>
                    </div>
                  );
                })}
            </div>
          </div>
          {current === 'quantile' ? (
            <LabelColorPick
              theme={theme}
              title="固定颜色"
              value={quantileValue[0]}
              size="normal"
              change={(params) => {
                change(params, 'quantileColor');
              }}
              wrapStyle={{}}
              attrKey={attrKey}
              paddingSize="normal"
            />
          ) : (
            <></>
          )}
          {current === 'linear' ? (
            <>
              <LabelSelect
                title="配色模版"
                value={selectValue}
                selectList={selectList}
                change={(value) => change(value, 'linearSelect')}
                size="normal"
                wrapStyle={{}}
                paddingSize="normal"
                suffixIcon="icon-arrow-down-filling"
                customStyle={{ width: '176px' }}
              />
              <div className="zl-ls-linear-color">
                <Popover
                  placement="bottom"
                  content={content1(linearValue[0], 'firstColor')}
                  trigger="click"
                  overlayClassName={`colorPopover ${
                    theme !== 'white' ? 'dark' : 'white'
                  }`}
                  destroyTooltipOnHide={true}
                  zIndex={1090}
                  visible={!close}
                >
                  <span
                    className="zl-ls-linear-color-select"
                    style={{ background: linearValue[0] }}
                    onClick={() => {
                      setClose(false);
                    }}
                  />
                </Popover>
                <span
                  className="zl-ls-linear-color-show"
                  style={{
                    backgroundImage: `linear-gradient(to right, ${linearValue[0]} , ${linearValue[1]}`
                  }}
                />
                <Popover
                  placement="bottom"
                  content={content1(linearValue[1], 'secondColor')}
                  trigger="click"
                  overlayClassName={`colorPopover ${
                    theme !== 'white' ? 'dark' : 'white'
                  }`}
                  destroyTooltipOnHide={true}
                  zIndex={1090}
                  visible={!close2}
                >
                  <span
                    className="zl-ls-linear-color-select"
                    style={{ background: linearValue[1] }}
                    onClick={() => {
                      setClose2(false);
                    }}
                  />
                </Popover>
              </div>
            </>
          ) : (
            <></>
          )}
          {current === 'threshold' ? (
            <>
              <LabelSelect
                title="配色模版"
                value={quantizeSelectValue}
                selectList={quantizeSelectList}
                change={(value) => change(value, 'quantizeSelect')}
                size="normal"
                wrapStyle={{}}
                paddingSize="normal"
                suffixIcon="icon-arrow-down-filling"
                customStyle={{ width: '176px' }}
              />
              <div className="quantizeColor">
                {quantizeValueList &&
                  quantizeValueList?.length > 0 &&
                  quantizeValueList?.map((item, index) => {
                    return (
                      <span
                        key={index}
                        style={{
                          background: item?.color
                        }}
                        className={`${
                          index === 0
                            ? 'first'
                            : index === quantizeValueList?.length - 1
                            ? 'last'
                            : ''
                        } ${quantizeValueList?.length === 1 ? 'all' : ''}`}
                      />
                    );
                  })}
              </div>

              <div className="quantizeContent">
                {quantizeValueList &&
                  quantizeValueList?.length > 0 &&
                  quantizeValueList?.map((item, index) => {
                    return (
                      <ToInput
                        length={quantizeValueList?.length}
                        theme={theme}
                        {...item}
                        index={index + 1}
                        change={change}
                      />
                    );
                  })}
              </div>

              <div className="quantizeNum">
                <span>组数</span>
                <InputNumber
                  value={numValue}
                  controls={{
                    upIcon: <CaretUpOutlined />,
                    downIcon: <CaretDownOutlined />
                  }}
                  size="small"
                  onChange={(value) => {
                    if (value < 1 || isNaN(value)) {
                      setNumValue(quantizeNum);
                    } else {
                      setNumValue(value);
                    }
                  }}
                  onBlur={() => {
                    change(numValue, 'quantizeNum');
                  }}
                  onPressEnter={() => {
                    change(numValue, 'quantizeNum');
                  }}
                />
              </div>
            </>
          ) : (
            <></>
          )}
        </div>
      </div>
      <div className="zl-ls-tab-wrap-btn">
        <FooterBtn
          saveStatus={
            current === 'threshold' &&
            quantizeValueList.some((item) => item?.max <= item?.min)
          }
          change={(type) => {
            change(type, 'popoverTabBtn');
            setIsVisible(false);
            // change(false, 'isShowTab')
            // setCurrent('quantile');
          }}
        />
      </div>
    </div>
  );

  return (
    <Wrap wrapStyle={wrapStyle}>
      <div className="label-popover-tab">
        <span className="label-popover-tab-title">
          <span>{title}</span>
          <Popover
            align={{ offset: [-25, 0] }}
            placement="bottomRight"
            content={content}
            trigger="click"
            visible={isShowTab}
            destroyTooltipOnHide={true}
            overlayClassName="zl-lagre-screen-setting-tab-popover"
          >
            <span
              className="label-popover-tab-span"
              onClick={() => {
                // setIsVisible(true);
                change(true, 'isShowTab');
              }}
            >
              {tabTitle}
            </span>
          </Popover>
        </span>
        {tabActiveValue === 'threshold' ? (
          <div
            className="quantizeColor"
            style={{ marginTop: 12 }}
            onClick={() => {
              // setIsVisible(true);
              change(true, 'isShowTab');
            }}
          >
            {quantizeValueList &&
              quantizeValueList?.length > 0 &&
              quantizeValueList?.map((item, index) => {
                return (
                  <span
                    key={index}
                    style={{
                      background: item?.color
                    }}
                    className={`${
                      index === 0
                        ? 'first'
                        : index === quantizeValueList?.length - 1
                        ? 'last'
                        : ''
                    } ${quantizeValueList?.length === 1 ? 'all' : ''}`}
                  />
                );
              })}
          </div>
        ) : (
          <span
            className="label-popover-color"
            style={colorType()}
            onClick={() => {
              change(true, 'isShowTab');
            }}
          />
        )}
      </div>
    </Wrap>
  );
};

export default LabelPopoverTab;

export interface IProps {
  wrapStyle: React.CSSProperties;
  title: string;
  tabTitle: string;
  tableList: ITableList[];
  attrKey?: string;
  change: Function;
  quantileValue: string;
  showColor: string;
  selectList: ISelectList[];
  selectValue: string;
  linearValue: string[];
  theme?: string;
  fillType?: string;
  isPure?: boolean;
  tabActiveValue?: string;
  isShowTab?: boolean;
  quantizeSelectList: ISelectList[];
  quantizeSelectValue: string;
  quantizeValueList: IQuantizeValueList[];
  quantizeNum?: number;
}

export interface ITableList {
  key: string;
  title: string;
}

export interface ISelectList {
  key: string;
  name: string;
  type: string;
  img: string;
  value: string[];
}

export interface IQuantizeValueList {
  color: string;
  max: number;
  min: number;
  status?: string;
}
