<template>
  <com-head :options="headList" showCtrl >
    <el-form label-width="90px" :inline="true" >
      <el-form-item label="場景名：" >
        <el-input v-model="search.state.sceneName" placeholder="請輸入"></el-input>
      </el-form-item>
      <el-form-item label="相機SN碼：">
        <el-input v-model="search.state.snCode" placeholder="請輸入"></el-input>
      </el-form-item>
      <el-form-item class="searh-btns">
        <el-button @click="search.reset">重置</el-button>
        <el-button type="primary" @click="search.submit">查詢</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer">
    <div class="body-head">
      <h3>場景列表</h3>
      <div class="table-ctrl-right">
        <!-- <el-button type="primary" v-if="currModel === 2 && auth.belong" @click="editCompanyHandle" :disabled="!dataList.state.length">場景歸屬</el-button>
        <el-button type="primary" v-if="currModel === 2 && auth.delete" @click="dataList.deleteSelect" :disabled="!dataList.state.length">刪除</el-button> -->
        <!-- <el-input placeholder="搜索場景" suffix-icon="el-icon-search" class="search-scene" v-model="search.state.sceneName" style="width: auto" /> -->

        <ul class="pathul">
          <li v-for="item in folderPathShow" @click="handlePathClick(item)" :key="item">
            {{ item.name }}
          </li>
        </ul>

        <i
          class="el-icon-folder-add"
          @click="
            addOrUpdateFold({
              parentId: search.state.folderId || '',
              name: '',
            })
          "
        ></i>
        <i class="el-icon-menu" :class="{ active: currModel === 1 }" @click="currModel = 1"></i>
        <i class="el-icon-s-fold" :class="{ active: currModel === 2 }" @click="currModel = 2"></i>
      </div>
    </div>

    <el-table v-if="currModel === 2" ref="multipleTable" :data="dataList.state" tooltip-effect="dark" style="width: 100%">
      <!-- @row-click="selectRow"
      @selection-change="dataList.changeSelectRows" -->
      <!-- status  0表示未建好，1表示建好，-1表示出錯 -->
      <!-- <el-table-column type="selection" width="55" v-if="auth.belong || auth.delete"></el-table-column> -->
      <el-table-column label="場景封面" v-slot:default="{ row }">
        <div class="table-img" @click.stop="gotoLink(row)">
          <img src="@/assets/image/folder.png" v-if="row.isFolder" />
          <img src="@/assets/image/vrmodel-err.png" v-else-if="row.status === -1" />
          <img src="@/assets/image/vrmodel-calc.png" v-else-if="row.status === 0" />
          <img src="@/assets/image/vrmodel-fengcun.png" v-else-if="row.payStatus !== 1" />
          <img :src="`${row.thumb}?time=${Date.now()}`" v-else />

          <!-- <div v-if="row.status === 0">計算中</div> -->
        </div>
      </el-table-column>
      <el-table-column label="標題" v-slot:default="{ row }">
        {{ row.isFolder ? row.name : row.sceneName }}
      </el-table-column>

      <el-table-column label="S/N" v-slot:default="{ row }">
        <span>{{ row.snCode || "-" }}</span>
      </el-table-column>
      <el-table-column label="瀏覽數量" v-slot:default="{ row }">
        <span>{{ row.viewCount || "-" }}</span>
      </el-table-column>
      <!-- <el-table-column label="協作者" prop="name"></el-table-column> -->
      <!-- <el-table-column label="所屬架構" v-slot:default="{ row }">
        <span>{{ row.departmentName || "暫無" }}</span>
      </el-table-column> -->
      <!-- <el-table-column label="分類" v-slot:default="{ row }">
        <span>{{ getTypeName(row.sceneType) || "-" }}</span>
      </el-table-column> -->
      <el-table-column label="創建時間" v-slot:default="{ row }">
        <span>{{ row.isFolder == 1 ? row.createTimeStr : row.createTime }}</span>
      </el-table-column>
      <el-table-column label="操作" v-slot:default="{ row }">
        <template v-if="row.isFolder">
          <span class="oper-span" @click="addOrUpdateFold(row)">重命名</span>
          <span class="oper-span" @click="gotoLink(row)">查看</span>
          <span class="oper-span" @click="moverFold(row)">移動</span>
          <span class="oper-span" @click="deleteFoler(row)">刪除</span>
        </template>
        <template v-else>
          <span v-if="(row.status === 1 || row.status === -2) && row.payStatus === 1" class="oper-span" @click="editModel(row)">編輯</span>
          <span v-if="row.payStatus === 1" class="oper-span" @click="moverFold(row)">移動</span>
          <span v-if="row.status === 1 || row.status === -2" class="oper-span" @click="gotoLink(row)">查看</span>
          <span class="oper-span" @click="dataList.delete(row)">刪除</span>
        </template>
      </el-table-column>
    </el-table>

    <div v-else class="mode2-layer">
      <div class="grid-data" v-if="dataList.state.length">
        <model-item
          v-for="item in dataList.state"
          :data="item"
          :key="item.id"
          @gotoLink="gotoLink(item)"
          @move="moverFold"
          @rename="addOrUpdateFold(item)"
          @deletefold="deleteFoler(item)"
          @delete="(data) => dataList.delete(data)"
          @update="(data) => editModel(data)"
        />
      </div>
      <div class="un-data" v-else>
        暫無數據
      </div>
    </div>

    <com-pagination
      @size-change="pag.sizeChange"
      @current-change="pag.currentChange"
      :current-page="pag.state.currPage"
      :page-size="pag.state.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pag.state.total"
    />

    <com-share v-if="shareItem.show" v-model:show="shareItem.show" :link="getShowModelUrl(shareItem.data)" :codeImg="getShareImg(shareItem.data)" />

    <com-dialog title="移動到文件夾" @submit="moveItemToFloder" v-model:show="moveFolder.show">
      <el-tree ref="folderRef" node-key="id" default-expand-all class="framework" :data="folderTree" :expand-on-click-node="false">
        <template v-slot="{ data }">
          <div class="custom-tree-node">
            <img :src="require('@/assets/image/folder.png')" alt="" />
            <span class="text">{{ data.name }}</span>
            <!-- <span @click="remove(node, data)" class="btn" v-if="data.level !== 0">
              <i class="el-icon-delete"></i>
            </span> -->
          </div>
        </template>
      </el-tree>
    </com-dialog>

    <com-dialog :title="currItem.id ? '編輯文件夾' : '新增文件夾'" @submit="addToFloder" v-model:show="addFolder.show">
      <div class="folderContent">
        <el-form label-width="100px">
          <el-form-item label="文件夾名：" class="mandatory">
            <el-input v-model="currItem.name" placeholder="請輸入文件夾名" maxlength="15" show-word-limit></el-input>
          </el-form-item>
        </el-form>
      </div>
    </com-dialog>
  </div>
</template>

<script>
import { ref, watch, computed } from "vue";
import getTableState from "@/state/tableRef";
import auth from "@/state/viewAuth";
import comHead from "@/components/head";
import comShare from "@/components/share";
import comDialog from "@/components/dialog";
import ModelItem from "./item";
import comPagination from "@/components/pagination";
import { SCENE_TYPE, getName } from "@/constant";
import { dateFormat } from "@/util";
import { getSceneList, deleteScene, getFolerTreeList, moveFoler, updateFoler, insertFoler, deleteFoler } from "@/request/config";
import axios from "axios";

const analysis = (data, level) => {
  return data.map((item) => ({
    id: item.id,
    name: item.name,
    level: level,
    children: item.children ? analysis(item.children, level + 1) : [],
  }));
};

export default {
  name: "vrscene",
  setup() {
    const state = getTableState({
      getUrl: getSceneList,
      delUrl: deleteScene,
      searchAttr: { sceneName: "", snCode: "", folderId: "" },
      pagAttr: { totalNum: "total" },
    });
    const shareItem = ref({ data: null, show: false });
    const editCompany = ref({ departmentId: 0, show: false });
    const moveFolder = ref({ show: false });
    const addFolder = ref({ show: false });

    const folderTree = ref([]);

    const headList = ref([{ name: "我的場景", value: "0" }]);
    const currModel = ref(1);
    const currItem = ref({
      id: "",
      name: "",
    });
    const loading = "";

    const time = ref(null);
    const pathFolder = ref([
      {
        name: "根目錄",
        id: "",
        index: 0,
      },
    ]);
    let info = localStorage.getItem('info'),userInfo = ''
    if(info){
      userInfo = JSON.parse(info&&localStorage.getItem('info'))
    }

    const folderPathShow = computed(() => {
      if (pathFolder.value.length >= 4) {
        return [
          pathFolder.value[0],
          { ...pathFolder.value[pathFolder.value.length - 3], name: "..." },
          pathFolder.value[pathFolder.value.length - 2],
          pathFolder.value[pathFolder.value.length - 1],
        ];
      }
      return pathFolder.value;
    });

    watch(time, () => {
      if (time.value) {
        state.search.value.state.startTime = dateFormat(new Date(time.value[0]), "yyyy-MM-dd hh:mm:ss");
        state.search.value.state.endTime = dateFormat(new Date(time.value[1]), "yyyy-MM-dd 23:59:59");
      } else {
        state.search.value.state.startTime = state.search.value.state.endTime = "";
      }
    });
    watch([() => state.search.value.state.startTime, () => state.search.value.state.endTime], () => {
      if (!state.search.value.state.startTime || !state.search.value.state.endTime) {
        time.value = null;
      }
    });
    watch(
      () => state.pag.value.state.total,
      () => (headList.value[0].name = "我的場景（" + state.pag.value.state.total + "）")
    );

    return { ...state,folderPathShow,userInfo, loading, folderTree, headList, addFolder, currModel, currItem, time, shareItem, auth, editCompany, moveFolder, pathFolder };
  },

  methods: {
    async moverFold(item) {
      this.currItem = item;
      let res = await axios.post(getFolerTreeList);

      this.folderTree = analysis(
        [
          {
            children: res.data,
            id: "",
            level: 0,
            name: "根目錄",
          },
        ],
        0
      );

      this.moveFolder.show = true;
    },
    async moveItemToFloder() {
      console.log(this.$refs.folderRef.getCurrentNode());
      let parent = this.$refs.folderRef.getCurrentNode();
      if (!parent) {
        return this.$alert("請選擇需要移動的目標文件夾");
      }
      let params = {
        parentId: parent.id,
      };

      params[this.currItem.isFolder ? "folderIds" : "sceneIds"] = this.currItem.id;

      if (params.parentId == this.currItem.id) {
        return this.$alert("不能移動到自身文件夾");
      }

      await axios.post(moveFoler, params);
      this.moveFolder.show = false;
      this.search.submit();

      // this.currItem
      // await Promise.all(
      //   this.dataList.selectRows.map((item) => axios.post(updateSceneDepartment, { sceneNum: item.num, departmentId: this.editCompany.departmentId }))
      // );
      // this.editCompany.show = false;
      // this.search.submit();
    },
    async addOrUpdateFold(item = null) {
      console.log(item);
      if (item) {
        this.currItem = item;
      }

      this.addFolder.show = true;
    },

    async addToFloder() {
      if (!this.currItem.name.trim()) {
        return this.$alert("文件夾名稱不能為空");
      }
      await axios.post(this.currItem.id ? updateFoler : insertFoler, {
        ...this.currItem,
      });

      this.addFolder.show = false;
      this.search.submit();
    },

    async deleteFoler(item) {
      if (await this.$confirm("此操作將刪除當前文件夾及其子文件夾所有場景，是否確認？", "提示")) {
        await axios.post(deleteFoler, {
          id: item.id,
        });
        this.$alert("刪除成功");
        this.search.submit();
      }
    },

    handlePathClick(data) {
      this.search.state.folderId = data.id;
      this.pathFolder.splice(data.index + 1);
    },
    getShareImg(item) {
      const link = process.env.VUE_APP_PREFIX + "/sceneQRcode/" + item.num + ".png";
      return link;
    },

    getShowModelUrl(item) {
      let link = "/spc.html?m=" + item.num;
      // 1 計算成功並可以外網訪問，不能編輯 2計算成功只能內網，能編輯
      if (item.status === 1) {
        return process.env.VUE_APP_DOMAIN + link;
      } else {
        return process.env.VUE_APP_INTRANET_DOMAIN + link;
      }
    },
    gotoLink(data) {
      if (data.isFolder) {
        this.loading = this.$loading({
          lock: true,
          text: "加載中",
          spinner: "el-icon-loading",
          background: "rgba(255, 255, 255, 0.4)",
          customClass: "loading",
        });
        this.search.state.folderId = data.id;
        data.index = this.pathFolder.length;
        this.pathFolder.push(data);
        let tt = setTimeout(() => {
          clearTimeout(tt);
          if (this.loading) {
            this.loading.close();
            this.loading = void 0;
          }
        }, 1000);
      } else {
        if ((data.status === 1 || data.status === -2) && data.payStatus === 1 ) {
          let domin = this.userInfo.deptId == 33?process.env.VUE_APP_SHOW_HK_LINK:process.env.VUE_APP_SHOW_LINK
          let link = domin + "index.html?m=" + data.num;
          window.open(link, "_blank");
        }
      }
    },
    editModel(item) {
      let link = "/cdf/epg.html?m=" + item.num;
      window.open(link, "_blank");
    },

    editCompanyHandle() {
      if (this.dataList.selectRows.length) {
        this.editCompany.show = true;
      } else {
        this.$alert("請選擇要更改的場景!", "提示");
      }
      // this.editCompany.data = {...item}
    },
    getTypeName: getName(SCENE_TYPE),
  },
  components: {
    "com-head": comHead,
    "com-dialog": comDialog,
    "com-share": comShare,
    "model-item": ModelItem,
    "com-pagination": comPagination,
  },
};
</script>

<style lang="scss" scoped>
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  .pathul {
    display: inline-block;
    vertical-align: middle;
    > li {
      display: inline-block;
      list-style: none;
      cursor: pointer;
      color: #909090;
      &:hover {
        color: #323233;
      }
      &:not(&:last-of-type) {
        &::after {
          content: "/";
          display: inline-block;
          margin: 0px 6px;
          cursor: auto;
          color: #909090 !important;
        }
      }
    }
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}
.custom-tree-node {
  margin: 10px 0;
  .text {
    font-size: 1rem;
    color: #303133;
  }
  > img {
    width: 1rem;
    vertical-align: text-top;
    margin-right: 10px;
  }

  .btn {
    color: rgb(144, 144, 144);
    border: 1px dashed currentColor;
    display: inline-block;
    margin-left: 10px;
    padding: 3px 5px;

    i {
      font-size: 0.8rem;
    }
  }
}

.mode2-layer {
  flex: 1;
  overflow-y: auto;
}
.grid-data {
  display: grid;
  grid: auto-flow / 1fr 1fr 1fr 1fr;
  grid-column-gap: 40px;
  grid-row-gap: 40px;
  padding-right: 30px;
}
.table-img {
  width: 50px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
  }

  div {
    position: absolute;
    z-index: 1;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
  }
}
.un-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #909399;
}

.oper-depar {
  cursor: pointer;
}

.folderContent {
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
  justify-content: center;
  min-height: 200px;
}
</style>
