<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 upload-icon">
            <div>
              <div class="remark">请上传2:1、120MB以内、jpg格式</div>
            </div>
          </i>
          <upload
            ref="uploadFile"
            :failString="'格式错误，请上传2:1、120MB以内、jpg格式的全景图片'"
            :limitFailStr="'过大，请上传2:1、120MB以内、jpg格式的全景图片'"
            accept-type="image/jpeg"
            media-type="image"
            :limit="120"
            @file-change="onFileChange"
          ></upload>
          <template v-if="showList">
            <UploadList
              @close="
                () => {
                  showList = false;
                }
              "
              :list="uploadList"
              @del="delUploadItem"
            />
          </template>
        </button>
      </div>
      <div class="filter">
        <div>
          <i
            @click="refreshList"
            class="iconfont icon-works_search"
          ></i>
          <input
            type="text"
            v-model="searchKey"
            @keyup.enter="refreshList"
            placeholder="搜索文件夹或素材"
          />
        </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>
        <!-- 内容各单元格 -->
        <!-- item：传给组件的data里各元素，对应单元格所在行（hasAuth都写成false）；data：item里各元素，对应每个单元格；sub：表头数据各元素，即单元各所属列的表头数据 -->
        <div slot-scope="{ data, item, sub }" slot="item" style="width: 100%">
          <!-- 操作型单元格 -->
          <div class="handle" v-if="sub.canclick">
            <i
              class="iconfont iconbs_list_cover hover-tips"
              @click="(showCover = true), (popupItem = item)"
            >
              <div>
                <div class="remark">设置封面</div>
              </div>
            </i>

            <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-warn" @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 + `?${Math.random()}`" alt="" />
          </div>
          <!-- 文字型单元格 -->
          <span
            v-else
            @click="
              sub.fontweight && ((showPreview = true), (popupItem = item))
            "
            :style="{ fontWeight: sub.fontweight, color: '#202020' }"
            >{{ data || "-" }}
          </span>
        </div>
      </tableList>
      <div class="total-number" v-if="list.length !== 0 || hasMoreData">已加载{{list.length}}条</div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && isClickSearch">
        <img :src="$noresult" alt="" />
        <span>未搜索到结果</span>
      </div>
      <div class="nodata" v-if="list.length == 0 && !hasMoreData && !isClickSearch">
        <img :src="config.empty" alt="" />
        <span>暂无素材~</span>
        <button @click="$refs.uploadFile.click()" class="upload-btn-in-table">上传素材</button>
      </div>
    </div>

    <uploadui/>


    <rename
      :show="showRename"
      :item="popupItem"
      @rename="handleRename"
      @close="showRename = false"
    />
    <preview
      :item="popupItem"
      :show="showPreview"
      @close="showPreview = false"
    />
    <cover
      @panocover="handlePanoCover"
      :item="popupItem"
      :show="showCover"
      @close="showCover = false"
    />
  </div>
</template>

<script>
import tableList from "@/components/table/index.vue";
import crumbs from "@/components/crumbs/index.vue";
import { data } from "./pano";
import rename from "../popup/rename";
import preview from "../popup/preview";
import cover from "../popup/cover";
import Upload from "@/components/shared/uploads/UploadMultiple";
import { getImgWH, changeByteUnit } from "@/utils/file";
import UploadList from "../components/uploadList";
import config from "@/config";

import uploadui from "../components/uploadui";


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

// 1切图，2失败，3成功

const TYPE = "pano";
const LONGPOLLINGTIME = 10;
const PAGE_SIZE = 20;

export default {
  name: 'Pano',
  components: {
    tableList,
    crumbs,
    rename,
    cover,
    preview,
    Upload,
    UploadList,
    uploadui
  },
  data() {
    return {
      config,
      isLongPolling: false, // TODO?
      showRename: false,
      showPreview: false,
      showCover: false,
      showList: false,
      popupItem: "",
      tabHeader: data,
      selectedArr: [],
      searchKey: "",
      tablist: [
        {
          name: "全景图片",
          id: TYPE,
        },
      ],
      list: [],
      hasMoreData: true,
      isRequestingMoreData: false,
      uploadList: [],
      isClickSearch: "",
    };
  },
  mounted() {
  },
  watch: {
    isLongPolling: {
      handler: function (newVal) {
        if (!newVal) {
          this.getMaterialList(true);
          this.clearinter();
        } else {
          this.Longpolling();
        }
      },
    },
  },
  methods: {
    clearinter() {
      this.interval && clearInterval(this.interval);
      this.interval = null;
    },
    Longpolling() {
      this.clearinter();
      this.interval = setInterval(() => {
        this._checkMStatus(true);
      }, LONGPOLLINGTIME * 1000);
    },
    handleRename(data) {
      editMaterial(
        {
          id: this.popupItem.id,
          name: data,
        },
        () => {
          this.$msg.success("修改成功");
          this.showRename = false;
          this.popupItem = "";
          this.getMaterialList();
        }
      );
    },
    handlePanoCover(data) {
      if (data.indexOf("http") > -1) {
        this.showCover = false;
        this.popupItem = "";
        return;
      }
      uploadCover({ file: data, filename: "cover.jpg" }, (res) => {
        if (res.code == 0) {
          editMaterial(
            {
              id: this.popupItem.id,
              icon: res.data,
            },
            () => {
              this.$msg.success("设置成功");
              this.showCover = false;
              this.popupItem = "";
              this.getMaterialList();
            }
          );
        }
      });
    },
    delUploadItem(index) {
      ~index && this.uploadList.splice(index, 1);
    },

    _checkMStatus(islongpolling = null) {
      let ids = this.uploadList.filter((item) => !!item.id);
      if (ids.length > 0) {
        checkMStatus(
          {
            ids: ids.map((item) => item.id),
            islongpolling,
          },
          (res) => {
            let tmp = [];
            this.uploadList.forEach((item) => {
              let titem = res.data.find((sub) => item.id == sub.id);
              if (titem) {
                tmp.push(titem);
              } else {
                tmp.push(item);
              }
            });
            this.uploadList = tmp;
            if (tmp.some((item) => item.status == 3)) {
              this.getMaterialList(true)
            }
            if (!tmp.some((item) => item.status == 1)) {
              this.isLongPolling = false;
            }
          }
        );
      }
    },
    del(item) {
      this.$confirm({
        content: "确定要删除素材吗？",
        ok: () => {
          delMaterial(item.id, () => {
            this.$msg.success("删除成功");
            this.getMaterialList();
          });
        },
      });
    },
    onFileChange(file) {
      let canUploadList = [];
      file.files.forEach((item,i)=>{
        let tmp = {
          statusStr: "上传中",
          status: 4,
          uid: `u_${this.$randomWord(true, 8, 8)}`,
          name: item.name,
        };
        if (item.type.indexOf("jpeg") <= -1) {
          setTimeout(() => {
            this.$msg({
              message: `“${item.name}”格式错误，请上传2:1、120MB以内、jpg格式的全景图片`,
              type: 'error'
            });
          }, i*100);
          return
        }
        let tname = item.name.substring(0, item.name.lastIndexOf("."));

        if (tname.length > 50) {
          setTimeout(() => {
            this.$msg({
              message: `“${item.name}”名称过长，请上传标题在50字以内的全景图片`,
              type: 'error'
            });
          }, i*100);
          return
        }
        this.uploadList.push(tmp);
        canUploadList.push({
          file: item,
          list: { ...tmp },
        });
      })


      let p = [];
      canUploadList.forEach((i) => {
        let promise = getImgWH(i);
        p.push(promise);
      });

      Promise.all(p).then((result) => {
        let pp = [];
        p.length > 0 &&
          result.forEach((data) => {
            let { width, height } = data.WH;
            if (width != 2 * height) {
              let idx = this.uploadList.findIndex(
                (sub) => sub.uid == data.list.uid
              );
              ~idx && this.uploadList.splice(idx, 1);
              return this.$msg({
                message: `“${data.file.name}”格式错误，请上传2:1、120MB以内、jpg格式的全景图片`,
                type: 'error'
              });
            }
            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) {
              response.forEach((item, i) => {
                this.uploadList[i].status = 5;
                let idx = this.uploadList.findIndex(sub=>sub.uid == item.data.tempId)
                if (idx>-1) {
                  if (item.code != 0) {
                    this.uploadList[idx].status = 5;
                  } else {
                    this.uploadList[idx] = {
                      ...this.uploadList[idx],
                      ...item.data,
                    };
                    this.isLongPolling = true;
                  }
                }
              });
            }
          });
      });
    },
    refreshList() {
      console.log('refresh');
      this.list = []
      this.isRequestingMoreData = false
      this.hasMoreData = true
      this.$refs['table-list'].requestMoreData()
    },
    getMoreMaterialItem(islongpolling = null) {
      this.isClickSearch = !!this.searchKey;
      this.isRequestingMoreData = true
      getMaterialList(
        {
          pageNum: Math.floor(this.list.length / PAGE_SIZE) + 1,
          pageSize: PAGE_SIZE,
          searchKey: this.searchKey,
          type: TYPE,
          islongpolling
        },
        (data) => {
          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.isRequestingMoreData = false
        },
        () => {
          this.isRequestingMoreData = false
        }
      );
    },
  },
};
</script>

<style lang="less" scoped>
.panorama {
  .upload-btn-in-table {
    width: 100px;
    height: 36px;
    background: linear-gradient(144deg, #00AEFB 0%, #0076F6 100%);
    border-radius: 22px;
    border: none;
    font-size: 14px;
    color: #FFFFFF;
    margin-top: 20px;
  }
  .hover-tips.upload-icon {
    &:hover {
      color: #fff !important;
      cursor: default;
    }
  }
}
</style>
<style lang="less" scoped>
@import "../style.less";
</style>