<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="'格式错误，请上传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="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_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" @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="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
      :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";
import crumbs from "@/components/crumbs";
import { data } from "./pano";
import rename from "../popup/rename";
import preview from "../popup/preview";
import cover from "../popup/cover";
import Paging from "../components/paging";
import Upload from "@/components/shared/uploads/UploadMultiple";
import { getImgWH, changeByteUnit } from "@/utils/file";
import UploadList from "../components/uploadList";

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

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

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

export default {
  components: {
    tableList,
    crumbs,
    rename,
    cover,
    Paging,
    preview,
    Upload,
    UploadList
  },
  data() {
    return {
      isLongPolling: false,
      showRename: false,
      showPreview: false,
      showCover: false,
      showList: false,
      popupItem: "",
      tabHeader: data,
      selectedArr: [],
      searchKey: "",
      tablist: [
        {
          name: "全景图片",
          id: TYPE,
        },
      ],
      list: [],
      uploadList: [],
      isClickSearch: "",
      paging: {
        pageSize: 8,
        pageNum: 1,
        total: 0,
        showSize: 4,
        current: 1,
      },
    };
  },
  mounted() {
    this.getMaterialList();
  },
  watch: {
    "paging.pageNum": function () {
      this.getMaterialList();
    },
    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;
                  }
                }
              });
            }
          });
      });
    },
    changeCurrent(data) {
      this.paging.pageNum = data;
    },
    getMaterialList(islongpolling = null) {
      this.isClickSearch = !!this.searchKey;

      getMaterialList(
        {
          pageNum: this.paging.pageNum,
          pageSize: this.paging.pageSize,
          searchKey: this.searchKey,
          type: TYPE,
          islongpolling
        },
        (data) => {
          this.list = data.data.list.map((i) => {
            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>