<template>
  <div>
    <div class="back">
      <div class="record">
        <div
          class="play"
          v-for="(item, index) in recordList"
          :key="index"
        >
          <audio controls :ref="'audios' + item.id" style="display:none">
            <source :src="item.src" type="audio/ogg" />
          </audio>
          <van-icon
            name="clear"
            style="position:absolute;left: -.25rem;top: .12rem;"
            color="red"
            @click="delRecord(item.id)"
          />
          <p v-show="item.player"></p>
          <img src="@/assets/images/3.png" alt=""  @click="transmit(item.id)" />
          <span>{{ item.duration }}"</span>
        </div>
        <i style="display:block;width:100%;height:.8rem"></i>
        <button @click="start" style="margin-bottom:.1rem" v-if="recordList.length<1">
          点击录音
        </button>
      </div>
    </div>
    <div class="drawing-container" v-show="isEditor">
      <div id="tui-image-editor"></div>
      <van-button plain type="info" class="closes" @click="close"
        >取消</van-button
      >
      <van-button type="info" class="save" @click="save">保存</van-button>
    </div>
    <van-overlay :show="loading">
      <div class="wrapper" @click.stop>
        <van-loading size="24px" color="#0094ff" vertical
          >上传中，请稍等...</van-loading
        >
      </div>
    </van-overlay>
  </div>
</template>

<script>
// import { upload, uploadUrl, getImageOfMinio } from '@/api/contractor.js'
import { v4 } from 'uuid'
import 'tui-image-editor/dist/tui-image-editor.css'
import 'tui-color-picker/dist/tui-color-picker.css'
import ImageEditor from 'tui-image-editor'
const locale_zh = {
  ZoomIn: '放大',
  ZoomOut: '缩小',
  Hand: '手掌',
  History: '历史',
  Resize: '调整宽高',
  Crop: '裁剪',
  DeleteAll: '全部删除',
  Delete: '删除',
  Undo: '撤销',
  Redo: '反撤销',
  Reset: '重置',
  Flip: '镜像',
  Rotate: '旋转',
  Draw: '画',
  Shape: '形状标注',
  Icon: '图标标注',
  Text: '文字标注',
  Mask: '遮罩',
  Filter: '滤镜',
  Bold: '加粗',
  Italic: '斜体',
  Underline: '下划线',
  Left: '左对齐',
  Center: '居中',
  Right: '右对齐',
  Color: '颜色',
  'Text size': '字体大小',
  Custom: '自定义',
  Square: '正方形',
  Apply: '应用',
  Cancel: '取消',
  'Flip X': 'X 轴',
  'Flip Y': 'Y 轴',
  Range: '区间',
  Stroke: '描边',
  Fill: '填充',
  Circle: '圆',
  Triangle: '三角',
  Rectangle: '矩形',
  Free: '曲线',
  Straight: '直线',
  Arrow: '箭头',
  'Arrow-2': '箭头2',
  'Arrow-3': '箭头3',
  'Star-1': '星星1',
  'Star-2': '星星2',
  Polygon: '多边形',
  Location: '定位',
  Heart: '心形',
  Bubble: '气泡',
  'Custom icon': '自定义图标',
  'Load Mask Image': '加载蒙层图片',
  Grayscale: '灰度',
  Blur: '模糊',
  Sharpen: '锐化',
  Emboss: '浮雕',
  'Remove White': '除去白色',
  Distance: '距离',
  Brightness: '亮度',
  Noise: '噪音',
  'Color Filter': '彩色滤镜',
  Sepia: '棕色',
  Sepia2: '棕色2',
  Invert: '负片',
  Pixelate: '像素化',
  Threshold: '阈值',
  Tint: '色调',
  Multiply: '正片叠底',
  Blend: '混合色',
  Width: '宽度',
  Height: '高度',
  'Lock Aspect Ratio': '锁定宽高比例'
}

const customTheme = {
  'common.bi.image': '', // 左上角logo图片
  'common.bisize.width': '0px',
  'common.bisize.height': '0px',
  'common.backgroundImage': 'none',
  'common.backgroundColor': '#f3f4f6',
  'common.border': '1px solid #333',

  // header
  'header.backgroundImage': 'none',
  'header.backgroundColor': '#fff',
  'header.border': '0px',

  // load button
  'loadButton.backgroundColor': '#fff',
  'loadButton.border': '1px solid #ddd',
  'loadButton.color': '#222',
  'loadButton.fontFamily': 'NotoSans, sans-serif',
  'loadButton.fontSize': '12px',
  'loadButton.display': 'none', // 隐藏

  // download button
  'downloadButton.backgroundColor': '#fdba3b',
  'downloadButton.border': '1px solid #fdba3b',
  'downloadButton.color': '#fff',
  'downloadButton.fontFamily': 'NotoSans, sans-serif',
  'downloadButton.fontSize': '12px',
  'downloadButton.display': 'none', // 隐藏

  // icons default
  'menu.normalIcon.color': '#8a8a8a',
  'menu.activeIcon.color': '#555555',
  'menu.disabledIcon.color': '#ccc',
  'menu.hoverIcon.color': '#e9e9e9',
  'submenu.normalIcon.color': '#8a8a8a',
  'submenu.activeIcon.color': '#e9e9e9',

  'menu.iconSize.width': '24px',
  'menu.iconSize.height': '24px',
  'submenu.iconSize.width': '32px',
  'submenu.iconSize.height': '32px',

  // submenu primary color
  'submenu.backgroundColor': '#1e1e1e',
  'submenu.partition.color': '#858585',

  // submenu labels
  'submenu.normalLabel.color': '#858585',
  'submenu.normalLabel.fontWeight': 'lighter',
  'submenu.activeLabel.color': '#fff',
  'submenu.activeLabel.fontWeight': 'lighter',

  // checkbox style
  'checkbox.border': '1px solid #ccc',
  'checkbox.backgroundColor': '#fff',

  // rango style
  'range.pointer.color': '#fff',
  'range.bar.color': '#666',
  'range.subbar.color': '#d1d1d1',

  'range.disabledPointer.color': '#414141',
  'range.disabledBar.color': '#282828',
  'range.disabledSubbar.color': '#414141',

  'range.value.color': '#fff',
  'range.value.fontWeight': 'lighter',
  'range.value.fontSize': '11px',
  'range.value.border': '1px solid #353535',
  'range.value.backgroundColor': '#151515',
  'range.title.color': '#fff',
  'range.title.fontWeight': 'lighter',

  // colorpicker style
  'colorpicker.button.border': '1px solid #1e1e1e',
  'colorpicker.title.color': '#fff'
}
export default {
  name: 'VueCli4VantAbnormal',
  data () {
    return {
      loading: false,
      isEditor: false,
      fileList: [],
      loop: '',
      btRecoding: false,
      blackBoxSpeak: false,
      startY: '',
      recorder: '',
      duration: '1',
      player: false,
      reasonValue: '',
      voiceUrl: '',
      chartUrl: '',
      index: null,
      src: '',
      recordList: [],
      show: false,
      url: ''
    }
  },
  created () {},
  mounted () {
  },

  methods: {
    // 删除语音
    delRecord (id) {
      this.$dialog({
        message: '您将删除本条语音，删除后无法恢复，确认删除吗？',
        showCancelButton: true
      }).then(() => {
        this.recordList.forEach((item, index) => {
          if (item.id === id) {
            console.log('删除的url', item.src)
            this.recordList.splice(index, 1)
          }
        })
      }).catch(() => {
      })
    },
    // 实时获取播放时长
    async countAudioTime () {
      const audio = this.$refs['audios' + this.recordList[this.recordList.length - 1].id][0]
      while (isNaN(audio.duration) || audio.duration === Infinity) {
        // 延迟一会 不然网页都卡死
        // eslint-disable-next-line no-new
        await new Promise(resolve => setTimeout(resolve, 200))
        // 设置随机播放时间，模拟调进度条
        audio.currentTime = 10000000 * Math.random()
      }
      this.$notify({ type: 'success', message: `音频的总时长:${audio.duration}` })
      const num = Math.ceil(audio.duration)
      console.log('音频的总时长:', audio.duration)
      this.$set(this.recordList[this.recordList.length - 1], 'duration', num)
      this.$notify({ type: 'success', message: '测试成功！' })
    },

    preview (a, b) {
      console.log(a, b)
      this.index = b.index
      this.init(a.content)
      this.isEditor = true
    },
    fileImage () {
      this.recordItem()
    },
    close () {
      this.isEditor = false
    },

    // 开始录音
    start () {
      window.suplink.record().then(res => {
        this.recordList.push({
          src: res.data.voiceUrl,
          duration: null,
          player: false,
          id: v4()
        })
        this.$nextTick(() => {
          this.$refs['audios' + this.recordList[this.recordList.length - 1].id][0].load()
          this.countAudioTime()
        })
        // 拿到的是suplink的url，在提交之前，调用接口传递给后端，后期根据需求转格式
      })
    },
    recordItem () {
      this.voiceUrl = ''
      const arr = []
      this.recordList.forEach(item => {
        arr.push(uploadUrl({ url: item.src }))
      })
      Promise.all(arr).then(res => {
        res.forEach(item => {
          this.voiceUrl += item.data.data
        })
        this.$emit('recordItem', {
          voiceUrl: this.voiceUrl,
          fileList: this.fileList
        })
      })
    },
    // 语音条倒计时
    transmit (id) {
      console.log(id, '这是播放的id')
      console.log(this.$refs, '这是所有的ref')
      this.$refs['audios' + id][0].play()
      let index = null
      this.recordList.forEach((item, it) => {
        if (item.id === id) {
          console.log('这是播放的src', item.src)
          index = it
        }
      })
      this.recordList[index].player = true
      const num = this.recordList[index].duration * 1
      const time = setInterval(() => {
        this.recordList[index].duration =
          this.recordList[index].duration * 1 - 1
      }, 1000)
      setTimeout(() => {
        clearInterval(time)
        this.recordList[index].duration = num
        this.recordList[index].player = false
      }, num * 1000)
    },
    // 编辑图片
    init (url) {
      this.instance = new ImageEditor(
        document.querySelector('#tui-image-editor'),
        {
          includeUI: {
            loadImage: {
              path: url,
              name: 'image'
            },
            menu: ['resize', 'crop', 'rotate', 'draw', 'shape', 'icon', 'text'], // 底部菜单按钮列表 隐藏镜像flip和遮罩mask
            initMenu: 'draw', // 默认打开的菜单项
            menuBarPosition: 'bottom', // 菜单所在的位置
            locale: locale_zh, // 本地化语言为中文
            theme: customTheme // 自定义样式
          },
          cssMaxWidth: 350, // canvas 最大宽度
          cssMaxHeight: 700 // canvas 最大高度
        }
      )
      document.getElementsByClassName('tui-image-editor-main')[0].style.top =
        '45px' // 调整图片显示位置
      document.getElementsByClassName(
        'tie-btn-reset tui-image-editor-item help'
      )[0].style.display = 'none' // 隐藏顶部重置按钮
    },
    // 保存图片，并上传
    save () {
      const base64String = this.instance.toDataURL() // base64 文件
      console.log(base64String)
      this.fileList[this.index].content = base64String
      this.isEditor = false
      this.$notify({ type: 'success', message: '编辑成功！' })
      // upload file tie-draw-range tui-image-editor-range
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .tui-image-editor-help-menu.top {
  display: none !important;
}
/deep/ .tui-image-editor-newline.tui-image-editor-range-wrap {
  display: none !important;
}
.abnormal {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: rgb(248, 249, 249);
}
.reason {
  width: 100%;
  margin-top: 0.5rem;
}
.back {
  // height: 4.5rem;
  background: #fff;
  border-radius: 0.1rem;
  width: 96vw;
  margin: 2vw 0 0 2%;
}
.photo {
  // height: 1rem;
  width: 100%;
  display: inline-block;
  text-align: left;
  margin: 0.2rem;
}
.record {
  width: 100%;
  min-height: 2rem;
  position: relative;
  text-align: center;
  p {
    width: 0.1rem;
    height: 0.25rem;
    background: #fff;
    position: absolute;
    right: 10%;
    top: 20%;
    border-top-left-radius: 50%;
    border-bottom-left-radius: 50%;
    // border-bottom-left-radius: 50%;
    // transform: skew(30deg);
    // transform: rotate(90deg);
    animation: banner1 0.7s ease-in infinite;
  }
  .play {
    position: relative;
    margin-left: 50%;
    margin-bottom: 0.1rem;
    width: 50%;
    height: 0.4rem;
    img {
      width: 100%;
      height: 100%;
      border-radius: 0.05rem;
    }
    span {
      position: absolute;
      left: 43%;
      top: 30%;
      color: gray;
    }
  }
  .butt{
    width: 90%;
    height: 0.4rem;
    visibility: hidden;
  }
  button {
    position: absolute;
    bottom: 0;
    left: 5%;
    width: 90%;
    height: 0.4rem;
    background: #ccc;
    border-radius: 0.05rem;
  }
  .shade {
    width: 2rem;
    height: 2rem;
    border-radius: 0.2rem;
    background: #eee;
    position: relative;
    .blackBoxSpeakConent {
      width: 80%;
      height: 0.4rem;
      margin-left: 10%;
      line-height: 0.4rem;
      border-radius: 0.1rem;
    }
    .anima {
      position: absolute;
      left: 0.8rem;
      top: 0.2rem;
      width: 0.4rem;
      height: 0.6rem;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      animation: banner 2s infinite;
      p {
        width: 100%;
        height: 0.02rem;
        border: 1px solid #eee;
      }
      .q {
        animation-delay: 0s;
      }
      .qq {
        animation-delay: 0.5s;
      }
      .qqq {
        animation-delay: 1s;
      }
      .qqqq {
        animation-delay: 1.5s;
      }
    }
  }
}

@keyframes banner1 {
  0% {
    right: 10%;
  }
  100% {
    right: 17%;
  }
}
@keyframes banner {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
// 音量跳动
.bounce {
  position: absolute;
  left: 0.8rem;
  top: 0.2rem;
  width: 0.4rem;
  height: 0.6rem;
  ul {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    li {
      list-style: none;
      width: 100%;
      height: 1px;
      background-color: #fff;
      &:nth-child(1) {
        animation: love1 0.9s 0s infinite;
      }
      &:nth-child(2) {
        animation: love1 0.9s 0.1s infinite;
      }
      &:nth-child(3) {
        animation: love1 0.9s 0.2s infinite;
      }
      &:nth-child(4) {
        animation: love1 0.91s 0.3s infinite;
      }
    }
    @keyframes love1 {
      30%,
      50% {
        opacity: 1;
        transform: translateY(0);
      }
      70%,
      100% {
        opacity: 0;
        transform: translateY(0);
      }
    }
  }
}
.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.recording {
  width: 100%;
  height: 1rem;
  img {
    width: 60%;
    height: 100%;
  }
}
</style>
