index.tsx 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
import React, { useEffect, useRef, useState } from 'react';
import defaultImg from './img/default_cover.png';
import classNames from 'classnames';
import { throttle, cloneDeep }  from 'lodash-es';
import {
  Image,
  message,
  Popconfirm,
  Popover,
  Spin,
  Tabs,
  Tooltip,
  Upload,
  Switch,
} from 'antd';
import {
  CheckOutlined,
  CloseOutlined,
  EditOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import {
  FORM_GROUP,
  ICON_CLASSIFY,
  BG_COLORS,
  ICONS,
  MAP_OLD_ICONS,
} from './enum';
import { deleteImg, getHistoryDataImg } from './service';
import './index.less';
import {QxBaseIcon, UploadFile} from "@qx/common";

interface IconProps {
  value: {
    type: string; // icon图标标识或者是http的url
    iconColor: string; // icon图标颜色
    belongTo?: string;
    showThemePicker?: boolean; // 是否展示主题选择模块
  };
  onChange: (value: {
    type: string;
    iconColor: string;
    belongTo?: string;
    showThemePicker: boolean | undefined;
  }) => void;
}
export const QxIconSelector: React.FC<IconProps> = (props) => {
  const { value, onChange } = props;
  const { iconColor, belongTo, showThemePicker } = value || {};

  const defaultIcon =
    (belongTo && FORM_GROUP[belongTo]) || 'icon-app-grid-2-fill';
  const icon =
    MAP_OLD_ICONS[value?.type] || // 映射老图标的标识
    ((value?.type?.includes('http') || // 自定义图标http直接返回
      !Object.keys(MAP_OLD_ICONS).includes(value?.type)) &&
      value?.type) ||
    defaultIcon; // 默认值
  const [bgColor, setBgColor] = useState<string>('');
  const [blockIcon, setBlockIcon] = useState<string>('');
  const [iconType, setIconType] = useState<'system' | 'custom'>();
  const [historyImg, setHistoryImg] = useState<any[]>([]);
  const [getDataLoading, setGetDataLoading] = useState<boolean>(false);
  const [uploading, setUploading] = useState<boolean>(false);
  const [iconShape, setIconShape] = useState<'fill' | 'line'>('fill');
  const [activeClassify, setActiveClassify] = useState<string>('');
  const iconListRef = useRef<HTMLDivElement>(null);

  // 新增应用时传递初始icon
  if (value && !value.type) {
    onChange({
      type: icon,
      iconColor: iconColor,
      belongTo,
      showThemePicker,
    });
  }

  const findClassifyByIcon = (icon: string) => {
    const splitIcon = icon?.split('-') || [];
    splitIcon.pop();
    const joinIcon = splitIcon.join('-');
    return (
      Object.keys(ICONS).find((cfy) => ICONS[cfy].includes(joinIcon)) || ''
    );
  };

  const scrollIntoView = (dom: HTMLElement, params: any = {}) => {
    dom.scrollIntoView(
      Object.assign({ block: 'start', inline: 'nearest' }, params),
    );
  };

  useEffect(() => {
    setBlockIcon(icon);
    setBgColor(iconColor || '');
    setIconType(icon?.includes('http') ? 'custom' : 'system');
    setIconShape(icon?.split('-').pop() === 'line' ? 'line' : 'fill');
  }, [icon, iconColor]);

  useEffect(() => {
    const cfy = findClassifyByIcon(icon);
    setActiveClassify(cfy);
  }, []);

  const onClickPopover = () => {
    setTimeout(() => {
      const cfy = findClassifyByIcon(blockIcon);
      const iconItemDom: any = document.querySelector(
        `div[data-icon-name=${blockIcon}]`,
      );
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      iconItemDom && scrollIntoView(iconItemDom);
      setTimeout(() => {
        // 恢复icon滚动副作用
        const iconCfyDOm: any = document.getElementById(
          `qx-icon-classify-${cfy}`,
        );
        setActiveClassify(cfy);
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        iconCfyDOm && scrollIntoView(iconCfyDOm, { block: 'center' });
      }, 1000);
    }, 500);
  };

  const onTabsChange = async (key: string) => {
    if (key === 'custom') {
      //获取历史上传的数据
      try {
        setGetDataLoading(true);
        const res = await getHistoryDataImg({
          appCode: 'my_icon',
          funCode: 'my_icon',
          mediaType: 'img',
        });
        setHistoryImg(res.list || []);
        setGetDataLoading(false);
      } catch (e) {
        setHistoryImg([]);
        setGetDataLoading(false);
      }
    }
  };

  const onIconShapeChange = (checked: boolean) => {
    setIconShape(checked ? 'line' : 'fill');
    const icon = blockIcon?.split('-');
    icon.pop();
    icon.push(checked ? 'line' : 'fill');
    onChange({
      type: icon.join('-'),
      iconColor: bgColor,
      belongTo,
      showThemePicker,
    });
  };

  const onScrollIconList = throttle(
    () => {
      Object.keys(ICONS).forEach((cfy) => {
        const iconItemDom: any = document.getElementById(`qx-icon-list-${cfy}`);
        const distance = Math.abs(
          iconItemDom?.offsetTop - (iconListRef.current?.scrollTop || 0),
        );
        if (distance < 40) {
          const iconCfyDOm: any = document.getElementById(
            `qx-icon-classify-${cfy}`,
          );
          scrollIntoView(iconCfyDOm, { block: 'center' });
          setActiveClassify(cfy);
        }
      });
    },
    30,
    { leading: false },
  );

  const onSelectClassify = (cfy: string) => {
    setActiveClassify(cfy);
    const iconItemDom: any = document.getElementById(`qx-icon-list-${cfy}`);
    scrollIntoView(iconItemDom);
    // window.scrollTo({ top: iconItemDom.offsetTop, behavior: 'smooth' });
  };

  const handleUpload = (file: any) => {
    // console.log('文件对象:',file);
    const imgArr = cloneDeep(historyImg);
    const formData = {
      file: 'file',
      appCode: 'my_icon',
      funCode: 'my_icon',
      publicFile: true, //长期有效文件
    };
    UploadFile(
      file,
      formData,
      () => {},
      (cr: any) => {
        // console.log('回调数据:',cr)
        const thumbUrl = cr.data?.qgImg?.urlMap?.thumb;
        if (Boolean(cr.success) && cr.data && cr.data.fileId && thumbUrl) {
          // message.success('上传成功')
          setIconType('custom');
          setBlockIcon(thumbUrl);
          onChange({
            type: thumbUrl,
            iconColor: bgColor,
            belongTo,
            showThemePicker,
          });
          setUploading(false);
          imgArr.unshift(cr.data);
        } else {
          // 上传失败
          message.error('上传失败');
        }
        setHistoryImg([...imgArr]);
      },
    );
  };

  const beforeUpload = (file: any) => {
    // console.log(file);
    const fileType =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg';
    if (!fileType) {
      message.error('请选择jpg或png或jpeg格式的文件');
    }
    const fileSize = file.size / 1024 / 1024 < 1;
    if (!fileSize) {
      message.error('请选择小于1MB的文件');
    }
    if (fileType && fileSize) {
      //如果文件符合上传条件
      setUploading(true);
      handleUpload(file);
    }
  };

  const handleDelete = async (fileId: string, index: number) => {
    const imgArr = cloneDeep(historyImg);
    await deleteImg([fileId]);
    imgArr.splice(index, 1);
    setHistoryImg([...imgArr]);
  };

  const renderContent = () => {
    return (
      <div className={'qx-select-custom-icons'}>
        <Tabs
          defaultActiveKey={'system'}
          centered
          tabBarGutter={60}
          onChange={onTabsChange}
        >
          <Tabs.TabPane tab="系统图标" key="system">
            {showThemePicker ? (
              <div className="block-color-box">
                {/* 系统默认颜色 */}
                <div
                  className={'block-color block-color--default'}
                  onClick={() => {
                    onChange({
                      type: blockIcon,
                      iconColor: '',
                      belongTo,
                      showThemePicker,
                    });
                  }}
                >
                  {!bgColor && <CheckOutlined />}
                </div>
                {BG_COLORS.map((color: string) => {
                  return (
                    <div
                      key={color}
                      style={{ backgroundColor: color }}
                      className={'block-color'}
                      onClick={() => {
                        onChange({
                          type: blockIcon,
                          iconColor: color,
                          belongTo,
                          showThemePicker,
                        });
                      }}
                    >
                      {color === bgColor && <CheckOutlined />}
                    </div>
                  );
                })}
              </div>
            ) : null}
            <div
              className={classNames(
                'block-icon-box',
                !showThemePicker && 'height336',
              )}
            >
              <div
                className="icon-list"
                ref={iconListRef}
                onScroll={onScrollIconList}
              >
                {Object.keys(ICONS).map((cfy) => {
                  return (
                    <div id={`qx-icon-list-${cfy}`} key={cfy}>
                      <div className="icon-classify-label">
                        {ICON_CLASSIFY[cfy]}
                      </div>
                      <div className="icon-classify-list">
                        {ICONS[cfy].map((item: string) => {
                          const icon = `${item}-${iconShape}`;
                          return (
                            <div
                              key={icon}
                              className={'block-icon'}
                              data-icon-name={icon}
                            >
                              <QxBaseIcon
                                type={icon}
                                onClick={() => {
                                  onChange({
                                    type: icon,
                                    iconColor: bgColor,
                                    belongTo,
                                    showThemePicker,
                                  });
                                  const cfy = findClassifyByIcon(icon);
                                  const iconCfyDOm: any =
                                    document.getElementById(
                                      `qx-icon-classify-${cfy}`,
                                    );
                                  scrollIntoView(iconCfyDOm, {
                                    block: 'center',
                                  });
                                  setActiveClassify(cfy);
                                }}
                                style={{
                                  color:
                                    bgColor && icon === blockIcon
                                      ? '#fff'
                                      : 'rgba(0, 0, 0, 0.45)',
                                  backgroundColor:
                                    icon === blockIcon ? bgColor : '',
                                }}
                                className={classNames({
                                  'block-icon--default':
                                    icon === blockIcon && !bgColor,
                                })}
                              />
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="icon-classify">
                <Switch
                  checked={iconShape === 'line' ? true : false}
                  className="classify-switch"
                  checkedChildren="线性"
                  unCheckedChildren="面性"
                  onChange={onIconShapeChange}
                />
                <div className="classify-label-list">
                  {Object.keys(ICONS).map((cfy) => {
                    return (
                      <div
                        id={`qx-icon-classify-${cfy}`}
                        className={classNames(
                          'classify-label',
                          activeClassify === cfy && 'active',
                        )}
                        key={cfy}
                        onClick={() => onSelectClassify(cfy)}
                      >
                        {ICON_CLASSIFY[cfy]}
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <div className="qx-select-custom-desc-icon-wrap">
                自定义图标&ensp;
                <Tooltip
                  title={
                    '请选择1MB以内的jpg、jpeg或png图片,建议尺寸144*144像素'
                  }
                  color="#ffffff"
                  overlayStyle={{ maxWidth: '240px' }}
                  overlayInnerStyle={{
                    fontSize: '14px',
                    color: '#50535D',
                    textAlign: 'justify',
                    lineHeight: '22px',
                  }}
                  placement={'right'}
                >
                  <ExclamationCircleOutlined className="custom-desc-icon" />
                </Tooltip>
              </div>
            }
            key="custom"
          >
            <Spin spinning={getDataLoading} style={{ top: '70px' }}>
              <div className="custom-icon-box">
                <div className="custom-icon-item">
                  <Upload
                    name="icon"
                    listType="picture-card"
                    accept=".jpg,.png"
                    maxCount={1}
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    className={'qx-custom-upload'}
                  >
                    <PlusOutlined />
                  </Upload>
                </div>
                {historyImg && historyImg.length ? (
                  <>
                    <div
                      style={{
                        height: '40px',
                        width: '40px',
                        textAlign: 'center',
                        paddingTop: '10px',
                        display: uploading ? '' : 'none',
                        margin: '0 10px 10px 0',
                      }}
                    >
                      <Spin tip={''} size={'small'} spinning={true} />
                    </div>
                    {/*<Image.PreviewGroup>*/}
                    {historyImg.map((item: any, index: number) => {
                      return (
                        <div className="custom-icon-item" key={index}>
                          <div className={'qx-custom-preview'}>
                            <Popconfirm
                              title={`确定要删除这张图片吗?`}
                              okText="确定"
                              cancelText="取消"
                              onConfirm={() => handleDelete(item.fileId, index)}
                            >
                              <div className={'qx-custom-preview_icon'}>
                                <CloseOutlined style={{ fontSize: '8px' }} />
                              </div>
                            </Popconfirm>
                            <Image
                              src={item?.qgImg?.urlMap?.thumb || 'error'}
                              fallback={defaultImg}
                              preview={false}
                              style={{ width: '24px', height: '24px' }}
                              onClick={() => {
                                setBlockIcon(item?.qgImg?.urlMap?.thumb);
                                setIconType('custom');
                                onChange({
                                  type: item?.qgImg?.urlMap?.thumb,
                                  iconColor: bgColor,
                                  belongTo,
                                  showThemePicker,
                                });
                              }}
                            />
                          </div>
                        </div>
                      );
                    })}
                    {/*</Image.PreviewGroup>*/}
                  </>
                ) : null}
              </div>
            </Spin>
          </Tabs.TabPane>
        </Tabs>
      </div>
    );
  };
  return (
    <div className="qx-select-icon-container" style={{ width: 'auto' }}>
      <Popover
        content={renderContent}
        placement="right"
        trigger="click"
        overlayClassName={'qx-icon-picker-overlay'}
        onOpenChange={onClickPopover}
        // getPopupContainer={(triggerNode) => triggerNode} // 图标不跟随标签
      >
        {iconType === 'custom' ? (
          <Image
            className="cover-img"
            src={blockIcon || 'error'}
            fallback={defaultImg}
            preview={false}
          />
        ) : (
          <QxBaseIcon
            className="cover-icon default__icon"
            type={blockIcon}
            style={{ backgroundColor: bgColor }}
          />
        )}
        <EditOutlined />
      </Popover>
    </div>
  );
};