VoiceDialog.vue 10.1 KB
<template>
  <d2-dialog
    title="上传音频"
    :is-visible="visible"
    width="70%"
    @closeDialog="handleClose"
    @confirmDialog="handleConfirm"
  >
    <div
      class="voice-box"
      v-loading="loading"
    >
      <el-form
        ref="voiceForm"
        :model="dataForm"
        :rules="formRules"
        label-width="154px"
        size="small"
      >
        <el-form-item
          label="门店:"
          prop="storeMerchantNo"
        >
          <el-select
            v-model="dataForm.storeMerchantNo"
            class="form-select"
            filterable
            placeholder="请选择"
            @change="chaneMerchant"
          >
            <el-option
              v-for="(subItem, subIndex) in merchantList"
              :key="subIndex"
              :value="subItem.merchantId"
              :label="subItem.merchantName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="员工:"
          prop="badgeId"
        >
          <el-select
            v-model="dataForm.badgeId"
            class="form-select"
            filterable
            placeholder="请选择"
            :disabled="!dataForm.storeMerchantNo"
          >
            <el-option
              v-for="(subItem, subIndex) in employeeList"
              :key="subIndex"
              :value="subItem.badgeId"
              :label="subItem.employeeName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="导入文件:"
          prop="recordings"
        >
          <el-button
            size="small"
            class="import-button"
          >
            <i class="el-icon-plus"></i>
            上传文件
            <input
              type="file"
              ref="fileUpload"
              multiple
              class="import-input"
              accept=".mp3,.aac,.m4a"
              @change="importFile($event)"
            />
          </el-button>
          <template v-if="dataForm.recordings.length">
            <div class="file-table">
              <d2-table
                ref="qualityTable"
                :table-params="tableParams"
                :tableData="dataForm.recordings"
                :hasNum="false"
                :hasPage="false"
              >
                <template
                  slot="recordingFilename"
                  slot-scope="scope"
                >
                  <div class="file-name">
                    <img src="https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/voice-file.png">
                    {{scope.scope.recordingFilename}}
                  </div>
                </template>
                <template
                  slot="recordingStartTime"
                  slot-scope="scope"
                >
                  <el-date-picker
                    v-model="scope.scope.recordingStartTime"
                    type="datetime"
                    placeholder="请手动选择接待时间"
                    :picker-options="rangePickerOptions"
                  >
                  </el-date-picker>
                </template>
                <template
                  slot="auth-button-other"
                  slot-scope="scope"
                >
                  <el-button
                    type="text"
                    @click="del(scope)"
                  >删除</el-button>
                </template>

              </d2-table>

            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
  </d2-dialog>
</template>

<script type='text/ecmascript-6'>
import { listShop4sByRef } from "@api/merchant"
import { getMerchantEmployeeList, updateRecordings, getAliOSSToken } from "@api/serviceManage"
import OSS from 'ali-oss'
import * as dayjs from 'dayjs'
import { rangePickerOptions } from "@/common/format"
import reportTrackFunMixin from '@/mixins/reportTrackFunMixin'
export default {
  mixins: [reportTrackFunMixin],
  name: 'VoiceDialog',
  props: {
    visible: Boolean
  },
  data () {
    return {
      rangePickerOptions,
      client: null,
      loading: false,
      merchantList: [],
      employeeList: [],
      dataForm: {
        storeMerchantNo: '',
        badgeId: '',
        recordings: []
      },
      formRules: {
        storeMerchantNo: [{ required: true, message: '请选择门店', trigger: 'change' }],
        badgeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        recordings: [{
          required: true, trigger: 'change',
          validator: (rule, value, callback) => {
            try {
              if (!value.length) callback(new Error('请上传文件'))
              else {
                value.map(e => {
                  if (!e.recordingStartTime) throw '请选择接待开始时间'
                })
              }
              callback()
            } catch (error) {
              callback(new Error(error))
            }
          },
        }]
      },
      tableParams: {
        tableOption: {
          width: 60
        },
        tableColumns: [
          {
            label: '文件名',
            addHtml: 'recordingFilename'
          },
          {
            label: '接待开始时间',
            addHtml: 'recordingStartTime',
          },
        ]
      },
    }
  },
  watch: {
    visible (n) {
      if (n && !this.client) this.init()
    }
  },
  mounted () {
    this.getServiceStore()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const res = await getAliOSSToken()
        if (res) this.client = new OSS({
          // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
          region: 'oss-cn-shenzhen',
          // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
          accessKeyId: res.lsaccessKeyId,
          accessKeySecret: res.lsaccessKeySecret,
          stsToken: res.securityToken, // 从STS服务获取的安全令牌(SecurityToken)。
          // 填写Bucket名称。
          bucket: 'glsk-oss',
          secure: true
        })
        else this.$message.error('获取阿里云配置失败!')
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    handleClose () {
      this.loading = false
      this.dataForm = this.$options.data.call(this).dataForm
      this.$refs.voiceForm.resetFields()
      this.$refs.fileUpload.value = ''
      this.$emit('update:visible', false)
    },
    chaneMerchant (e) {
      this.dataForm.badgeId = ''
      this.employeeList = []
      this.getMerchantEmployeeList(e)
    },
    del ({ index }) {
      this.dataForm.recordings.splice(index, 1)
    },
    async importFile (event) {
      try {
        if (!this.client) {
          this.$refs.fileUpload.value = ''
          this.init()
          return this.$message.error('请重试!')
        }
        const data = event.srcElement.files
        console.log(data)
        this.loading = true
        for (let i = 0; i < data.length; i++) {
          await this.putObject(data[i])
        }
        this.loading = false
        this.$refs.fileUpload.value = ''
      } catch (error) {
        this.loading = false
        this.$refs.fileUpload.value = ''
      }
    },
    handleConfirm () {
      this.$refs.voiceForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            const { badgeId, recordings } = this.dataForm
            recordings.map(e => {
              e.badgeId = badgeId
              e.recordingStartTime = dayjs(e.recordingStartTime).format('YYYY-MM-DD HH:mm:ss')
            })
            this.setReportTrackData(0,'upload_audio',{recordings})
            console.log(recordings)
            const res = await updateRecordings({ recordings })
            console.log(res)
            if (res) {
              this.$message.success('上传成功')
              this.$emit('refresh')
              this.handleClose()
              this.loading = false
            }

          } catch (error) {
            this.loading = false
            this.$message.error(error)
          }
        }
      })
    },
    getServiceStore () {
      listShop4sByRef({
        yqMerchantId: ''
      }).then((res) => {
        this.merchantList = res || []
        console.log(res)
      })
    },
    async getMerchantEmployeeList (storeMerchantNo) {
      try {
        this.loading = true
        const res = await getMerchantEmployeeList({
          storeMerchantNo
        })
        this.employeeList = res
        this.loading = false
        console.log(res)
      } catch (error) {
        this.loading = false
      }
    },
    async putObject (data) {
      let date = '',
        [originalString] = data.name.split('.'),
        [_day, _time] = originalString.split('_')
      if (_day && _time) {
        const rex = /^\d+$/
        let year = originalString.slice(0, 4),
          month = originalString.slice(4, 6),
          day = originalString.slice(6, 8),
          time = originalString.slice(9, 13)
        if (rex.test(year) && rex.test(month) && rex.test(day) && rex.test(time)) date = `${year}-${month}-${day} ${time.slice(0, 2)}:${time.slice(2)}`
      }
      try {
        const result = await this.client.put(`quality/${data.name}`, data)
        console.log(result)
        const { length } = this.dataForm.recordings
        this.$set(this.dataForm.recordings, length, {
          recordingFilename: data.name,
          recordingStartTime: date,
          recordingUrl: result.url
        })
      } catch (error) {
        console.log(error)
        this.init()
        this.$message.error('上传失败')
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.form-select {
  width: 432px;
}
.file-table {
  margin-top: 6px;
}
.file-name {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666666;
  img {
    width: 16px;
    height: 16px;
    margin-right: 6px;
  }
}
.import-button {
  position: relative;
  .import-input {
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
}
</style>