index.tsx 15 KB
Newer Older
1
import React from 'react';
2
import { Upload, Modal, message, Tabs, Result, Input, Collapse,Anchor  } from 'antd';
3 4 5 6
import { PlusOutlined, CheckCircleFilled } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
import classnames from 'classnames';
import { UploadFile, UploadChangeParam, RcFile } from 'antd/lib/upload/interface';
7 8
import { uuid } from '@/utils/tools';
import { get, PUBLISH_SERVICE } from '@/services';
9
import styles from './index.less';
10
import { getImageBases } from '@/services/common/api';
11
import UploadContext from './context'
12
import _, { clone } from 'lodash'
13
const { Link } = Anchor;
14

15 16


17 18
const { TabPane } = Tabs;
const { Search } = Input;
19 20
// 维护图片分类映射
const wallCateName: any = {
张烨's avatar
张烨 committed
21
  icon: '图标',
22
  bg: '背景',
张烨's avatar
张烨 committed
23
  uploaded: '上传',
24
};
25
const tabNames: any = {
Maofei94's avatar
Maofei94 committed
26
  icon: 'icon图标',
Maofei94's avatar
Maofei94 committed
27
  androidMenu: '移动应用图标',
Maofei94's avatar
Maofei94 committed
28
  menuNew: '应用图标',
29
  logo: '项目logo',
30 31
  menu: '菜单图标',
  CityTemp: '用户上传',
张烨's avatar
张烨 committed
32
}
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

function getBase64(file: File | Blob) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });
}

interface PicturesWallType {
  fileList?: UploadFile<any>[];
  action?: string;
  headers?: any;
  withCredentials?: boolean;
  maxLen?: number;
  onChange?: (v: any) => void;
  cropRate?: number | boolean;
  isCrop?: boolean;
52
  type?: 'CityTemp' | 'icon' | 'androidMenu' | 'menuNew',
张烨's avatar
张烨 committed
53
  value?: string | string[],
张烨's avatar
张烨 committed
54
  uploadContext: any,
张烨's avatar
张烨 committed
55
  search: string,
张烨's avatar
张烨 committed
56
  actives: any,
Maofei94's avatar
Maofei94 committed
57
  picType: any,
58 59 60 61 62 63 64 65
}

class PicturesWall extends React.Component<PicturesWallType> {
  state = {
    previewVisible: false,
    previewImage: '',
    wallModalVisible: false,
    previewTitle: '',
张烨's avatar
张烨 committed
66
    imgBed: this.props.uploadContext?.imgBed || [],
67
    curSelectedImg: '',
68 69
    baseUrl: '',
    prevProps: {},
张烨's avatar
张烨 committed
70
    search: '',
张烨's avatar
张烨 committed
71
    actives: {},
张烨's avatar
张烨 committed
72 73 74 75 76
    fileList: this.props.value ? Array.isArray(this.props.value) ? this.props.value.map((v) => ({
      url: v,
      uid: uuid(8, 16),
      name: '熊猫运维中台系统',
      status: 'done',
77
    })) as UploadFile<any>[] : [{
张烨's avatar
张烨 committed
78 79 80 81
      url: this.props.value,
      uid: uuid(8, 16),
      name: '熊猫运维中台系统',
      status: 'done',
张烨's avatar
张烨 committed
82
    }] as UploadFile<any>[] : [],
83
  };
张烨's avatar
张烨 committed
84

85 86 87 88 89 90
  /**
   *  判断value是否更新,若更新则更新state.fileList
   *  判断imgBed是否更新,若更新则更新state.imgBed
   * @param props 
   * @param state 
   */
张烨's avatar
张烨 committed
91
  static getDerivedStateFromProps = (props, state) => {
92
    const { value, uploadContext = {} } = props;
张烨's avatar
张烨 committed
93
    const { imgBed, update } = uploadContext;
张烨's avatar
张烨 committed
94
    const fileList = state.fileList;
95
    const shouldUpdate = fileList.every(f => Array.isArray(value) ? !value.some(v => f.url === v) : f.url !== value)
96
    if (value !== state.prevProps.value && shouldUpdate) {
张烨's avatar
张烨 committed
97
      return {
张烨's avatar
张烨 committed
98
        prevProps: props,
99
        fileList: Array.isArray(value) ? value.map((v) => ({
张烨's avatar
张烨 committed
100 101 102 103
          url: v,
          uid: uuid(8, 16),
          name: '熊猫运维中台系统',
          status: 'done',
104
        })) as UploadFile<any>[] : value ? [{
张烨's avatar
张烨 committed
105
          url: value,
张烨's avatar
张烨 committed
106 107 108
          uid: uuid(8, 16),
          name: '熊猫运维中台系统',
          status: 'done',
109
        }] as UploadFile<any>[] : []
张烨's avatar
张烨 committed
110 111
      }
    }
112
    if (imgBed != state.prevProps.uploadContext?.imgBed) {
张烨's avatar
张烨 committed
113
      const activeKeys = {};
114 115 116 117 118 119 120 121 122 123 124 125
      const imgArr = JSON.parse(JSON.stringify(imgBed))
      imgArr.forEach(item => {
        if(item.fileUrls.length > 0) {
          item.child.unshift({
            moduleName: item.moduleName,
            fileUrls: item.fileUrls,
            child: [],
            baseUrl: item.baseUrl
          })
        }
        activeKeys[item.moduleName] = item.child.map(c => c.moduleName)
      });
张烨's avatar
张烨 committed
126 127
      return {
        prevProps: props,
张烨's avatar
张烨 committed
128 129
        imgBed,
        actives: activeKeys,
张烨's avatar
张烨 committed
130 131
      }
    }
张烨's avatar
张烨 committed
132 133 134
    return {
      prevProps: props
    };
张烨's avatar
张烨 committed
135 136
  }

137 138
  update = () => {
    if (this.props.value) {
张烨's avatar
张烨 committed
139
      this.setState({
140
        fileList: Array.isArray(this.props.value) ? this.props.value.map((v) => ({
张烨's avatar
张烨 committed
141 142 143 144
          url: v,
          uid: uuid(8, 16),
          name: '熊猫运维中台系统',
          status: 'done',
145
        })) as UploadFile<any>[] : [{
张烨's avatar
张烨 committed
146 147 148 149 150 151 152 153
          url: this.props.value,
          uid: uuid(8, 16),
          name: '熊猫运维中台系统',
          status: 'done',
        }] as UploadFile<any>[]
      })
    }
  }
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

  handleCancel = () => this.setState({ previewVisible: false });

  handleModalCancel = () => this.setState({ wallModalVisible: false });

  handlePreview = async (file: UploadFile<any>) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1),
    });
  };

  handleWallSelect = (url: string) => {
    this.setState({
      wallModalVisible: true,
    });
  };

177
  handleImgSelected = (url: string, baseUrl: any) => {
178 179
    console.log(url,baseUrl);
    
180 181
    this.setState({
      curSelectedImg: url,
182
      baseUrl: baseUrl
183 184 185 186 187 188 189 190 191 192
    });
  };

  handleWallShow = () => {
    this.setState({
      wallModalVisible: true,
    });
  };

  handleModalOk = () => {
张烨's avatar
张烨 committed
193
    const { maxLen = 1 } = this.props;
194
    const { baseUrl, curSelectedImg } = this.state
195 196 197
    const fileList = [
      {
        uid: uuid(8, 16),
198
        name: '熊猫运维中台系统',
199
        status: 'done',
Maofei94's avatar
Maofei94 committed
200
        url: curSelectedImg,
201 202
      },
    ];
203
    if (!curSelectedImg) {
Maofei94's avatar
Maofei94 committed
204
      message.warn({
205 206
        duration: 2,
        content: '请先选择图片'
Maofei94's avatar
Maofei94 committed
207 208 209
      })
      return
    }
210 211 212 213
    if (curSelectedImg.includes('CityTemp')) {
      localStorage.setItem('pd-baseUrl', baseUrl)
    } else {
      localStorage.setItem('pd2-baseUrl', baseUrl)
Maofei94's avatar
Maofei94 committed
214 215
    }
    console.log(fileList[0].url)
216
    this.props.onChange && this.props.onChange(maxLen === 1 ? fileList[0].url.replace('civweb4\\', '') : fileList.map(f => f.url.replace('civweb4\\', '')));
217 218 219 220
    this.setState({ fileList, wallModalVisible: false });
  };

  handleChange = ({ file, fileList }: UploadChangeParam<UploadFile<any>>) => {
张烨's avatar
张烨 committed
221
    const { maxLen = 1, uploadContext } = this.props;
222 223 224
    this.setState({ fileList });
    if (file.status === 'done') {
      const files = fileList.map(item => {
张烨's avatar
张烨 committed
225
        const { status, name, thumbUrl } = item;
226
        const url = item.response && item.response.data || thumbUrl;
227
        return { uid: uuid(8, 16), name, status, url };
228
      });
229 230
      this.setState({ fileList: files })
      this.props.onChange && this.props.onChange(maxLen === 1 ? files[0].url : files.map(f => f.url));
张烨's avatar
张烨 committed
231
      uploadContext?.update && uploadContext.update()
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    }
  };

  handleBeforeUpload = (file: RcFile) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg' ||
      file.type === 'image/gif';
    if (!isJpgOrPng) {
      message.error('只能上传格式为jpeg/png/gif的图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于2MB!');
    }
248
    return isJpgOrPng && isLt2M || Upload.LIST_IGNORE;;
249 250
  };

张烨's avatar
张烨 committed
251 252 253 254 255 256 257 258
  // componentDidMount() {
  //   const { type = ''} = this.props;
  //   getImageBases(type).then(res => {
  //     if(res.code === 0){
  //       this.setState({imgBed: res.data})
  //     }
  //   })
  // }
259

260 261
  getImageUrl(path) {
    if (path && path.indexOf('http') === 0) {
262
      return path
263 264
    }
    if (path && path.indexOf('data:') === 0) {
265 266
      return path
    }
267
    if (path && path.indexOf('assets') === 0) {
268
      return `${window.location.origin}/civweb4/${path}`.replace(/\\/g, '/')
张烨's avatar
张烨 committed
269
    }
270
    return `${window.location.origin}/${path}`.replace(/\\/g, '/')
271 272
  }

273
  getFileName(path: string) {
张烨's avatar
张烨 committed
274
    const match = path.match(/(?<=[\/\\])([^\\\/\.]*)(\.?\w*)$/)
275
    return match && match[1] || ''
张烨's avatar
张烨 committed
276 277
  }

278
  renderImgItem(url, baseUrl) {
张烨's avatar
张烨 committed
279
    const fileName = this.getFileName(url)
280
    const { curSelectedImg, search } = this.state;
张烨's avatar
张烨 committed
281
    return (
282
      <div
张烨's avatar
张烨 committed
283
        className={classnames({
284
          [styles.imgItem]: true,
张烨's avatar
张烨 committed
285
          [styles.hide]: !fileName.includes(search)
286
        })}
张烨's avatar
张烨 committed
287
        key={url}
288
        onClick={() => this.handleImgSelected(url, baseUrl)}>
张烨's avatar
张烨 committed
289 290 291 292 293
        <div
          className={classnames(
            curSelectedImg === url ? styles.seleted : '',
          )}
        >
294
          <img
张烨's avatar
张烨 committed
295 296
            className={classnames({
              [styles.svgGray]: /\.svg$/.test(url)
297 298 299
            })}
            src={this.getImageUrl(url)}
            title={url}
张烨's avatar
张烨 committed
300 301 302 303 304
            alt="熊猫运维中台系统" />
          <span className={styles.iconBtn}>
            <CheckCircleFilled />
          </span>
        </div>
305
        <span id={`#${curSelectedImg}`} title={fileName}>{fileName}</span>
张烨's avatar
张烨 committed
306 307 308 309
      </div>
    );
  }

310
  renderCollapse(module) {
张烨's avatar
张烨 committed
311
    const { Panel } = Collapse;
312 313 314 315 316 317 318
    const items = module.fileUrls.map(url => this.renderImgItem(url, module.baseUrl))
    return items.length > 0 && <Panel
      forceRender
      header={module.moduleName}
      key={module.moduleName}>
      {items}
    </Panel>
张烨's avatar
张烨 committed
319 320
  }

321 322
  handleCollapseChange(v, moduleName) {
    const activeKeys = { ...this.state.actives }
张烨's avatar
张烨 committed
323 324 325 326 327 328
    activeKeys[moduleName] = v;
    this.setState({
      actives: activeKeys
    })
  }

329 330 331 332 333 334 335 336
  render() {
    const {
      previewVisible,
      previewImage,
      fileList,
      previewTitle,
      wallModalVisible,
      imgBed,
张烨's avatar
张烨 committed
337
      actives,
338 339 340
      curSelectedImg,
    } = this.state;
    const {
341
      action = `${window.location.origin}${PUBLISH_SERVICE}/FileCenter/UploadSingleFile`,
342 343 344 345 346
      headers,
      withCredentials = true,
      maxLen = 1,
      cropRate = 375 / 158,
      isCrop,
Maofei94's avatar
Maofei94 committed
347
      picType,
348 349 350 351 352 353 354 355
    } = this.props;

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">上传</div>
      </div>
    );
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
    const onSearch = (key) => {
      const bed = this.props.uploadContext.imgBed
      const nodes = _.cloneDeep(bed)

      for(const node of nodes){
        arrayTreeFilter(node,key)
      }
       
      console.log(nodes)
      this.setState({imgBed:nodes})

    }

    const arrayTreeFilter = (node,key) => {
      
      let reg = new RegExp(`/${key}/g`)
      
      for (const nodeItem of node.child) {
        if ( nodeItem.child.length < 1) {
         
          
            if(!reg.test(nodeItem.moduleName)){
              node.child.splice(nodeItem,1)
              console.log(nodeItem.moduleName,"--------------------移除图包-----------------")
            }
        }else{
          arrayTreeFilter(nodeItem,key);
        }
      }
      
    }
    
388 389 390 391 392 393 394 395 396

    return (
      <>
        {isCrop ? (
          <ImgCrop
            modalTitle="裁剪图片"
            modalOk="确定"
            modalCancel="取消"
            rotate={true}
张烨's avatar
张烨 committed
397
            aspect={cropRate as number}
398 399
          >
            <Upload
400
              fileList={fileList.map(f => ({ ...f, url: this.getImageUrl(f.url) }))}
401 402
              onPreview={this.handlePreview}
              onChange={this.handleChange}
403
              name="singleFile"
404 405 406 407 408
              listType="picture-card"
              className={styles.avatarUploader}
              action={action}
              withCredentials={withCredentials}
              headers={{
张烨's avatar
张烨 committed
409 410
                // 'x-requested-with': localStorage.getItem('user') || '',
                Authorization: 'Bearer ' + localStorage.getItem('token') || '',
411 412 413 414 415 416 417 418 419
                ...headers,
              }}
              beforeUpload={this.handleBeforeUpload}
            >
              {fileList.length >= maxLen ? null : uploadButton}
            </Upload>
          </ImgCrop>
        ) : (
          <Upload
420
            fileList={fileList.map(f => ({ ...f, url: this.getImageUrl(f.url) }))}
421 422
            onPreview={this.handlePreview}
            onChange={this.handleChange}
423
            name="singleFile"
424 425 426 427 428
            listType="picture-card"
            className={styles.avatarUploader}
            action={action}
            withCredentials={withCredentials}
            headers={{
张烨's avatar
张烨 committed
429 430
              // 'x-requested-with': localStorage.getItem('user') || '',
              Authorization: 'Bearer ' + localStorage.getItem('token') || '',
431 432 433 434 435 436 437 438
              ...headers,
            }}
            beforeUpload={this.handleBeforeUpload}
          >
            {fileList.length >= maxLen ? null : uploadButton}
          </Upload>
        )}
        <div className={styles.wallBtn} onClick={this.handleWallShow}>
439
          从图片库选择
440 441 442
        </div>
        <Modal
          visible={previewVisible}
邓超's avatar
邓超 committed
443
          // title={previewTitle}
444 445 446
          footer={null}
          onCancel={this.handleCancel}
        >
张烨's avatar
张烨 committed
447
          <img alt="预览图片" className={styles.svgBg} style={{ width: '100%' }} src={this.getImageUrl(previewImage)} />
448 449 450 451 452 453
        </Modal>
        <Modal
          visible={wallModalVisible}
          title="图片库"
          okText="确定"
          cancelText="取消"
Maofei94's avatar
Maofei94 committed
454
          width={1080}
455 456
          onCancel={this.handleModalCancel}
          onOk={this.handleModalOk}
张烨's avatar
张烨 committed
457
          className={styles.modal}
458
        >
459
          <Input    
460 461 462 463
                    placeholder="搜索图库" 
                    className={styles.search} 
                    size="middle" 
                    value={this.state.search}
464
                    style={{marginLeft:'102px',width:'50%'}}
465 466
                    onChange={e => this.setState({search: e.target.value})} 
                    allowClear/>
467
          {/* <Search style ={{   width:'200px',margin: '10px 0 10px 100px'}} onSearch={onSearch} /> */}
邓超's avatar
邓超 committed
468
          <Tabs defaultActiveKey={imgBed[0]?.moduleName} tabPosition="left" >
469
            {imgBed.map((item, i) => {
470 471 472
              if (item.moduleName == picType || item.moduleName == 'CityTemp') {
                const child = [...item.child] || [];
                if (item.fileUrls.length > 0) {
473
                  child.unshift({
474 475 476 477 478 479 480
                    moduleName: item.moduleName,
                    fileUrls: item.fileUrls,
                    child: [],
                    baseUrl: item.baseUrl
                  })
                }
                return (
481 482
                  <TabPane tab={tabNames[item.moduleName] || item.moduleName} key={item.moduleName} style={{overflow:'hidden'}}> 
                    
483 484 485 486 487 488 489 490 491 492 493
                    <div className={styles.imgBox}>
                      <Collapse
                        bordered
                        activeKey={actives[item.moduleName]}
                        onChange={(v) => this.handleCollapseChange(v, item.moduleName)}>
                        {child.map(child => this.renderCollapse(child))}
                      </Collapse>
                    </div>
                  </TabPane>
                );
              }
494
            })}
Maofei94's avatar
Maofei94 committed
495
            {/* <TabPane tab="更多" key="more">
张烨's avatar
张烨 committed
496
              <Result status="500" title="温馨提示" subTitle="更多素材, 正在筹备中..." />
Maofei94's avatar
Maofei94 committed
497
            </TabPane> */}
498 499 500 501 502 503 504
          </Tabs>
        </Modal>
      </>
    );
  }
}

张烨's avatar
张烨 committed
505 506
const PicturesWallWrapper = (props: any) => {
  return <UploadContext.Consumer>
507
    {(uploadContext) => <PicturesWall {...props} uploadContext={uploadContext} />}
张烨's avatar
张烨 committed
508 509 510
  </UploadContext.Consumer>
}
export default PicturesWallWrapper;