<template>
  <com-head :options="headList" showCtrl>
    <el-form label-width="90px" :inline="true">
      <el-form-item label="店鋪名稱：">
        <el-input v-model="search.state.shopName" placeholder="請輸入"></el-input>
      </el-form-item>
      <el-form-item label="店鋪分類：" v-if="$route.name == 'shop'">
        <common-select v-model="search.state.categoryId" :label="'categoryName'" :url="getCategoryList" />
      </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-input placeholder="關鍵詞" suffix-icon="el-icon-search" class="search-scene" v-model="search.state.searchKey" style="width: auto" /> -->
        <el-button type="primary" icon="el-icon-plus" @click="oper.readyInsert">添加店鋪</el-button>
      </div>
    </div>
    <el-table ref="multipleTable" :data="dataList.state" tooltip-effect="dark" style="width: 100%" @row-click="dataList.selectRow">
      <el-table-column label="店鋪名稱" prop="shopName"></el-table-column>
      <el-table-column label="品牌logo" prop="shopLogo" v-slot:default="{ row }">
        <div class="table-img">
          <img :src="`${row.shopLogo}?time=${Date.now()}`" />
        </div>
      </el-table-column>
      
      <el-table-column label="排序" prop="sort"></el-table-column>
      <el-table-column label="場景地址" prop="sceneUrl"></el-table-column>
      <el-table-column label="店鋪分類" prop="categoryName"></el-table-column>
      <el-table-column label="所屬架構" prop="deptName"></el-table-column>
      <el-table-column label="創建時間" prop="createTime"></el-table-column>
      <el-table-column label="操作" v-slot:default="{ row }">
        <span class="oper-span" @click="oper.readyUpdate(row)">編輯信息</span>
        <span class="oper-span" @click="getEditModelUrl(row)">編輯場景</span>
        <span class="oper-span" @click="dataList.delete(row)" style="color: var(--primaryColor)">刪除</span>
      </el-table-column>
    </el-table>

    <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"
    />
  </div>

  <com-dialog :title="(oper.state.id ? '修改' : '添加') + '店鋪'" v-model:show="oper.state.show" @submit="submit">
    <el-form ref="form" :model="oper.state" label-width="120px" class="shop-from">
      <!-- <el-form-item label="店鋪類型：" class="mandatory">
        <el-select v-model="oper.state.region" placeholder="店鋪類型：">
          <el-option label="區域一" value="shanghai"></el-option>
          <el-option label="區域二" value="beijing"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="店鋪名稱：" class="mandatory">
        <el-input maxlength="30" show-word-limit :modelValue="oper.state.shopName" @update:modelValue="(val) => (oper.state.shopName = val.trim())"></el-input>
      </el-form-item>

      <el-form-item label="排序：" class="mandatory">
        <el-input-number v-model="oper.state.sort" :min="1" :max="10000" />
      </el-form-item>

      
      <el-form-item label="店鋪分類：" class="mandatory">
        <common-select
          :modelValue="oper.state.categoryId"
          :label="'categoryName'"
          :url="getCategoryList"
          @update:modelValue="(val) => (oper.state.categoryId = val)"
          hideAll
        />
      </el-form-item>
      <el-form-item label="所屬架構：" class="mandatory">
        <com-company :modelValue="String(oper.state.deptId)" @update:modelValue="(val) => (oper.state.deptId = val)" style="width: 100%" hideAll />
        <!-- <common-select :modelValue="oper.state.deptId" :url="getDeptList" @update:modelValue="val => oper.state.deptId = val" hideAll /> -->
      </el-form-item>
      <el-form-item label="選擇場景：" class="mandatory">
        <common-select
          :modelValue="oper.state.sceneUrl"
          :optid="'num'"
          :label="'sceneName'"
          :filter="[{
            key:'status',value:'-2'
          },{
            key:'payStatus',value:'1'
          }]"
          :url="getFilterFolerSceneList"
          @update:modelValue="(val) => (oper.state.sceneUrl = val)"
          hideAll
        />
      </el-form-item>



      <el-form-item label="選擇進入位置：" class="mandatory">
        <img style="width:100%" v-if="oper.state.initialScreen && oper.state.inPosition" :src="oper.state.initialScreen" alt="" />
        <el-button type="primary" :disabled="!oper.state.sceneUrl" @click.stop="setViewShow">設置</el-button>
      </el-form-item>

      <el-form-item label="品牌logo：" class="mandatory">
        <com-upload
          @changeLogo="changeLogo"
          @close="oper.state.shopLogo = ''"
          @update:modelValue="(val) => (oper.state.shopLogo = val)"
          :logo="oper.state.shopLogo"
        />
        <!-- <com-company :modelValue="oper.state.shopLogo" @update:modelValue="val => oper.state.deptId = val.trim()" hideAll /> -->
      </el-form-item>
      <!-- <el-form-item label="物理地址：" class="mandatory">
        <el-input :modelValue="oper.state.childName" @update:modelValue="val => oper.state.childName = val.trim()"></el-input>
      </el-form-item>
      <el-form-item label="S/N：" class="mandatory">
        <el-input :modelValue="oper.state.snCode" @update:modelValue="val => oper.state.snCode = val.trim()"></el-input>
      </el-form-item> -->
    </el-form>
  </com-dialog>

  <com-dialog width="80vw" title="設置進入位置" v-model:show="viewSetData" @submit="setView" @quit="viewSetData = false">
    <iframe class="sceneIfr" ref="viewscene$" :src="`${showDomain}show.html?m=${oper.state.sceneUrl}`" frameborder="0"></iframe>
  </com-dialog>
</template>

<script>
import axios from "axios";
import { ref, watch } from "vue";
import getTableState from "@/state/tableRef";
import auth from "@/state/viewAuth";
import comDialog from "@/components/dialog";
import comCommonSelect from "@/components/common-select";
import comCompany from "@/components/company-select";
import comUpload from "@/components/upload-com";
import comPagination from "@/components/pagination";
import comHead from "@/components/head";
import { dateFormat } from "@/util";
import { convertBlob2File } from "@/util/file";

import { getShopList, insertShop, updateShop, deleteShop, getCategoryList, getDeptList, getFilterFolerSceneList, uploadFile } from "@/request/config";

export default {
  name: "shop",
  setup() {
    const state = getTableState({
      updateUrl: updateShop,
      insertUrl: insertShop,
      getUrl: getShopList,
      delUrl: deleteShop,
      searchAttr: { shopName: "", categoryId: "" },
      operAttr: {
        shopName: "",
        categoryId: "",
        deptId: "",
        sceneUrl: "",
        sort:1,
        inPosition: "",
        initialScreen: "",
        shopLogo: "",
      },
      deletealert:'此操作將會刪除當前店鋪信息，是否確認？',
      pagAttr: { totalNum: "total" },
    });
    const headList = ref([{ name: "店鋪管理", value: "0" }]);
    const time = ref(null);
    const viewSetData = ref(false);

    const viewscene$ = ref(null);
    const loading = "";

    const showDomain = ref(process.env.VUE_APP_SHOWVIEW_LINK)

    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 + "）")
    );

    console.log({ ...state });

    return { ...state, viewscene$, loading,showDomain, viewSetData, headList, time, auth, getCategoryList, getDeptList, getFilterFolerSceneList };
  },
  async mounted() {
    await this.$nextTick();
    window.addEventListener("message", (res) => {
      if (Object.prototype.toString.call(res.data) == "[object Object]") {
        if (res.data.source === "viewSceneReady") {
          if (this.loading) {
            this.loading.close();
            this.loading = void 0;
          }
        }
      }
    });
  },
  methods: {
    getEditModelUrl(item) {
      let link = "/cdf/epg.html?m=" + item.sceneUrl;
      window.open(link, "_blank");
      // return process.env.VUE_APP_INTRANET_DOMAIN + link
    },
    setViewShow() {
      this.viewSetData = true;
      this.loading = this.$loading({
        lock: true,
        text: "加載中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.4)",
        customClass: "loading",
      });
    },
    async changeLogo(file) {
      let res = await axios.post(uploadFile, {
        file,
      });
      this.oper.state.shopLogo = res.data;
    },

    submit() {
      if (!this.oper.state.shopName.trim()) {
        return this.$alert("店鋪名稱不能為空！", "提示");
      } else if (!this.oper.state.categoryId.trim()) {
        return this.$alert("店鋪不能為空！", "提示");
      } else if (!this.oper.state.deptId.trim()) {
        return this.$alert("所屬架構不能為空！", "提示");
      } else if (!this.oper.state.sceneUrl.trim()) {
        return this.$alert("場景不能為空！", "提示");
      } else if (!this.oper.state.inPosition) {
        return this.$alert("進入位置不能為空！", "提示");
      } else if (!this.oper.state.shopLogo.trim()) {
        return this.$alert("店鋪logo不能為空！", "提示");
      }

      this.oper.state.id ? this.oper.update() : this.oper.insert();
    },
    async setView() {
      this.loading = this.$loading({
        lock: true,
        text: "加載中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.4)",
        customClass: "loading",
      });

      let thumbs = await this.viewscene$.contentWindow.__sdk.Camera.screenshot();
      let res = await axios.post(uploadFile, {
        file: convertBlob2File(thumbs[1].data, `thumb-sceneview.jpg`),
      });

      this.oper.state.inPosition = this.viewscene$.contentWindow.__sdk.Camera.getPoseUrlParams();
      this.oper.state.initialScreen = res.data;

      this.viewSetData = false;
      if (this.loading) {
        this.loading.close();
        this.loading = void 0;
      }
    },
  },
  components: {
    "com-dialog": comDialog,
    "common-select": comCommonSelect,
    "com-head": comHead,
    "com-company": comCompany,
    "com-pagination": comPagination,
    "com-upload": comUpload,
  },
};
</script>

<style lang="scss" scoped>
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}
.table-img {
  width: 50px;
  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;
  }
}
.sceneIfr {
  width: 100%;
  height: 650px;
}
.shop-from {
  width: 320px;
  margin: 0 auto;
}
</style>
