ImportUtil.js 15.2 KB
Newer Older
徐立's avatar
徐立 committed
1
import React, { Fragment } from 'react';
钟是志's avatar
钟是志 committed
2
import { Button, Steps, Upload, Icon, Tabs, Table } from 'antd';
徐立's avatar
徐立 committed
3 4
import styles from './ImportUtil.less';
import ButtonDiy from './ButtonDiy/ButtonDiy';
5
import { getToken } from '../utils/token';
tb53863844's avatar
tb53863844 committed
6
import FormdataWrapper from '../utils/object-to-formdata-custom';
chscls@163.com's avatar
chscls@163.com committed
7
import config from '@/webPublic/one_stop_public/config';
徐立's avatar
徐立 committed
8
import { connect } from 'dva';
钟是志's avatar
钟是志 committed
9
import { getMessage, getModal } from '@/webPublic/one_stop_public/utils/utils';
10
import { giveFilePostDataInfoForTrue } from '@/webPublic/one_stop_public/Base16';
11
import { getTransformApi } from '@/webPublic/one_stop_public/2022beidianke/localstorageTransform';
12
import ProgressDiy from './ProgressDiy';
13 14 15 16
import {
  getSassApiHeader,
  getSysCode
} from '@/webPublic/one_stop_public/2023yunshangguizhou/utils';
17
import { decodeObjKey, getServicesNomal, importExecute } from '../Services/services';
18
import { importDataQueryApi, importAnalyseApi } from '../Services/apiConfig';
19

钟是志's avatar
钟是志 committed
20 21
const Modal = getModal();
const message = getMessage();
徐立's avatar
徐立 committed
22 23
const Step = Steps.Step;
const TabPane = Tabs.TabPane;
24 25
let tempCallback = () => {
};
徐立's avatar
徐立 committed
26

27 28 29 30 31 32
@connect(({
            DataObj,
            loading,
          }) => ({
  DataObj,
  loading: loading.models.DataObj,
徐立's avatar
徐立 committed
33 34
}))
export default class ImportUtil extends React.PureComponent {
35 36
  constructor(props) {
    super(props);
37
    tempCallback = this.props.callback || tempCallback;
38

39 40 41 42 43 44 45 46 47 48 49 50 51
    this.state = {
      ch: false,
      currentKey: '1',
      visible: false,
      current: 0,
      isShow: true,
      fileCacheKey: '',
      sucData: [],
      errData: [],
      column: [],
      confirmLoading: false,
      openProgress: false,
      // exportTemplateUrl,
52

53
      isNextDisabled: false,
54
      trueObjId: '',
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
  showModal = () => {
    this.setState({
      sucData: [],
      errData: [],
      column: [],
      current: 0,
      isShow: true,
      isNextDisabled: false,
      fileCacheKey: '',
      visible: true,
    });
  };
  handleOk = (e) => {
    this.setState({
      visible: false,
    });
  };
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };
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
  next() {
    const current = this.state.current + 1;
    if (current === 2) {
      this.setState({
        current: current,
        isShow: false,
      });
      if (this.state.errData.lenth > 0) {
        message.error('请检查数据');
        return;
      } else {
        this.import();
      }
    }
    if (current === 3) { // 导入完成后
      console.log('current === 3');
      this.setState(
        {
          current: current,
          isShow: true,
        },
        () => {
          if (tempCallback && typeof tempCallback === 'function') {
            tempCallback();
            tempCallback = null;
          }
        },
      );
    }
  }
xuli's avatar
xuli committed
111

112 113 114 115
  prev() {
    const current = this.state.current - 1;
    this.setState({ current });
  }
xuli's avatar
xuli committed
116

117 118 119
  changeOpenProgress = (v) => {
    if (v === false) {
      this.next();
120
      message.success('导入成功', 1);
121 122 123 124
      this.setState({
        current: 3,
        isShow: true,
        visible: false,
钟是志's avatar
钟是志 committed
125
        openProgress: false,
126 127 128
      });
    }
  };
徐立's avatar
徐立 committed
129

130 131 132
  import() {
    const {
      importParams,
133
      objId,
134
    } = this.props;
135 136 137
    const {
      trueObjId
    } = this.state;
138 139 140
    importExecute({
      ...(importParams || {}),
      cacheKey: this.state.fileCacheKey,
141
      objId: trueObjId || objId,
142 143 144 145 146 147 148 149
    }).then(res => {
      if (res && res.sync === false && res.total) {
        // 23013 学生事务/学生医保管理/学生平安险/保险办理,2001010248 高职界面已购买 导入 报错【接口超时】
        this.setState({
          openProgress: res,
        });
        return;
      }
150

151
      this.next();
152
        message.success('导入成功', 1);
153 154 155 156 157 158 159
        this.setState({
          current: 3,
          isShow: true,
          visible: false,
        });
    });
  }
徐立's avatar
徐立 committed
160

161 162 163 164
  getCachKey = (filePath) => {
    const {
      importParams,
      importConfig,
165
      objId,
166
    } = this.props;
167
    const { trueObjId } = this.state;
168 169 170 171
    getServicesNomal(importAnalyseApi, {
      ...(importParams || {}),
      isLocal: false,
      filePath,
徐立's avatar
徐立 committed
172

173
      importConfig: importConfig ? JSON.stringify(importConfig) : null,
174
      objId: trueObjId || objId,
175 176 177 178 179
    }).then(res => {
      this.setState({
        fileCacheKey: res.cacheKey,
      });
      this.queryFile(res.cacheKey);
180 181 182 183 184
    });
  };
  queryFile = (cacheKey) => {
    const {
      importParams,
185
      objId,
186
    } = this.props;
187
    const { trueObjId } = this.state;
188 189 190
    getServicesNomal(importDataQueryApi, {
      ...(importParams || {}),
      cacheKey,
191
      objId: trueObjId || objId,
192 193 194 195
    }).then(res => {
      this.setState({
        current: 1,
        isShow: false,
徐立's avatar
徐立 committed
196

197 198 199 200 201 202 203
        sucData: res.pass,
        errData: res.noPass,
        column: res.column,
      });
      if (res.noPass && res.noPass.length === 0) {
        if (res.pass.length === 0) {
          message.error('当前没有验证成功的数据,无法导入。');
204 205 206 207 208
          this.setState({
            currentKey: '1',
            ch: !this.state.ch,
            isNextDisabled: true,
          });
209 210 211 212 213 214 215
        } else {
          message.success('所有数据验证通过,请确认后点击下一步。');
          this.setState({
            currentKey: '2',
            ch: !this.state.ch,
            isNextDisabled: false,
          });
216
        }
217 218 219 220 221 222 223 224
      } else {
        message.error('当前存在未验证通过的数据,请按错误提示检测更正导入文件');
        this.setState({
          currentKey: '1',
          ch: !this.state.ch,
          isNextDisabled: true,
        });
      }
225 226
    });
  };
徐立's avatar
徐立 committed
227

228 229 230
  changePane = (activeKey) => {
    this.setState({ currentKey: activeKey });
  };
231

232 233 234 235 236 237 238 239 240 241 242 243 244 245
  componentDidMount() { // 1396 考场监考老师、QQ群等信息能批量导入。
    if(this.props.importConfig?.objKey && typeof this.props.importConfig.objKey === 'string' &&
      this.props.importConfig.objKey.length > 10
    ){
      decodeObjKey(this.props.importConfig.objKey).then((res) => {
        if(res && typeof res === 'string' && res.length > 10) {
          console.log(res, res.length);
          this.setState({
            trueObjId: res,
          })
        }
      })
    }
  }
xuli's avatar
xuli committed
246

247 248 249 250 251 252 253 254
  downloadFile = async () => {
    this.setState({ confirmLoading: true });
    const {
      objId,
      fileName,
      importParams,
      importConfig,
    } = this.props;
255
    const { trueObjId } = this.state;
256 257 258
    const params = {
      ...importParams,
      importConfig: importConfig ? JSON.stringify(importConfig) : null,
259
      objId: trueObjId || objId,
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
      fileName,
    };
    let url = `${config.httpServer}/DataObjApi/importTemplateDownload`;
    let newParams = giveFilePostDataInfoForTrue(params, url);
    if (newParams && newParams.datas) {
      newParams.datas.token = getToken();
    }
    const {
      transformApi,
      headersApi,
    } = await getTransformApi(newParams.url);
    fetch(transformApi, {
      method: 'POST',
      body: FormdataWrapper(newParams.datas),
    })
      .then((res) => {
        console.log(res.status);
        if (res.status != 200 && res.status !== 202) {
          return res.json();
        } else {
          return res.blob();
        }
      })
      .then((data) => {
        if (data instanceof Blob) {
          let a = document.createElement('a');
          let url = window.URL.createObjectURL(data);
          let filename =
            (this.props.fileName ? this.props.fileName : '导入模板.') + (this.props.ext || 'xlsx');
          a.href = url;
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(url);
          a = null;
        } else {
          message.error(`文件导出错误`);
        }
      })
      .catch((err) => {
        console.error(err);
        message.error(`网络请求超时`);
      })
      .finally(() => {
        this.setState({ confirmLoading: false });
      });
  };
xuli's avatar
xuli committed
306

307 308 309 310
  render() {
    const props = {
      name: 'file',
      action: config.uploadUrl,
311
      headers: getSassApiHeader(),
312 313 314 315 316 317 318 319 320 321 322
      data: {
        token: getToken(),
      },
      accept: '.xlsx',
      showUploadList: false,
      onChange: (info) => {
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功`);
          let x = info.file.response;
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
          this.getCachKey(x);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败`);
        }
      },
    };
    const steps = [
      {
        title: '上传Excel',
      },
      {
        title: '验证数据',
      },
      {
        title: '数据导入',
      },
      {
        title: '导入完成',
      },
    ];
徐立's avatar
徐立 committed
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
    const {
      current,
      openProgress,
      fileCacheKey,
    } = this.state;
    const { name } = this.props;
    const column1 = this.state.column
      ? [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 50,
          render: (v, r, i) => i + 1,
        },
        {
          title: '数据行数',
          dataIndex: 'row_index',
          width: 50,
        },
        ...this.state.column,
      ]
      : [];
    let column2 = this.state.column ? [{
      title: '数据行数',
      dataIndex: 'row_index',
      width: 50,
    }, ...this.state.column] : [];
    if (column1.length > 1) {
      column1[1].render = (val) => <span style={{ color: 'red' }}>{val}</span>;
    }
xuli's avatar
xuli committed
376

377 378 379 380 381 382 383 384 385 386 387 388
    if (column2) {
      let xuhao = column2.find((g) => g.dataIndex === '序号');
      if (!xuhao) {
        column2.unshift({
          title: '序号',
          fixed: 'left',
          width: 50,
          render: (v, r, i) => i + 1,
          dataIndex: '序号',
        });
      }
    }
389

390 391 392 393 394 395
    const btn = {
      name: name || '批量导入',
      type: 'default',
      className: 'defaultBlue',
      ...(this.props.btn ? this.props.btn : {}),
    };
396 397 398
    if(this.state.visible){
      console.log(this.props);
    }
399 400 401

    return (
      <span>
402 403
				<ButtonDiy {...btn} handleClick={this.showModal} />
				<Modal
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
          visible={this.state.visible}
          onOk={this.handleOk}
          maskClosable={false}
          destroyOnClose
          onCancel={this.handleCancel}
          title={null}
          footer={null}
          width={'80%'}>
          {
            !!openProgress ? <ProgressDiy fileCacheKey={fileCacheKey}
                                          {...openProgress}
                                          changeOpenProgress={this.changeOpenProgress}
              /> :
              <div className={styles.nomal}>
                <p className={styles.import}>EXCEL导入向导</p>
                <div style={{ margin: 'auto 23px' }}>
                  <Steps current={current}>
                    {steps.map((item) => (
                      <Step key={item.title} title={item.title} />
                    ))}
                  </Steps>
                  <div className='steps-content'>{steps[this.state.current].content}</div>
                  <div className={styles.button}>
                    {this.state.current < steps.length - 1 &&
                    this.state.current !== 0 && (
                      <ButtonDiy
                        name={this.state.current == 3 ? '确认导入' : '下一步'}
                        type='primary'
                        disabled={this.state.current != 3 && this.state.isNextDisabled}
                        // className='primaryBlue'
                        handleClick={() => this.next()}
                      />
                    )}
tb53863844's avatar
tb53863844 committed
437

438 439 440 441 442 443 444 445 446 447
                    {this.state.current > 0 && (
                      <ButtonDiy
                        style={{ marginLeft: 8 }}
                        name='上一步'
                        className='defaultBlue'
                        handleClick={() => this.prev()}
                      />
                    )}
                  </div>
                </div>
tb53863844's avatar
tb53863844 committed
448

449 450 451 452
                <div className={styles.tip}>
                  <p className={styles.tipContent}>
                    <span>欢迎使用EXCEL导入向导,首先请您上传需要导入的EXCEL文件。</span>
                    <span>
453 454
									点击“选择文件”选择您要导入的EXCEL文件,点击“开始上传”将其上传到服务器上,点击“清空队列”清空当前上传文件队列。
								</span>
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
                  </p>
                </div>
                {this.state.isShow ? (
                  <div className={styles.buttonDown}>
                    <Upload {...props}>
                      <Button>
                        <Icon type='upload' />
                        点击上传
                      </Button>
                    </Upload>
                    <ButtonDiy
                      name={'下载模板'}
                      type='primary'
                      // className='primaryBlue'
                      handleClick={() => this.downloadFile()}
                      loading={this.state.confirmLoading}
                    />
                  </div>
                ) : (
                  <Upload {...props}>
                    <Button>
                      <Icon type='upload' />
                      重新上传
                    </Button>
                  </Upload>
                )}
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 518 519 520 521 522 523 524 525
                {this.state.isShow ? (
                  <div className={styles.attentionItem}>
                    <p>导入事项</p>
                    <p>1. 导入操作一次只能上传 1 EXCEL文件。</p>
                    <p>2. 导入文件最大文件大小上传 1 GB</p>
                    <p>3. 只能上传EXCEL文件(XLS, XLSX) 默认支持EXCEL 2003EXCEL 2007</p>
                    <p>4. 请将EXCEL文件的所有单元格格式设置为“文本”格式</p>
                  </div>
                ) : (
                  <div className={styles.error} style={{ marginTop: 20 }}>
                    <Tabs
                      activeKey={this.state.currentKey}
                      key={this.state.ch}
                      onChange={this.changePane}
                      type='card'>
                      {this.state.errData && this.state.errData.length == 0 ? (
                        ''
                      ) : (
                        <TabPane tab={<span style={{ color: 'red' }}>验证错误列表</span>} key='1'>
                          <Table
                            columns={column1}
                            size='small'
                            style={{ overflow: 'auto' }}
                            dataSource={this.state.errData}
                            bordered={true}
                            scroll={{ x: 'max-content' }}
                          />
                        </TabPane>
                      )}
                      <TabPane tab={<span style={{ color: 'green' }}>验证成功列表</span>} key='2'>
                        <Table
                          columns={column2}
                          size='small'
                          style={{ overflow: 'auto' }}
                          dataSource={this.state.sucData}
                          bordered={true}
                          scroll={{ x: 'max-content' }}
                        />
                      </TabPane>
                    </Tabs>
                  </div>
                )}
              </div>
          }
526 527
				</Modal>
			</span>
528 529
    );
  }
徐立's avatar
徐立 committed
530
}