<template>
  <div class="panorama con">
    <div class="top">
      <crumbs :list="tablist"/>
      <div class="filter">
        <div>
          <input
            type="text"
            v-model="searchKey"
            @keyup.enter="(paging.current = 1) && getMaterialList()"
            placeholder="搜索素材"
          >
          <i @click="(paging.current = 1) && getMaterialList()" class="iconfont iconbs_search"></i>
        </div>
      </div>
    </div>
    <div class="btn">
                

      <button @mouseover.stop="showList=true"  @click="$refs.uploadFile.click();" class="ui-button ui-button-rect submit"><span>上传素材</span><i class="iconfont iconbs_upload"></i>
        <upload ref="uploadFile"
        :failString="'格式错误，请上传200MB以内、mp4格式的视频'"
        :limitFailStr="'过大，请上传200MB以内、mp4格式的视频'"
         accept-type="video/mp4" media-type="video" :limit="200"  @file-change="onFileChange"></upload>
        <template v-if="showList">
          <UploadList
            @close="
              () => {
                showList = false;
              }
            "
            :list="uploadList"
            @del="delUploadItem"
          />
        </template>
      </button>
    </div>
    <div class="list">
      <tableList @selection-change="data=>{selectedArr=data}" :header='tabHeader' :showLine='true' :selection='false' :data='list' class="table-list" >
        <div slot-scope="{data}" slot="header">
          {{data.name}}
        </div>
        <div slot-scope="{data,item,sub}" slot="item" style="width:100%">
          <div class="handle" v-if="sub.canclick">
            <i
              class="iconfont iconbs_list_edit hover-tips"
              @click="(showRename = true), (popupItem = item)"
            >
              <div>
                <div class="remark">重命名</div>
              </div>
            </i>
            <i class="iconfont iconlist_delete hover-tips" @click="del(item)">
              <div>
                <div class="remark">删除</div>
              </div>
            </i>
          </div>
          <div class="img" v-else-if="sub.type=='image'" 
            @click="(showPreview = true), (popupItem = item)"
          >
            <img :src="`${data}`||$thumb" alt="">
          </div>
          <span v-else @click="sub.fontweight&&((showPreview = true), (popupItem = item))" :style="{fontWeight:sub.fontweight,color:'#202020'}">{{data||'-'}}</span>
        </div>
      </tableList>
      <div class="nodata" v-if="list.length == 0">
        <img :src="$noresult" alt="">
        <span>{{isClickSearch?'未搜索到结果':'暂无素材，快去上传吧'}}</span>
      </div>
    </div>
    <div class="paging">
      <Paging
        v-if="paging.total>0"
        :paging="paging"
        @changeCurrent="changeCurrent"
      />
    </div>

    <rename :item="popupItem" :show='showRename' @rename="handleRename" @close="showRename=false" />
    <preview
          :item="popupItem"
          :show="showPreview"
          @close="showPreview = false"
        />
  </div>
</template>

<script>
import tableList from '@/components/table'
import crumbs from '@/components/crumbs'
import {data} from './video'
import rename from '../popup/rename'
import Paging from '../components/paging'
import Upload from "@/components/shared/uploads/UploadMultiple";
import { changeByteUnit } from '@/utils/file'
import preview from "../popup/preview";
import UploadList from "../components/uploadList";


import {
  getMaterialList,
  uploadMaterial,
  editMaterial,
  delMaterial
} from "@/api";


const TYPE = 'video'

export default {
  components:{
    tableList,
    preview,
    crumbs,
    rename,
    Paging,
    UploadList,
    Upload
  },
  data(){
    return {
      showRename:false,
      showList:false,      
      showPreview: false,
      popupItem: "",
      isClickSearch:'',
      tabHeader: data,
      selectedArr: [],
      searchKey:'',
      tablist:[{
        name:'视频',
        id:TYPE
      }],
      list:[],
      uploadList:[],
      paging: {
        pageSize: 12,
        pageNum: 1,
        total: 0,
        showSize: 4,
        current: 1
      }
    }
  },
  mounted() {
    this.getMaterialList();
  },
  watch:{
    'paging.pageNum':function () {
      this.getMaterialList()
    }
  },
  methods:{
    handleRename(data){
      editMaterial({
          id:this.popupItem.id,
          name:data
        },()=>{
          this.$tips({ content: "修改成功",icon:'ok'});
          this.showRename = false
          this.popupItem = ''
          this.getMaterialList()
        });
    },
    delUploadItem(index){
      ~index && this.uploadList.splice(index, 1)
    },
    del(item){
      this.$confirm({
          content: "是否删除？",
          ok: () => {
              delMaterial(item.id,()=>{
                this.$tips({ content: "删除成功",icon:'ok' });
                this.getMaterialList()
              });
          }
      });
    },
    onFileChange(file) {
      let canUploadList = []
      for (let i = 0; i < file.files.length; i++) {
        let item = file.files[i];
        let tmp = {
          statusStr: "上传中",
          status: 4,
          uid: `u_${this.$randomWord(true, 8, 8)}`,
          name: item.name,
        };
        if (item.type.indexOf("mp4") <= -1) {
          return this.$alert({
              content: `“${item.name}”格式错误，请上传200MB以内、mp4格式的视频`
          });
        }
        let tname= item.name.substring(0, item.name.lastIndexOf("."));
         if (tname.length > 50) {
          return this.$alert({
              content: `“${item.name}”名称过长，请上传标题在50字以内的视频`
            });
        }
        this.uploadList.push(tmp)
        canUploadList.push({
          file: item,
          list: { ...tmp },
        });
      }


      let p = []
      canUploadList.forEach(i => {
        let promise = new Promise((resolve)=>{
            resolve(i)
        })
        p.push(promise)
      })

    Promise.all(p).then(result=>{
        let pp = []
        p.length>0&&result.forEach(data => {
              let params = {}
              params['file'] = data.file
              let promise = new Promise((resolve, reject) => {
                uploadMaterial(params, {
                  type: TYPE,
                  uid: data.list.uid,
                }, response => {
                  resolve(response);
                },(err)=>{
                  reject(err)
                })
              }) 
              pp.push(promise)
        });
        pp.length>0&& Promise.all(pp).then((response) => {
            if (response.length > 0) {
              this.uploadList.forEach(item=>{
                item.status = 5
              }) 
              response.forEach((item, i) => {
                let idx = this.uploadList.findIndex(
                  (sub) => sub.uid == item.data.tempId
                );
                if (item.code == 0) {
                  if (idx > -1) {
                    this.uploadList.splice(idx,1)
                  }
                }
              });
              this.getMaterialList();
            }
          });
      })
    },
    changeCurrent(data){
      this.paging.pageNum = data
    },
    getMaterialList() {
      this.isClickSearch = !!this.searchKey
      getMaterialList(
        {
          pageNum: this.paging.pageNum,
          pageSize: this.paging.pageSize,
          searchKey: this.searchKey,
          type:TYPE
        },
        (data) => {
          
          this.list = data.data.list.map(i=>{
            i.icon = i.ossPath+this.$videoImg
            i.fileSize = changeByteUnit(Number(i.fileSize))
            return i
          })
          
          this.paging.pageNum = data.data.pageNum;
          this.paging.pageSize = data.data.pageSize;
          this.paging.total = data.data.total;

          
        }
      );
    }
  }
}
</script>

<style lang="less" scoped>
.panorama{
  
}
</style>
<style lang="less" scoped>
@import '../style.less';
</style>