<template>
  <div class="ChooseImg" style="width: 900px; max-width: 80vw;">
    <div style="margin:10px;" v-if="type==1|| type==0">选择图片</div>
    <div style="margin:10px;" v-if="type==2">选择音频</div>
    <div style="margin:10px;" v-if="type==3">选择视频</div>

    <el-row v-loading="loading" style="border: 1px solid rgb(227, 227, 227);">
      <el-col :span="24">
        <div style="margin-top: 10px;margin-left: 20px;display: flex;" class="appendInput">
          <el-input size="small" style="width:250px" placeholder="请输入内容" @keyup.enter.native="GetPageList" v-model="msg.MediaName">
            <el-button @click="GetPageList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <q-btn color="accent" size="sm" class="q-mr-md" icon="cloud_upload" style="margin-left: 15px;" @click="goadd" label="上传"></q-btn>
        </div>
        <!-- type=0  图片单选 -->
        <template v-if="type==0">
          <div class="basefix app-attachment-list" v-if="dataList && dataList.length>0">
            <el-tooltip v-for="(item,index) in dataList" :key="index" class="item" effect="dark"
              :content="item.MediaGroupName" placement="top-start">
              <div @click="PageSelect(item)" :class="getChecked(item) ? 'selected' :''"
                class="el-tooltip item app-attachment-item">
                <img :src="getIconLink(item.ImageUrl)" class="app-attachment-img" style="width: 100px; height: 100px;">
                <div class="app-attachment-name">{{item.MediaName}}</div>
              </div>
            </el-tooltip>
          </div>
         
        </template>
         <!-- type=1  图片多选 -->
        <template v-if="type==1">
          <div class="basefix app-attachment-list" v-if="dataList && dataList.length>0">
            <el-tooltip v-for="(item,index) in dataList" :key="index" class="item" effect="dark"
              :content="item.MediaGroupName" placement="top-start">
              <div @click="PageSelect(item)" :class="getChecked(item) ? 'selected' :''"
                class="el-tooltip item app-attachment-item">
                <img :src="getIconLink(item.ImageUrl)" class="app-attachment-img" style="width: 100px; height: 100px;">
                <div class="app-attachment-name">{{item.MediaName}}</div>
              </div>
            </el-tooltip>
          </div>
        </template>
        <!-- type2 音频 -->
        <template v-if="type==2">
          <div class="basefix app-attachment-list" v-if="dataList && dataList.length>0">
            <el-tooltip v-for="(x,y) in dataList" :key="y" class="item" effect="dark"
              :content="x.MediaGroupName" placement="top-start">
              <div @click="PageSelect(x)" :class="getChecked(x) ? 'selected' :''"
                class="el-tooltip item app-attachment-item">
                  <q-circular-progress show-value class="text-red q-ma-md" :max='parseInt(x.Minutes)'
                    size="70px" :thickness="0.2" color="light-blue" track-color="grey-3" @click.stop="playVoice(x.Path,y)">
                    <q-icon name="volume_up" class="q-mr-xs" />
                    <span style="font-size: 11px;">
                    </span>
                  </q-circular-progress>
                  <div class="app-attachment-name">{{x.MediaName}}</div>
              </div>
            </el-tooltip>
          </div>
        </template>
        <!-- type3 视频 -->
        <template v-if="type==3">
          <div class="basefix app-attachment-list" v-if="dataList && dataList.length>0">
            <el-tooltip v-for="(x,y) in dataList" :key="y" class="item" effect="dark"
              :content="x.MediaGroupName" placement="top-start">
              <div style="width:200px;height:185px;padding:10px;" @click.stop="PageSelect(x)" :class="getChecked(x) ? 'selected' :''"
                class="el-tooltip item app-attachment-item">
                  <video width="100%" height="140" controls="controls" v-if="x.Path">
                      <source :src="x.Path" type="video/mp4" />
                  </video>
                  <div class="app-attachment-name">{{x.MediaName}}</div>
              </div>
            </el-tooltip>

          </div>
        </template>
        <div style="width: 100%;display: flex;align-items: center;justify-content: center;height: 100px;" v-if="dataList.length==0">
          暂无数据
        </div>
        <div style="padding:0 10px 10px 0">
          <el-pagination style="text-align:right" background :current-page="currentPage"
            @current-change="handleCurrentChange" :page-size="msg.pageSize" layout="prev, pager, next,jumper"
            :total="PageCount">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <div style="margin:10px;text-align:right">
      <el-button size="small" @click="closeDialog">取消</el-button>
      <el-button size="small" type="primary" @click="SelectImgId">选定</el-button>
    </div>
    <div v-if="Isadd==true">
      <alladdsc :allclassifyList="allclassifyList" :type='msg.Type' @editsuccess="getchildren" :editobj='editobj'
                @getcancel='Isadd=false'></alladdsc>
    </div>
  </div>
</template>

<script>
    import alladdsc from '../components/alladdsc'
    import {
      GetContributeMediumGroupList,
  
    } from '../../../api/system/wechat';
  import {
    GetContributeMediumPage
  } from '../../../api/system/wechat';
  import BenzAMRRecorder from 'benz-amr-recorder'

  export default {
    name: 'ChooseImg',
    components: {
       alladdsc
    },
    props: {
      type: {
        type: Number,
        default: null
      },
    },
    data() {
      return {
        czType: 0,
        val: '',
        Id: '',
        currentPage: 1,
        msg: {
          pageIndex: 1,
          pageSize: 12,
          rowsPerPage: 12,
          MediaGroupId: 0, //分组
          Type: 1, //类型
          MediaName: ''
        },
        loading: false,
        groupList: [],
        pageMsgDig: false,
        selectId: -1,
        emitmsg: [],
        PageCount:0,
        dataList:[],
        playRec: null, //播放对象
        Isadd: false,
        editobj: null,
        allclassifyList:[],
      }
    },
    created() {
      this.getWeChatMediumGroupList()
    },
    computed: {

    },
    mounted() {
      if(this.type){
        if(this.type==1 || this.type==0){
          this.msg.Type =1
        }else{
          this.msg.Type = this.type;
        }
        
      }
      this.GetPageList();
    },
    methods: {
      getWeChatMediumGroupList() {
        GetContributeMediumGroupList({}).then(res => {
          this.allclassifyList = JSON.parse(JSON.stringify(res.Data))
        })
      },
       playVoice(_url, index) {
        // TODO 这里暂时没处理 音频播放中暂停
        let vm = this
        if (vm.voiceActive && (vm.voiceActive != index)) { //如果再放一个点击另一个上一个清0
          vm.dataList[vm.voiceActive].timevalue = 0
        }
        if (vm.playRec !== null) {
          vm.stopPlayVoice(index)
        }
        vm.playRec = new BenzAMRRecorder()
        //⚠️注意跨域问题
        vm.playRec.initWithUrl(_url).then(function () {
          vm.voiceActive = index
          vm.playRec.play()
          let timer = setInterval(() => {
            vm.dataList[index].timevalue += 0.1
            vm.$forceUpdate();
          }, 100);

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

          })
        }).catch((e) => {
          vm.$message.error('播放录音失败')
        })
      },
      //停止播放
      stopPlayVoice() {
        if (this.playRec) {
          if (this.playRec.isPlaying()) {
            this.playRec.stop()
          }
        }
      },
      closeDialog(){
        this.$emit('closeDia');
      },
      getChecked(item) {
        var isChecked = false;
        if (this.emitmsg && this.emitmsg.length > 0) {
          this.emitmsg.forEach(eItem => {
            if (eItem.Id == item.Id && !isChecked) {
              isChecked = true;
            }
          });
        }
        return isChecked;
      },
      //选择图片 
      PageSelect(item) {
        if(this.type!=1){//单选
          this.emitmsg = [];
          this.emitmsg.push(item)
        }else{//图片多选的时候
          if(this.emitmsg &&  this.emitmsg.length>0){//一个没有选择的时候
            let data = JSON.parse(JSON.stringify(this.emitmsg))
            let isyes = false
            data.forEach((eItem,eindex) => {
              if (eItem.Id == item.Id) {
                this.emitmsg.splice(eindex,1)
                isyes = true
              }
            });
            if(isyes== false){
              this.emitmsg.push(item)
            }
          }else{//有一个选中的时候
            this.emitmsg.push(item)
          }
        }
        this.selectId = item.Id;
      },
      SelectImgId() {
        if (this.emitmsg && this.emitmsg.length > 0) {
        var result = this.emitmsg;
        this.$emit('SelectId', result)
        }
        this.selectId = -1;
        this.emitmsg = [];
      },
      UploadImage(file) {
        this.UploadFileToTencent(this.FileType().GoodsImg, file.file, res => {
          if (res.resultCode == 1) {
            this.addpageMsg.Path = res.FileUrl;
            this.addpageMsg.Name = res.FileName;
            this.addPageList();
          }
        })
      },
      // 新增素材信息
      addPageList() {
        var upInfo = JSON.parse(localStorage.uploadInfo);
        if(upInfo){
          this.addpageMsg.PathType=upInfo.StoreType;
        }
        this.apipost("/api/product/SetGetMaterialInfo", this.addpageMsg, res => {
          if (res.data.resultCode == 1) {
            this.GetPageList();
          }
        })
      },
     
      handleCurrentChange(val) {
        this.msg.pageIndex = val;
        this.GetPageList();
      },
      GetPageList() {
        GetContributeMediumPage(this.msg).then(res => {
            this.loading = false
            this.dataList = res.Data.PageData;
            this.PageCount = res.Data.Count
            this.dataList.forEach(x => {
              x.check = false;
            })
          })
          .catch(err => {
            this.loading = false
          })
      },
      goadd(){
        this.Isadd = true;
      },
      getchildren(){
        this.handleCurrentChange(1)
        this.Isadd = false
      },
    },
  }

</script>

<style>
  .ChooseImg{
    background: #fff;
    width:1000px;
  }
  .ChooseImg .el-input.is-active .el-input__inner,
  .ChooseImg .el-input__inner:focus {
    border-color: #DCDFE6;
  }

  .ChooseImg .app-attachment-list .selected {
    box-shadow: 0 0 0 1px #1ed0ff;
    background: #daf5ff;
    border-radius: 5px;
  }

  .ChooseImg .selectActive .el-icon-tickets {
    color: #409EFF;
  }

  .ChooseImg .selectActive {
    color: #409EFF;
  }

  .ChooseImg .app-attachment-name {
    color: #666666;
    margin-top: 5px;
    font-size: 13px;
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
  }

  .ChooseImg .app-attachment-item .app-attachment-img {
    display: block;
  }

  .ChooseImg .app-attachment-upload i {
    font-size: 30px;
    color: #909399;
  }

  .ChooseImg .app-attachment-item {
    display: inline-block;
    cursor: pointer;
    position: relative;
    float: left;
    width: 120px;
    height: 140px;
    margin: 7.5px;
    text-align: center;
    padding: 10px 10px 0;
  }

  .ChooseImg .app-attachment-upload {
    box-shadow: none;
    border: 1px dashed #b2b6bd;
    height: 100px;
    width: 100px;
    margin: 17.5px;
    padding: 0;
  }

  .ChooseImg .app-attachment-list {
    padding: 5px;
    min-height: 475px;
  }

  .ChooseImg .appendInput .el-input__inner {
    border-right: none;

  }

  .ChooseImg .appendInput .el-input-group__append {
    background-color: #fff !important;
    border-left: none;
    padding: 0 15px;
  }
   .materialupload {
    width: 118px;
    height: 118px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
    background: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px;
  }

</style>
