<template>
  <div class="panorama con">
    <div class="top">
      <crumbs :list="tablist" />
    </div>
    <div class="second-line">
      <div class="btn">
        <button
          @mouseover.stop="showList = true"
          @click="$refs.uploadFile.click()"
          class="ui-button submit"
        >
          <span>上传素材</span>
          <i class="iconfont icon-material_prompt hover-tips hover-tips-upload-icon">
            <div>
              <div class="remark">请上传10MB以内、jpg/png格式的图片</div>
            </div>
          </i>
          <upload
            ref="uploadFile"
            :failString="'格式错误，请上传10MB以内、jpg/png格式的图片'"
            :limitFailStr="'过大，请上传10MB以内、jpg/png格式的图片'"
            accept-type="image/png,image/jpeg"
            media-type="image"
            :limit="10"
            @file-change="onFileChange"
          ></upload>
        </button>
      </div>
      <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="搜索素材"
          />
          <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="false"
        :data="list"
        class="table-list"
        ref="table-list"
      >
        <div slot-scope="{ data }" slot="header">
          {{ data.name }}
        </div>
        <div slot-scope="{ data, item, sub }" slot="item" style="width: 100%">
          <div v-if="sub.canclick" class="handle">
            <i
              class="iconfont icon-material_operation_editor hover-tips"
              @click="(showRename = true), (popupItem = item)"
            >
              <div>
                <div class="remark">重命名</div>
              </div>
            </i>
            <i class="iconfont icon-material_operation_delete hover-tips-warn" @click="del(item)">
              <div>
                <div class="remark">删除</div>
              </div>
            </i>
          </div>
          <div v-else-if="sub.type == 'image'" class="img">
            <img
              :id="'img' + item.id"
              :src="data + `?${Math.random()}`"
              alt=""
              @click="previewImage(item)"
            />
          </div>
          <span
            v-else
            :style="{ fontWeight: sub.fontweight, color: '#202020' }"
            >{{ data || "-" }}</span
          >
        </div>
      </tableList>
      <UploadTaskList class="upload-task-list" fileType="AUDIO" :taskList="uploadListForUI" @cancel-task="onCancelTask"></UploadTaskList>
      <div class="total-number" v-if="list.length !== 0 || hasMoreData">已加载{{list.length}}条</div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && lastestUsedSearchKey">
        <img :src="$noresult" alt="" />
        <span>未搜索到结果~</span>
      </div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && !lastestUsedSearchKey">
        <img :src="config.empty" alt="" />
        <span>暂无素材~</span>
        <button @click="$refs.uploadFile.click()" class="upload-btn-in-table">上传素材</button>
      </div>
    </div>

    <rename
      v-if="showRename"
      :item="popupItem"
      @rename="handleRename"
      @close="showRename = false"
    />
    <preview
      ref="image-previewer"
      :canFullScreen="false"
      :imageList="list.map(item => item.icon)"
      :imageTitleList="list.map(item => item.name)"
      @click-delete="onClickDeleteInPreview"
    />
  </div>
</template>

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

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

const TYPE = "image";

export default {
  components: {
    tableList,
    crumbs,
    rename,
    Upload,
    preview,
    UploadTaskList,
  },
  data() {
    return {
      config, // TODO: 没必要这么弄
      showRename: false,
      showList: false,
      popupItem: null,
      tabHeader: data,
      selectedArr: [],
      // 因为searchKey的变化经过debounce、异步请求的延时，才会反映到数据列表的变化上，所以是否显示、显示哪种无数据提示，也要等到数据列表变化后，根据数据列表是否为空，以及引发本次变化的那个searchKey瞬时值来决定。本变量就是用来保存那个瞬时值。
      lastestUsedSearchKey: '',
      isFilterFocus: false,

      searchKey: "",
      tablist: [
        {
          name: "图片",
          id: TYPE,
        },
      ],
      list: [],
      hasMoreData: true,
      isRequestingMoreData: false,
    };
  },
  computed: {
    ...mapState({
      uploadListForUI: 'uploadStatusListImage',
    })
  },
  mounted() {
  },
  watch: {
    searchKey: {
      handler: function () {
        this.refreshListDebounced()
      },
      immediate: false,
    },
  },
  methods: {
    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, false),
    handleRename(newName) {
      editMaterial(
        {
          id: this.popupItem.id,
          name: newName,
        },
        () => {
          this.$msg.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;
        }
      );
    },
    del(item) {
      this.$confirm({
        title: '删除素材',
        content: "确定要删除素材吗？",
        okText: '删除',
        ok: () => {
          delMaterial(item.id, () => {
            this.$msg.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));
                    i.createTime = i.createTime.substring(0, i.createTime.length - 3)
                    i.updateTime = i.updateTime.substring(0, i.updateTime.length - 3)
                    return i;
                  });
                  this.list = this.list.concat(newData)
                  if (this.list.length === data.data.total) {
                    this.hasMoreData = false
                  }
                  if (this.list.length === 0) {
                    this.$refs['image-previewer'].onClickClose()
                  }
                } else {
                  console.error('在素材列表里没找到要删除的那一项！');
                }

                this.isRequestingMoreData = false
                this.lastestUsedSearchKey = lastestUsedSearchKey
              },
              () => {
                this.isRequestingMoreData = false
                this.lastestUsedSearchKey = lastestUsedSearchKey
              }
            )
          });
        },
      });
    },
    previewImage(targetItem) {
      const index = this.list.findIndex((eachItem) => {
        return eachItem.id === targetItem.id
      })
      this.$refs['image-previewer'].show(index)
    },
    onFileChange(e) {
      e.files.forEach((eachFile, i) => {
        if (
          eachFile.type.indexOf("jpeg") <= -1 &&
          eachFile.type.indexOf("png") <= -1
        ) {
          setTimeout(() => {
            this.$msg({
              message: `“${eachFile.name}”格式错误，请上传10MB以内、jpg/png格式的图片`,
              type: "warning",
            });
          }, i * 100);
          return;
        }

        if (eachFile.name.substring(0, eachFile.name.lastIndexOf(".")).length > 50) {
          setTimeout(() => {
            this.$msg({
              message: `“${eachFile.name}”名称过长，请上传标题在50字以内的图片`,
              type: "warning",
            });
          }, i * 100);
          return;
        }

        let itemInUploadList = {
          title: eachFile.name,
          ifKnowProgress: true,
          progress: 0,
          status: 'LOADING',
          statusText: "正在上传素材",
          uid: `u_${this.$randomWord(true, 8, 8)}`,
          abortHandler: null,
        };
        
        itemInUploadList.abortHandler = uploadMaterial(
          {
            file: eachFile
          },
          {
            type: TYPE,
            uid: itemInUploadList.uid,
          },
          () => { // 上传成功
            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 = '素材上传失败'
            }
          },
          (progress) => {
            itemInUploadList.progress = progress
          }
        );

        this.uploadListForUI.push(itemInUploadList);
      });
    },
    onCancelTask(uid) {
      const index = this.uploadListForUI.findIndex((eachItem) => {
        return eachItem.uid === uid
      })
      this.uploadListForUI[index].abortHandler.abort()
    },
    getMoreMaterialItem() {
      this.isRequestingMoreData = true
      const lastestUsedSearchKey = this.searchKey
      getMaterialList(
        {
          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) => {
            i.fileSize = changeByteUnit(Number(i.fileSize));
            i.createTime = i.createTime.substring(0, i.createTime.length - 3)
            i.updateTime = i.updateTime.substring(0, i.updateTime.length - 3)
            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
        }
      );
    },
    onClickDeleteInPreview(index) {
      this.del(this.list[index])
    },
  },
};
</script>

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