<template>
  <div class="panorama con">
    <div class="top">
      <crumbs :list="folderPath" @click-path="onClickPath" />
    </div>
    <div class="second-line">
      <div class="btn">
        <button
          @mouseover.stop="showList = true"
          @click="onUploadFile"
          class="ui-button submit"
        >
          <span>{{upload_material}}</span>
          <i class="iconfont icon-material_prompt hover-tips hover-tips-upload-icon">
            <div>
              <div class="remark">{{audio_size}}</div>
            </div>
          </i>
          <upload
            ref="uploadFile"
            :failString="audio_fail"
            :limitFailStr="audio_limit"
            accept-type="audio/mp3"
            media-type="audio"
            :limit="20"
            @file-change="onFileChange"
          ></upload>
        </button>
      </div>
      <button
        class="ui-button submit"
        @click="isShowNewFolder = true"
      >
        {{$i18n.t(`gather.new_folder`)}}
      </button>
      <button
        class="ui-button cancel"
        @click="onClickMoveFolder"
      >
        {{$i18n.t(`gather.move_folder`)}}
      </button>
      <div class="filter">
        <div :class="{active: isFilterFocus}" @focusin="onFilterFocus" @focusout="onFilterBlur">
          <i class="iconfont icon-works_search search" ></i>
          <input
            type="text"
            v-model="searchKey"
            :placeholder="serch_material"
          />
          <i v-if="searchKey" @click="searchKey=''" class="iconfont icontoast_red del"></i>
        </div>
      </div>
    </div>
    <div class="list">
      <tableList
        @selection-change="
          (data) => {
            selectedArr = data;
          }
        "
        @request-more-data="getMoreMaterialItem"
        :canRequestMoreData="hasMoreData && !isRequestingMoreData"
        :header="tabHeader"
        :showLine="true"
        :selection="true"
        :data="list"
        class="table-list"
        ref="table-list"
      >
        <!-- 插到tableList组件各个header插槽，并通过插槽的headerItem作用域拿到表头各项 -->
        <div slot-scope="{ headerItem }" slot="header">
          {{ headerItem.name && $i18n.t(`zh_key.${headerItem.name}`)  }}
        </div>
        <div slot-scope="{ itemData, lineData, headerItem }" slot="tableItem" style="width: 100%">
          <div class="handle" v-if="headerItem.canclick">
            <i
              class="iconfont icon-material_operation_editor hover-tips"
              @click="onClickRename(lineData)"
            >
              <div>
                <div class="remark">{{rename}}</div>
              </div>
            </i>
            <i
              class="iconfont icon-material_operation_delete hover-tips-warn"
              @click="del(lineData)"
            >
              <div>
                <div class="remark">{{deltips}}</div>
              </div>
            </i>
          </div>
          <div
            v-else-if="headerItem.type == 'audio' && lineData.type !== 'dir'"
            class="audio"
          >
            <v-audio
              :vkey="lineData.id"
              :idleft="`_${$randomWord(true, 8, 8)}`"
              :idright="`_${$randomWord(true, 8, 8)}`"
              :myAudioUrl="itemData"
            ></v-audio>
          </div>
          <div
            v-else-if="headerItem.type == 'audio' && lineData.type === 'dir'"
            class="img dirIcon"
          >
            <img
              :src="require('@/assets/images/icons/folder-blue.png')"
              alt=""
              @click="onClickFolder(lineData)"
            />
          </div>
          <span
            v-else
            class="textItem"
            :class="{
              dirName: headerItem.key === 'name' && lineData.type === 'dir'
            }"
            @click="(headerItem.key === 'name' && lineData.type === 'dir') ? onClickFolder(lineData): null"
          >
            {{ itemData || "-" }}
          </span>
        </div>
      </tableList>
      <UploadTaskList class="upload-task-list" fileType="AUDIO" :taskList="uploadListForUI" :targetFolderId="currentFolderId" @cancel-task="onCancelTask"></UploadTaskList>
      <div class="total-number" v-if="list.length !== 0 || hasMoreData">{{had_load}}</div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && lastestUsedSearchKey">
        <img :src="$noresult" alt="" />
        <span>{{no_serch_result}}</span>
      </div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && !lastestUsedSearchKey">
        <img :src="config.empty" alt="" />
        <span>{{no_material_result}}</span>
        <button @click="$refs.uploadFile.click()" class="upload-btn-in-table">{{upload_material}}</button>
      </div>
    </div>

    <CreateFolder
      v-if="isShowNewFolder"
      :validate=validateNewFolderName
      @close="isShowNewFolder = false"
      @submit="onSubmitNewFolder"
    />
    <RenameFolder
      v-if="isShowRenameFolder"
      :oldName="popupItem.name"
      :validate=validateRenameFolderName
      @close="isShowRenameFolder = false"
      @submit="onSubmitRenameFolder"
    />
    <rename
      v-if="showRename"
      :item="popupItem"
      @rename="handleRename"
      @close="showRename = false"
    />
  </div>
</template>

<script>
import config from "@/config";
import tableList from "@/components/table";
import crumbs from "@/components/crumbs";
import { data } from "./audio";
import rename from "../popup/rename";
import vAudio from "@/components/audio/index.vue";
import Upload from "@/components/shared/uploads/UploadMultiple";
import { changeByteUnit } from "@/utils/file";
import UploadTaskList from "../components/uploadList1.1.0.vue";
import { debounce } from "@/utils/other.js"
import { mapState } from 'vuex';
import {i18n} from "@/lang"
import folderMixinFactory from "../folderMixinFactory.js";

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

const TYPE = "audio";

const folderMixin = folderMixinFactory(TYPE)

export default {
  mixins: [
    folderMixin,
  ],
  components: {
    tableList,
    crumbs,
    rename,
    Upload,
    vAudio,
    UploadTaskList,
  },
  data() {
    return {
      upload_material: i18n.t("gather.upload_material"),
      audio_size: i18n.t("gather.audio_size"),
      audio_limit: i18n.t("gather.audio_limit"),
      audio_fail: i18n.t("gather.audio_fail"),
      serch_material: i18n.t("gather.serch_material"),
      rename: i18n.t("gather.rename"),
      deltips: i18n.t("gather.delete"),
      no_serch_result: i18n.t("gather.no_serch_result"),
      no_material_result: i18n.t("gather.no_material_result"),


      config,
      showRename: false,
      showList: false,
      popupItem: null,
      tabHeader: data,
      selectedArr: [],
      
      // 因为searchKey的变化经过debounce、异步请求的延时，才会反映到数据列表的变化上，所以是否显示、显示哪种无数据提示，也要等到数据列表变化后，根据数据列表是否为空，以及引发本次变化的那个searchKey瞬时值来决定。本变量就是用来保存那个瞬时值。
      lastestUsedSearchKey: '',
      isFilterFocus: false,
      searchKey: "",
      list: [],
      hasMoreData: true,
      isRequestingMoreData: false,
    };
  },
  computed: {
    ...mapState({
      uploadListForUI: 'uploadStatusListAudio',
    }),
    had_load(){
      return i18n.t("gather.had_load",{msg:this.list.length})
    }
  },
  mounted() {
  },
  watch: {
    searchKey: {
      handler: function () {
        this.refreshListDebounced()
      },
      immediate: false,
    },
  },
  methods: {
    onUploadFile(){
      checkUserSize({},(data)=>{
        //判断已用是否大于3G
        if ((data.data / 1024 / 1024) > 3) {
          this.$alert({ content: i18n.t("tips_code.FAILURE_3024") });
        }else{
          this.$refs.uploadFile.click()
        }
      })
    },
    onFilterFocus() {
      this.isFilterFocus = true
    },
    onFilterBlur() {
      this.isFilterFocus = false
    },
    refreshListDebounced: debounce(function() {
      this.list = []
      this.isRequestingMoreData = false
      this.hasMoreData = true
      this.$refs['table-list'].requestMoreData()
    }, 700, true),
    stopAllAudio() {
      Array.from($("audio")).forEach((item) => {
        if (!item.paused) {
          item.pause();
        }
      });
    },
    handleRename(newName) {
      editMaterial(
        {
          id: this.popupItem.id,
          name: newName,
        },
        () => {
          this.$msg.success(i18n.t("gather.edit_success"));
          const index = this.list.findIndex((eachItem) => {
            return eachItem.id === this.popupItem.id
          })
          if (index >= 0) {
            this.list[index].name = newName
          } else {
            console.error('在素材列表里没找到要重命名的那一项！');
          }
          this.showRename = false;
          this.popupItem = null;
        }
      );
    },
    onClickRename(lineData) {
      this.popupItem = lineData
      if (lineData.type !== 'dir') {
        this.showRename = true
      } else {
        this.isShowRenameFolder = true
      }
    },
    del(item) {
      this.$confirm({
        title: i18n.t("gather.delete_material"),
        content: i18n.t("gather.comfirm_delete_material"),
        okText: i18n.t("gather.delete"),
        ok: () => {
          delMaterial(item.id, () => {
            this.$msg.success(i18n.t("gather.delete_success"));
            this.isRequestingMoreData = true
            const lastestUsedSearchKey = this.searchKey
            getMaterialList(
              {
                pageNum: this.list.length + 1,
                pageSize: 1,
                searchKey: this.searchKey,
                type: TYPE,
              },
              (data) => {
                const index = this.list.findIndex((eachItem) => {
                  return eachItem.id === item.id
                })
                if (index >= 0) {
                  this.list.splice(index, 1)
                  const newData = data.data.list.map((i) => {
                    i.fileSize = changeByteUnit(Number(i.fileSize));
                    return i;
                  });
                  this.list = this.list.concat(newData)
                  if (this.list.length === data.data.total) {
                    this.hasMoreData = false
                  }
                  this.$bus.emit('deletedAudio') // 各个Audio组件需要重新初始化
                } else {
                  console.error('在素材列表里没找到要删除的那一项！');
                }

                this.isRequestingMoreData = false
                this.lastestUsedSearchKey = lastestUsedSearchKey
              },
              () => {
                this.isRequestingMoreData = false
                this.lastestUsedSearchKey = lastestUsedSearchKey
              }
            )
          });
        },
      });
    },
    onFileChange(e) {
      e.files.forEach((eachFile, i) => {
        if (eachFile.name.toLowerCase().indexOf("mp3") <= -1) {
          setTimeout(() => {
            this.$msg({
              message: `“${eachFile.name}”${i18n.t("gather.audio_fail")}`,
              type: "warning",
            });
          }, i * 100);
          return;
        }

        if (eachFile.name.substring(0, eachFile.name.lastIndexOf(".")).length > 50) {
          setTimeout(() => {
            this.$msg({
              message: `“${eachFile.name}”${i18n.t("gather.too_long_word_audio")}`,
              type: "warning",
            });
          }, i * 100);
          return;
        }

        let itemInUploadList = {
          title: eachFile.name,
          ifKnowProgress: true,
          progress: 0,
          status: 'LOADING',
          statusText: i18n.t("gather.uploading_material"),
          uid: `u_${this.$randomWord(true, 8, 8)}`,
          abortHandler: null,
          parentFolderId: this.currentFolderId,
        };
        
        itemInUploadList.abortHandler = uploadMaterial(
          {
            dirId: this.currentFolderId,
            file: eachFile,
            temId: itemInUploadList.uid,
            type: TYPE,
          },
          () => { // 上传成功
            const index = this.uploadListForUI.findIndex((eachItem) => {
              return eachItem.uid === itemInUploadList.uid
            })
            this.uploadListForUI.splice(index, 1)
            this.refreshListDebounced()
          },
          (err) => {
            if (err.statusText === 'abort') { // 用户取消了上传任务。
              const index = this.uploadListForUI.findIndex((eachItem) => {
                return eachItem.uid === itemInUploadList.uid
              })
              this.uploadListForUI.splice(index, 1)
            } else {
              itemInUploadList.status = 'FAIL'
              itemInUploadList.statusText = i18n.t("gather.material_upload_fail")
            }
          },
          (progress) => {
            itemInUploadList.progress = progress
          }
        );

        this.uploadListForUI.push(itemInUploadList);
      });
    },
    onCancelTask(uid) {
      const index = this.uploadListForUI.findIndex((eachItem) => {
        return eachItem.uid === uid
      })
      if (this.uploadListForUI[index].status === 'LOADING') {
        this.uploadListForUI[index].abortHandler.abort()
      } else {
        this.uploadListForUI.splice(index, 1)
      }
    },
    getMoreMaterialItem() {
      this.isRequestingMoreData = true
      const lastestUsedSearchKey = this.searchKey
      getMaterialList(
        {
          dirId: this.currentFolderId,
          pageNum: Math.floor(this.list.length / config.PAGE_SIZE) + 1,
          pageSize: config.PAGE_SIZE,
          searchKey: this.searchKey,
          type: TYPE,
        },
        (data) => {
          const newData = data.data.list.map((i) => {
            if (i.type !== 'dir') {
              i.fileSize = changeByteUnit(Number(i.fileSize));
            }
            return i;
          });
          this.list = this.list.concat(newData)
          if (this.list.length === data.data.total) {
            this.hasMoreData = false
          }
          this.isRequestingMoreData = false
          this.lastestUsedSearchKey = lastestUsedSearchKey
        },
        () => {
          this.isRequestingMoreData = false
          this.lastestUsedSearchKey = lastestUsedSearchKey
        }
      );
    },
  },
};
</script>

<style lang="less" scoped>
</style>
<style lang="less" scoped>
@import "../style.less";
</style>