step-first.vue 16.5 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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
<template>
  <div class="import-main" v-loading="loading">
    <div class="upload-container">
      <div class="upload-item" v-for="(item, index) in fileList" :key="item">
        <div class="upload-label" :style="{ width: textNum * 20 + 'px' }">
          <label v-if="item.flag">*</label>
          {{ item.templateName }}:
        </div>
        <div class="upload-desc">
          <div class="upload-btn">
            <el-button size="small">
              <i class="el-icon-plus"></i>
              {{ item.fileName ? '更换文件' : '上传文件' }}
            </el-button>
            <input type="file" style="opacity: 0" ref="file" accept="*" @change="uploadFile($event, item, index)" />
          </div>

          <a :href="item.templateUrl">下载模板</a>
          <div class="upload-tips" v-if="!item.fileName && !item.fileInfo">支持扩展名:xlsx、xls</div>
          <div class="upload-tips" v-if="item.fileInfo">
            <i class="el-icon-success"></i>
            文件格式正确({{ item.fileName }})
          </div>
          <div class="upload-tips" v-if="item.fileName && !item.fileInfo">
            <i class="el-icon-error"></i>
            文件格式错误,请更换文件({{ item.fileName }})
          </div>
        </div>
      </div>
      <div class="upload-item">
        <div class="upload-label" :style="{ width: textNum * 20 + 'px' }">
          备注:
        </div>

        <div class="upload-desc">
          <el-input type="textarea" maxlength="50" :rows="6" placeholder="为本次导入的数据添加备注" v-model="remarks"></el-input>
        </div>
      </div>
      <div class="upload-item">
        <div class="upload-label" :style="{ width: textNum * 20 + 'px' }">
          跟进人
          <el-popover placement="top" width="400" trigger="hover" content="用户点击短信中的链接后,将自动分配以下某位员工的企微名片,客户添加好友将自动回复后台所配置的欢迎语。">
            <img src="@/assets/img/question.png" slot="reference" class="count-item-question" />
          </el-popover>
          :
        </div>

        <div class="upload-desc">
          <div style="position: relative">
            <el-button size="small" @click="handleAddEmp">
              <i class="el-icon-plus"></i>
              选择跟进专员
            </el-button>
            <div class="el-input-tag input-tag-wrapper" v-show="staffIdList.length">
              <el-tag effect="plain" type="info" v-for="(tag, idx) in staffIdList" :key="idx" closable :disable-transitions="false" @close="remove(idx)">
                <i class="el-icon-user-solid"></i>
                {{ tag.staffName }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
    <select-emp ref="selectEmpForm" @selectTable="selectTable"></select-emp>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
import util from '@/utils/util'
import uploadInfo from '@/utils/upload'
import selectEmp from '@/components/selectEmp'
import MD5 from 'md5'
export default {
  name: 'step-first',

  props: {},
  components: {
    selectEmp
  },
  data() {
    return {
      textNum: 0,
      loading: false,
      staffIdList: [],
      tabelHeader: [],
      tabelHeaderModel: [],
      fileList: [],
      remarks: ''
    }
  },
  mounted() {
    this.merchantConfig()
  },
  methods: {
    async merchantConfig() {
      this.loading = true
      const fileList = (await this.$apis.square.merchantConfig({})) || []
      this.fileList = fileList.map(item => {
        this.textNum = this.textNum > item.templateName.length ? this.textNum : item.templateName.length + 1
        return {
          size: '',
          flag: !parseInt(item.mustUpload),
          fileName: '',
          templateName: item.templateName,
          fileUrl: '',
          fileInfo: '',
          templateUrl: item.templateUrl,
          BusinessTypeId: item.businessType,
          businessTypeName: item.businessName
        }
      })
      this.loading = false
      this.readWorkbookFromRemoteFile()
    },
    getUploadInfo() {
      for (let f of this.fileList) {
        if (!f.fileName && f.flag) {
          this.$message.error('请上传' + f.templateName)
          return false
        }
        if (!f.fileInfo && f.fileName) {
          this.$message.error(f.templateName + '文件格式错误,请更换文件')
          return false
        }
      }
      const staffIdList = this.staffIdList.map(item => {
        return item.staffId
      })
      return {
        fileList: this.fileList,
        remarks: this.remarks,
        staffIdList
      }
    },
    getDownloadModel() {
      this.$apis.square.downloadModel({}).then(res => {
        console.log(res)
      })
    },
    // 从网络上读取某个excel文件,url必须同域,否则报错
    async readWorkbookFromRemoteFile() {
      for (let f of this.fileList) {
        try {
          let tabelHeaderArr = await this.getTabelHeaderModel(f.templateUrl)
          this.tabelHeaderModel.push(tabelHeaderArr)
        } catch (error) {
          this.$message.error('读取失败')
        }
      }
    },
    getTabelHeaderModel(model_url) {
      const _this = this
      return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open('get', model_url, true)
        xhr.responseType = 'arraybuffer'
        xhr.onload = function(e) {
          if (xhr.status == 200) {
            var datat = new Uint8Array(xhr.response)
            var workbook = XLSX.read(datat, { type: 'array' })
            const wsname = workbook.SheetNames[0]
            const ws = workbook.Sheets[wsname]
            /* 数组转换 */
            const data = _this.getHeaderRow(ws)
            resolve(data)
          } else {
            reject()
          }
        }
        xhr.send()
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      /* sheet['!ref']表示所有单元格的范围,例如从A1到F8则记录为 A1:F8*/
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C,
        R = range.s.r /* 从第一行开始 */
      /* 按列进行数据遍历 */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* 查找第一行中的单元格 */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]

        let hdr = 'UNKNOWN ' + C // <-- 进行默认值设置
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        if (!hdr.includes('UNKNOWN')) {
          headers.push(hdr)
        }
      }
      return headers
    },
    compareHeader(file) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.onload = event => {
          /* 解析数据 */
          const bstr = event.target.result
          const wb = XLSX.read(bstr, { type: 'binary' })
          /* 获取文件的第一个工作表(WorkSheet) */
          const wsname = wb.SheetNames[0]
          const ws = wb.Sheets[wsname]
          if (!ws['!ref']) {
            this.$message.error('格式错误')
            this.loading = false
            return
          }
          const data = this.getHeaderRow(ws)
          resolve(data)
        }
        reader.readAsBinaryString(file)
      })
    },
    send(arr) {
      let max = 3 //最多允许同时执行的ajax次数
      var current = 0 //当前有多少ajax正在执行
      // var _name = getFileType(w.fileName);
      var _num = 0
      var len = arr.length
      var hasFile = false
      for (let i = len - 1; i >= 0; i--) {
        var _index = i
        var fileBase64 = uploadInfo.transformArrayBufferToBase64(arr[i])
        var oParams = uploadInfo.getParams(_index, fileBase64)
        var o = {}
        oParams.file = oParams.fileType + '@' + fileBase64

        o.method = 'POST'
        o.data = oParams
        //fileFragmentUpload(o);
        //如果存在url,则直接跳出循环
        if (hasFile) {
          return false
        }
        this.$apis.common.getUploadFileToken(o).then(res => {
          if (res.code == 0) {
            _num++
            var _obj = res.data

            // 如果有进度条,则设置对应的进度条属性

            //如果存在url,则直接跳出循环
            if (res.data.fileUrl) {
              hasFile = true
              return false
            }
          }
        })
      }
    },
    //创建worker分线程
    createWorker() {
      let self = this
      var myWorker = function() {
        // let that = this
        let w = {}
        this.addEventListener(
          'message',
          function(e) {
            var _obj = e.data
            var files = self.file
            console.log(self)
            var reader = new FileReader()

            w.config = _obj.config
            w.options = _obj.options
            w.file = _obj.file

            //var r1 = getToken(files);

            reader.readAsArrayBuffer(files)
            reader.onload = function(e) {
              var hexHash = MD5(e.target.res)
              if (hexHash) {
                console.log('加密结束:' + new Date().getTime())
              }
              var oParams = {}
              oParams.fileMD5 = hexHash
              oParams.file = e.target.result
              oParams.size = files.size

              //w.fileMD5 = hexHash;

              this.postMessage(oParams)
              /*var _arr = fileSlice(oParams);
                        console.log(_arr)
                        w.list = _arr;
                        Promise.all([r1]).then(res => {
                            checkFileIsUpload(hexHash).then(res => {
                                console.log(res);
                                if (res.code == 0) {
                                    send(_arr);
                                }
                            });
                        })*/
            }
          },
          false
        )
      }

      var workerData = new Blob(['(' + myWorker.toString() + ')()'], {
        type: 'text/javascript'
      })
      return workerData
    },

    async uploadFile(e, uploadItem, index) {
      const file = e.srcElement.files[0]
      let AllImgExt = '.xls|.xlsx'
      let extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      console.log(extName)
      if (AllImgExt.indexOf(extName) === -1) {
        this.$message.error('上传格式不正确')
        return false
      }
      const size = file.size / 1024 / 1024
      if (size > 8) {
        this.$message.error('单文件体积需小于8M')
        return
      }
      this.loading = true
      const header = await this.compareHeader(file)
      if (util.getArrayIsSubset(header, this.tabelHeaderModel[index])) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = event => {
          const imgFile = event.target.result
          const arrBase64 = imgFile.split(',')
          const fileInfo = file.name.split('.')[1] + '@' + arrBase64[1]
          uploadItem.fileInfo = fileInfo
          uploadItem.size = size
          uploadItem.fileName = file.name
          this.loading = false
          // const params = {}
          // console.log(fileInfo)
          // params.fileList = [{ file: fileInfo, fileType: 'doc' }]
          // this.$apis.common.pictureUpload(params).then(res => {
          //   uploadItem.fileUrl = res
          //   uploadItem.size = size
          //   uploadItem.fileName = file.name
          //   this.$refs.file.value = ''
          //   this.loading = false
          // })
        }
      } else {
        uploadItem.fileName = file.name
        uploadItem.fileInfo = ''
        this.loading = false
      }
    },
    // uploadFile(e, uploadItem, index) {
    //   const file = e.srcElement.files[0]
    //   let AllImgExt = '.xls|.xlsx'
    //   let extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
    //   console.log(extName)
    //   if (AllImgExt.indexOf(extName) === -1) {
    //     this.$message.error('上传格式不正确')
    //     return false
    //   }
    //   const size = file.size / 1024 / 1024
    //   if (size > 30) {
    //     this.$message.error('单文件体积需小于30M')
    //     return
    //   }
    //   const reader = new FileReader(file)
    //   reader.onload = event => {
    //     /* 解析数据 */
    //     const bstr = event.target.result
    //     const wb = XLSX.read(bstr, { type: 'binary' })
    //     /* 获取文件的第一个工作表(WorkSheet) */
    //     const wsname = wb.SheetNames[0]
    //     const ws = wb.Sheets[wsname]
    //     /* 数组转换 */
    //     const data = XLSX.utils.sheet_to_json(ws, { header: 1 })
    //     /* 进行表格数据更新 */
    //     uploadItem.fileName = file.name
    //     if (data && data.length > 0 && util.getArrayIsSubset(data[0], this.tabelHeaderModel[index])) {
    //       const arrBase64 = bstr.split(',')
    //       const fileInfo = file.name.split('.')[1] + '@' + arrBase64[1]
    //       this.$apis.common.pictureUpload({ file: fileInfo }).then(res => {
    //         uploadItem.fileUrl = res
    //         uploadItem.size = size
    //         this.$refs.file.value = ''
    //       })
    //     }
    //     /* 进行表格表头数据更新 */
    //     this.getHeaderRow(ws)
    //   }
    //   reader.readAsBinaryString(file)
    // },
    uploadFileSuccess(e) {
      let AllImgExt = '.xls|.xlsx'
      let extName = e.name.substring(e.name.lastIndexOf('.')).toLowerCase()
      console.log(extName)
      if (AllImgExt.indexOf(extName) === -1) {
        this.$message.error('上传格式不正确')
        return false
      }
      const size = e.size / 1024 / 1024
      if (size < 9) {
        // // 转码base64
        const reader = new FileReader()
        reader.readAsDataURL(e)
        reader.onload = event => {
          const imgFile = event.target.result
          const arrBase64 = imgFile.split(',')
          const fileInfo = e.name.split('.')[1] + '@' + arrBase64[1]
          this.$apis.common.pictureUpload({ file: fileInfo }).then(res => {
            this.fileInfo = res
            this.importName = e.name
            this.$refs.file.value = ''
          })
        }
      } else {
        this.$message.error('上传文件不可超过9M')
      }
    },
    //选择员工
    handleAddEmp() {
      this.$refs.selectEmpForm.init(this.staffIdList)
    },
    selectTable(item) {
      this.staffIdList = item.map(item => {
        return {
          staffId: item.relationId,
          staffName: item.staffName
        }
      })
    },
    remove(index) {
      this.staffIdList.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.import-main {
  margin: 60px auto 0px;
  width: 92%;
  .upload-item {
    display: flex;
    margin-top: 30px;
    font-size: 14px;
    .upload-label {
      font-size: 14px;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      text-align: right;
      min-width: 110px;
      label {
        color: #eb4e4e;
      }
      img {
        width: 14px;
        height: 14px;
        vertical-align: middle;
      }
    }
    .upload-desc {
      margin-top: -6px;
      .upload-btn {
        position: relative;
        display: inline-block;
        input {
          cursor: pointer;
          position: absolute;
          height: 100%;
          width: 100%;
          top: 0px;
          left: 0px;
          font-size: 0px;
        }
      }
      /deep/ .el-textarea {
        width: 500px;
      }
      a {
        color: #5850ff;
        margin-left: 10px;
        vertical-align: text-bottom;
      }
      .upload-tips {
        margin-top: 6px;
        font-size: 14px;
        font-weight: 400;
        color: #999999;
        line-height: 22px;
        i {
          color: #2cca74;
          &.el-icon-error {
            color: #eb4e4e;
          }
        }
      }
      .input-tag-wrapper {
        position: relative;
        font-size: 14px;
        background-color: #fff;
        background-image: none;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        box-sizing: border-box;
        color: #666;
        display: inline-block;
        outline: none;
        padding: 5px 5px 0px 5px;
        max-height: 68px;
        overflow: auto;
        flex-wrap: wrap;
        transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
        width: 500px;
        display: flex;
        align-items: center;
        margin-top: 6px;
        font-size: 14px;
        i {
          color: #75acff;
          margin-right: 3px;
          font-size: 14px;
        }
      }
      .el-tag {
        margin-right: 4px;
        height: 26px;
        line-height: 24px;
        margin-bottom: 5px;
      }
    }
  }
}
</style>