<template>
  <div class="allAddSC" style="padding: 0;margin: 0;">
    <!-- 图片新增修改 -->
    <div v-if="type==1">
      <q-dialog v-model="Isadd" persistent>
        <q-card style="width: 520px; max-width: 80vw;max-height:80vh;">
          <q-card-section>
            <div class="text-h6">新建/修改图片素材</div>
          </q-card-section>
          <q-separator />
          <q-card-section class="q-pt-none" style="margin-top: 15px;padding: 20px;">
            <q-select filled stack-label option-value="Id" option-label="Name" v-model="addMsg.MediaGroupId"
              @input="$forceUpdate()" ref="Id" :options="allclassifyList" label="分组" :dense="false" emit-value
              map-options />
            <!-- <q-select filled stack-label option-value="Id" option-label="Name" class="q-mt-lg"
              v-model="addMsg.PlatformType" @input="$forceUpdate()" ref="Id" :options="platTypeList" label="平台类型"
              :dense="false" emit-value map-options /> -->
            <!-- <q-input clearable filled v-model="addMsg.MediaName" placeholder="请输入图片名称" class="q-mt-lg" maxlength="20" /> -->

            <div style="margin-top: 15px;">
              <div style="width:70px">上传图片:</div>
              <div style="margin-top: 15px;">
                <el-upload class="avatar-uploader" ref="upload" :action="importFileUrl2" v-if="ismodify==false"
                  :multiple="false" :on-success="successUpload" :show-file-list="false"
                  accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp">
                  <div v-if="imgPath==''" class="materialupload">
                    <i class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                  </div>
                  <q-img v-else :src="imgPath" style="width: 110px;height: 110px;border-radius: 6px;display: flex;">
                  </q-img>
                </el-upload>
                <q-img v-else :src="imgPath" style="width: 110px;height: 110px;border-radius: 6px;display: flex;"
                  v-if="ismodify"></q-img>
                <!-- <el-upload class="avatar-uploader materialupload" action="" :before-upload="uploadFile"
                  accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp" :show-file-list="false">
                  <i class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;" v-if="addMsg.Path==''"></i>
                  <q-img v-else :src="addMsg.Path" style="width: 110px;height: 110px;border-radius: 6px;display: flex;">
                  </q-img>
                </el-upload> -->
                <div style="margin-top: 20px;">
                  (图片大小不超过2M，图片名不能重复，支持JPG，JPEG及PNG格式)
                </div>
              </div>
            </div>
            <q-input clearable filled v-model="addMsg.MediaName" placeholder="请输入图片名称" class="q-mt-lg" maxlength="20" />

          </q-card-section>
          <q-separator />
          <q-card-actions align="right" class="bg-white">
            <q-btn class="q-mr-md" label="取消" @click="getcancel" />
            <q-btn color="accent" class="q-mr-md" label="确定" @click="saveImage()" />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
    <!-- //音频 -->
    <div v-if="type==2">
      <q-dialog v-model="Isadd" persistent>
        <q-card style="width: 520px; max-width: 80vw;">
          <q-card-section>
            <div class="text-h6">新建/修改音频</div>
          </q-card-section>
          <q-separator />
          <q-card-section class="q-pt-none" style="margin-top: 15px;padding: 20px;">
            <q-select filled stack-label option-value="Id" option-label="Name" v-model="addMsg.MediaGroupId"
              @input="$forceUpdate()" ref="Id" :options="allclassifyList" label="分组" :dense="false" emit-value
              map-options />
            <!-- <q-select filled stack-label option-value="Id" option-label="Name" class="q-mt-lg"
              v-model="addMsg.PlatformType" @input="$forceUpdate()" ref="Id" :options="platTypeList" label="平台类型"
              :dense="false" emit-value map-options /> -->
            <q-input clearable filled v-model="addMsg.MediaName" placeholder="请输入音频名称" class="q-mt-lg" maxlength="20" />
            <div style="margin-top: 15px;">
              <div style="width:70px">上传音频:</div>
              <q-circular-progress v-if='addMsg.Path' show-value class="text-red q-ma-md" :max='duration'
                :value="timevalue" size="70px" :thickness="0.2" color="light-blue" track-color="grey-3"
                @click.stop="playVoice(addMsg.Path)">
                <q-icon name="volume_up" class="q-mr-xs" />
                <span style="font-size: 11px;">
                  {{timevalue?timevalue.toFixed(1):0}}
                </span>
              </q-circular-progress>
              <div style="margin-top: 15px;">
                <el-upload class="avatar-uploader " action="" :before-upload="uploadFile" :show-file-list="false"
                  v-if="ismodify==false">
                  <q-btn color="accent" size="sm" class="q-mr-md" icon="cloud_upload" label="上传"
                    @click='stopPlayVoice()'>
                  </q-btn>
                </el-upload>
                <div style="margin-top: 20px;">
                  (音频上传大小不超过2MB，播放长度不超过60s,支持AMR格式。)
                </div>
              </div>
            </div>
          </q-card-section>
          <q-separator />
          <q-card-actions align="right" class="bg-white">
            <q-btn class="q-mr-md" label="取消" @click="getcancel(),stopPlayVoice()" />
            <q-btn color="accent" class="q-mr-md" label="确定" @click="saveaudio(),stopPlayVoice()" />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
    <!-- 视频 -->
    <div v-if="type==3">
      <q-dialog v-model="Isadd" persistent>
        <q-card style="width: 520px; max-width: 80vw;">
          <q-card-section>
            <div class="text-h6">新增视频</div>
          </q-card-section>
          <q-separator />
          <q-card-section class="q-pt-none" style="margin-top: 15px;padding: 20px;">
            <q-select filled stack-label option-value="Id" option-label="Name" v-model="addMsg.MediaGroupId"
              @input="$forceUpdate()" ref="Id" :options="allclassifyList" label="分组" :dense="false" emit-value
              map-options />
            <!-- <q-select filled stack-label option-value="Id" option-label="Name" class="q-mt-lg"
              v-model="addMsg.PlatformType" @input="$forceUpdate()" ref="Id" :options="platTypeList" label="平台类型"
              :dense="false" emit-value map-options /> -->
            <q-input clearable filled v-model="addMsg.MediaName" placeholder="请输入视频名称" class="q-mt-lg" maxlength="20" />
            <q-input clearable filled v-model="addMsg.Description" placeholder="请输入视频介绍" class="q-mt-lg" type="textarea"
              maxlength="300" counter />
            <div style="margin-top: 15px;">
              <div style="width:80px">视频封面图:</div>
              <div style="margin-top: 15px;">
                <div style="width:100px;height:100px;border:1px solid #d1d1d1;text-align:center;line-height:100px;"
                  @click="getImgChoice=true">
                  <i class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"
                    v-if="addMsg.VideoWXImage==''"></i>
                  <q-img v-else :src="addMsg.VideoWXImage" style="width: 100%;height: 100%;">
                  </q-img>
                </div>
                <!-- <el-upload class="avatar-uploader materialupload" action="" :before-upload="uploadFile"
                  accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp" :show-file-list="false">
                  <i class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;" v-if="addMsg.Path==''"></i>
                  <q-img v-else :src="addMsg.Path" style="width: 110px;height: 110px;border-radius: 6px;display: flex;">
                  </q-img>
                </el-upload> -->
                <div style="margin-top: 20px;">
                  (图片大小不超过2M，图片名不能重复，支持JPG，JPEG及PNG格式)
                </div>
              </div>
            </div>
            <div style="margin-top: 15px;">
              <div style="width:70px">上传视频:</div>

              <video width="320" height="240" controls="controls" v-if="addMsg.Path!=''">
                <source :src="addMsg.Path" type="video/mp4" />
              </video>
              <div style="margin-top: 15px;">
                <el-upload class="avatar-uploader " action="" :before-upload="uploadFile" :show-file-list="false"
                  v-if="ismodify==false">
                  <q-btn color="accent" size="sm" class="q-mr-md" icon="cloud_upload" label="上传">
                  </q-btn>
                </el-upload>
                <div style="margin-top: 20px;">
                  (视频上传大小不超过10M，支持MP4格式)
                </div>

              </div>
            </div>

          </q-card-section>
          <q-separator />
          <q-card-actions align="right" class="bg-white">
            <q-btn class="q-mr-md" label="取消" @click="getcancel" />
            <q-btn color="accent" class="q-mr-md" label="确定" @click="savevideo()" />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
    <!-- 选择文件 -->
    <q-dialog title="选择文件" v-model="getImgChoice" width="1200px">
      <ChooseImg @SelectId="SelectId" :type="1" @closeDia="getImgChoice=false"></ChooseImg>
    </q-dialog>
  </div>
</template>

<script>
  import BenzAMRRecorder from 'benz-amr-recorder'
  import ChooseImg from '../components/ChooseImg'
  import {
    wechatUploadSelfFile,
    UploadSelfFile
  } from "../../../api/common/common"; //上传图片
  import {
    SetContributeMediumInfo, //新增修改素材
    GetContributePlatfrom
  } from '../../../api/system/wechat';
  export default {
    components: {
      ChooseImg
    },
    name: "allAddSC",
    props: {
      allclassifyList: {
        type: Array,
        default: [],
      },
      type: {
        type: String,
        default: 1,
      },
      editobj: {
        type: Object,
        default: null,
      }

    },
    data() {
      return {
        Isadd: true,
        addMsg: {
          Id: 0,
          MediaGroupId: '', //	分组ID
          MediaName: '', //标题/名称
          Description: '', //视频介绍
          Type: this.type, //1图片 2 音频 3视频
          VideoImage: '', //视频封面图
          VideoWXImage: '', //视频封面图（微信地址） （修改时 素材库选择）	
          Path: '', //文件路径
          PlatformType: 1, //平台类型 枚举
          Minutes: '' //音频/视频 时长 00:00格式
        },
        platTypeList: [], //平台类型
        duration: 0, //音频中时长
        timevalue: 0, //音频播放到时间点
        playRec: null,
        imgPath: '',
        importFileUrl2: '',
        getImgChoice: false,
        ismodify: false, //是否修改
      }
    },
    created() {
      if (this.editobj != null) {
        this.addMsg = JSON.parse(JSON.stringify(this.editobj))
        this.ismodify = true
        if (this.type == 1) {
          this.imgPath = this.addMsg.ImageUrl;
        }
      }
      let address = process.env.API;
      this.importFileUrl2 = address + '/upload/UploadTemporaryFile'
    },
    mounted() {
      this.getPlatForm();
    },
    methods: {
      SelectId(obj) {
        this.addMsg.VideoWXImage = obj.url;
        this.getImgChoice = false;
      },
      //获取已开放平台
      getPlatForm() {
        GetContributePlatfrom({}).then(res => {
          if (res.Code == 1) {
            this.platTypeList = res.Data;
          }
        })
      },
      setWeChat() {
        SetContributeMediumInfo(this.addMsg).then(res => {
          this.$q.notify({
            icon: 'iconfont icon-chenggong',
            color: 'accent',
            timeout: 2000,
            message: res.Message,
            position: 'top'
          })
          this.$emit('editsuccess')
        })
      },
      getcancel() {
        this.$emit('getcancel')
      },
      successUpload(file) {
        if (file.Code == 1) {
          let address = process.env.API;
          let aOne = address.split('/api')[0];
          this.imgPath = aOne + file.Data.HttpPath;
          this.addMsg.Path = file.Data.Path;
          this.addMsg.MediaName = file.Data.Name;
        }
      },
      uploadFile(files) { //图片上传
        if (this.type == 1) { //图文和图片、小程序的时候处理
          let types = ['image/jpeg', 'image/jpg', 'image/png'];
          const isImage = types.includes(files.type);
          const isLtSize = files.size / 1024 / 1024 < 2;
          if (!isLtSize) {
            this.$q.notify({
              type: 'negative',
              message: `上传图片大小不能超过 2MB!`,
              position: 'top'
            })
            return false;
          }
          if (!isImage) {
            this.$q.notify({
              type: 'negative',
              message: `上传图片只能是 JPG、JPEG、PNG 格式!`,
              position: 'top'
            })
          } else {

          }
        }
        if (this.type == 2) { //音频上传
          // 文件类型进行判断
          let types = ['mp3', 'wma', 'wav', 'amr'];
          const isAudio = types.includes(files.type);
          const isLt2M = files.size / 1024 / 1024 < 2;
          let Times = this.getTimes(files)
          const isTime60S = Times >= 60 ? true : false;
          if (!isLt2M) {
            this.$q.notify({
              type: 'negative',
              message: `上传文件大小不能超过 2MB!!`,
              position: 'top'
            })
          } else {
            if (isTime60S) {
              this.$q.notify({
                type: 'negative',
                message: `上传文件时长不能超过60秒!!`,
                position: 'top'
              })
            } else {
              UploadSelfFile('wechatcatalogue', files, res => {
                if (res.Code == 1) {
                  let amr = new BenzAMRRecorder()
                  let that = this
                  amr.initWithUrl(res.FileUrl).then(function () {
                    that.duration = amr.getDuration();
                    if (Number(that.duration) >= 60) {
                      that.$q.notify({
                        type: 'negative',
                        message: `上传文件时长不能超过60秒!!`,
                        position: 'top'
                      })
                    } else {
                      that.$forceUpdate();
                      that.addMsg.Path = res.FileUrl;
                      that.addMsg.MediaName = res.FileName ? res.FileName : '';
                      that.addMsg.Minutes = parseInt(that.duration.toFixed());
                    }
                  }).catch((e) => {

                  })
                }
              })
            }
          }
        }
        if (this.type == 3) { //视频上传
          // 文件类型进行判断
          const isLt10M = files.size / 1024 / 1024 < 10;
          if (['video/mp4'].indexOf(files.type) == -1) {
            this.$q.notify({
              type: 'negative',
              message: `请上传正确的视频格式!`,
              position: 'top'
            })
            return false;
          }
          if (!isLt10M) {
            this.$q.notify({
              type: 'negative',
              message: `上传视频大小不能超过10MB哦!`,
              position: 'top'
            })
            return false;
          }
          var configObj = {
            isCreateCover: 1
          }
          UploadSelfFile('wechatcatalogue', files, res => {
            if (res.Code == 1) {
              let amr = new BenzAMRRecorder()
              let that = this
              amr.initWithUrl(res.FileUrl).then(function () {
                that.duration = amr.getDuration();
                that.addMsg.Path = res.FileUrl;
                that.addMsg.MediaName = res.FileName ? res.FileName : '';
                that.addMsg.Minutes = parseInt(that.duration.toFixed());
              }).catch((e) => {})
            }
          })
        }
      },
      getTimes(file) { //获取音频妙数
        var content = file;
        let audioDuration = 0
        //获取录音时长
        var url = URL.createObjectURL(content);
        //经测试，发现audio也可获取视频的时长
        var audioElement = new Audio(url);
        audioElement.addEventListener("loadedmetadata", function (_event) {
          audioDuration = parseInt(audioElement.duration);
        });
        return audioDuration
      },

      saveImage() { //图片提交
        if (this.addMsg.MediaGroupId == '') {
          this.$q.notify({
            type: 'negative',
            message: `请选择分组选择`,
            position: 'top'
          })
          return
        }
        if (this.addMsg.Path == '') {
          this.$q.notify({
            type: 'negative',
            message: `请上传图片`,
            position: 'top'
          })
          return
        }
        this.setWeChat()
      },
      saveaudio() { //音频
        if (this.addMsg.MediaGroupId == '') {
          this.$q.notify({
            type: 'negative',
            message: `请选择分组选择`,
            position: 'top'
          })
          return
        }
        if (this.addMsg.Path == '') {
          this.$q.notify({
            type: 'negative',
            message: `请上传音频`,
            position: 'top'
          })
          return
        }
        this.setWeChat()
      },
      savevideo() { //视频
        if (this.addMsg.MediaGroupId == '') {
          this.$q.notify({
            type: 'negative',
            message: `请选择分组选择`,
            position: 'top'
          })
          return
        }
        if (this.addMsg.Path == '') {
          this.$q.notify({
            type: 'negative',
            message: `请上传视频`,
            position: 'top'
          })
          return
        }
        this.setWeChat()
      },
      showUpLoadFile(i) {
        // 文件类型进行判断

        if (
          i.FileName.substring(
            i.FileName.lastIndexOf(".") + 1,
            i.FileName.length
          ).toUpperCase() == "PDF" ||
          i.FileName.substring(
            i.FileName.lastIndexOf(".") + 1,
            i.FileName.length
          ).toUpperCase() == "TXT"
        ) {
          this.previewPDF(i.Url);
        } else {
          window.open(
            "https://view.officeapps.live.com/op/view.aspx?src=" + i.FilePath
          );
        }
      },

      playVoice(_url) {
        // TODO 这里暂时没处理 音频播放中暂停
        let vm = this
        if (vm.playRec !== null) {
          vm.stopPlayVoice()
        }
        vm.playRec = new BenzAMRRecorder()
        //⚠️注意跨域问题
        vm.playRec.initWithUrl(_url).then(function () {
          vm.playRec.play()
          let timer = setInterval(() => {
            vm.timevalue += 0.1
            vm.$forceUpdate();
          }, 100);

          vm.playRec.onEnded(function () {
            vm.timevalue = 0
            clearInterval(timer); //停止
            setTimeout(() => {
              vm.$forceUpdate();
            }, 1000);

          })
        }).catch((e) => {

          vm.$message.error('播放录音失败')
        })
      },
      //停止播放
      stopPlayVoice() {
        if (this.playRec) {
          if (this.playRec.isPlaying()) {
            this.playRec.stop()
          }
        }
      },

    }
  }
</script>

<style>
  .allAddSC .Sysuser_Date .el-input--prefix .el-input__inner {
    background-color: red;
    border: 0;
  }

  .allAddSC .state-item {
    padding: 2px 5px;
    border-radius: 3px;
    text-align: center;
    font-size: 10px;
  }

  .allAddSC .frIdlist {
    padding: 3px 10px;
    border-radius: 3px;
    background: #EEEEEF;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
    margin-bottom: 5px;
    cursor: pointer;
  }

  .class-popover .q-pr-lg {
    padding-right: 0;
    margin-top: 20px;
  }

  .allAddSC .el-date-editor.el-input {
    width: 100%;
  }

  .allAddSC .el-date-editor.el-input input {
    background-color: transparent !important;
  }

  .allAddSC .el-range-editor .el-range-input {
    background: none;
  }

  .Sysuser_Date .el-input__inner {
    background: transparent !important;
    border: 0 !important;
  }

  .allAddSC .el-drawer.rtl {
    overflow: inherit;
  }

  .allAddSC .el-date-editor.el-input {
    width: 100%;
  }

  .allAddSC .el-date-editor.el-input input {
    background-color: transparent !important;
  }

  .allAddSC .el-range-editor .el-range-input {
    background: none;
  }

  .Sysuser_Date .el-input__inner {
    background: transparent !important;
    border: 0 !important;
  }

  .allAddSC .el-drawer.rtl {
    overflow: inherit;
  }

  .allAddSC .imgcard {
    width: 240px;
    margin: 0 15px 15px 0
  }

  .allAddSC .imgstyle {
    width: 100%;
    height: 120px;
    border-radius: 0;
  }

  .allAddSC .onetext {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 208px;
  }

  .addscfile .icon-excel,
  .addscfile .icon-pdf,
  .addscfile .icon-txt,
  .addscfile .icon-wenjian,
  .addscfile .icon-yasuobao,
  .addscfile .icon-shipin,
  .addscfile .icon-word {
    font-size: 38px;
    color: green;
    line-height: 75px;
  }

  .fullscreen {
    z-index: 999;
  }
</style>