<template>
  <div class="body-layer">
    <com-head :options="headList" :showCtrl="undefined" v-model="active">
  </com-head>
    <div class="borderSet" v-if="active == 0">
        <div class="body-head">
        <h3></h3>
        <div class="table-ctrl-right">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="changAddshow"
            >添加外框</el-button
          >          
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleDowmFile(active)"
            >下载导入模板</el-button
          >      
          <el-upload class="upload-demo1" style="margin-left:10px;display: inline-block;"
                    action="/back/upload/file"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :show-file-list="false"
                    @success="handFileSuccess"
                    :headers="{Token:user.token}"
                    :before-remove="beforeRemove"
                    multiple
                    :limit="3"
                    :on-exceed="handleExceed">
                    <el-button type="primary">导入品牌</el-button>
                </el-upload>
        </div>
      </div>
      <el-table
            ref="multipleTable"
            :data="borderData.list"
            tooltip-effect="dark"
            style="width: 100%"
            @row-click="dataList.selectRow"
        >
            <el-table-column label="外框ID" width="100" prop="id"></el-table-column>
            <el-table-column label="外框名称" prop="outlineName"></el-table-column>
            <el-table-column
            label="外框图片"
            prop="outlineImage"
            v-slot:default="{ row }"
            >
            <div class="table-img">
                <img :src="`${row.outlineImage}?time=${Date.now()}`" />
            </div>
            </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="delBorder(row.id)"
                style="color: var(--primaryColor)"
                >刪除</span
            >
            </el-table-column>
        </el-table>
        <com-pagination
        @size-change="borderSizeChange"
        @current-change="borderCurrentChange"
        :current-page="borderData.state.pageNum"
        :page-size="borderData.state.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="borderData.state.total"
        />
    </div>
    <div v-else class="other">
        <div class="setFile">
            <div class="down">
                <p>1、下载模板，请按示例填写。</p>
                <el-button type="primary" @click="exporFileinfo.show = true">下载导入模板</el-button>
                <p>注：导入模板中包含此场景全部热点信息</p>
            </div>
            <div class="upload">
                <p>2、上传并导入。</p>
                <el-upload class="upload-demo"
                    v-model:file-list="exporFileinfo.fileList"
                    action="/back/upload/file"
                    @success="handFileSuccess1"
                    :headers="{Token:user.token}"
                    multiple
                    :limit="1">
                    <el-button type="primary">选择文件</el-button>
                    <template v-slot:tip>
                        <div class="el-upload__tip">{{exporFileinfo.tips || '选择文件上传，系统自动校验数据是否合规，并给出提示。'}}</div>
                    </template>
                </el-upload>
            </div>
            <div class="down upload" v-if="exporFileinfo.filePath">
                <p>3、上传并导入。</p>
                <el-button type="primary" @click="handleUpload">上传并导入</el-button>
            </div>
        </div>
    </div>
  </div>

  <com-dialog
    :title="'下载导入模板'"
    width="40vw"
    v-model:show="exporFileinfo.show"
    @submit="submit"
  >
    <el-form
      ref="form"
      :model="exporFileinfo"
      label-width="120px"
      class="shop-from"
    >
      <el-form-item label="選擇場景：" class="mandatory">
        <common-select
          :modelValue="exporFileinfo.sceneNum"
          :optid="'num'"
          :label="'sceneName'"
          :filter="[
            {
              key: 'status',
              value: '-2',
            },
            {
              key: 'payStatus',
              value: '1',
            },
          ]"
          :url="getFilterFolerSceneList"
          @update:modelValue="(val) => (exporFileinfo.sceneNum = val)"
          hideAll
        />
      </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>
  
  <com-dialog
    width="40vw"
    title="添加外框"
    v-model:show="showAddborder"
    @submit="setBorder"
    @quit="showAddborder = false"
  >
    <el-form label-width="90px" :inline="true">
      <el-form-item label="名称：">
        <el-input v-model="setBorderData.outlineName" placeholder="請輸入"></el-input>
      </el-form-item>
      <el-form-item label="图片：" class="mandatory">
        <com-upload
          @changeLogo="changeLogo"
          @close="setBorderData.outlineImage = ''"
          @update:modelValue="(val) => (setBorderData.outlineImage = val)"
          :logo="setBorderData.outlineImage"
        />
        </el-form-item>
    </el-form>
  </com-dialog>
</template>
  
  <script>
import axios from "axios";
import { reactive, 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, dowmBlobfile } from "@/util/file";
import user from '@/state/user'

import {
  getShopList,
  insertShop,
  updateShop,
  deleteShop,
  getCategoryList,
  getDeptList,
  getFilterFolerSceneList,
  uploadFile,
  getBorderList,
  addBorder,
  downTemplate,
  delBorderApi,
  checkFile,
  uploadExcel,
} from "@/request/config";

export default {
  name: "shop",
  setup() {
    const mpStatus = ref(0);
    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 fileList = ref([])
    const headList = ref([
      { name: "外框设置", value: 0 },
      // { name: "热点导出", value: 1 },
      { name: "瀑布流导入", value: 1 },
      { name: "精选推荐设置", value: 2 },
      { name: "品牌推荐设置", value: 3 },
    ]);
    const titleObj = reactive({
        2:'瀑布流商品导入',
        3:'精选推荐热点导入设置',
        4:'品牌推荐热点导入设置',
    })
    const setBorderData = ref({
      outlineName:'',
      outlineImage:'',
    })
    const exporFileinfo = ref({
      tips:'',
      filePath:'',
      fileList:[],
      sceneNum:'',
      show:false,
    })
    const time = ref(null);
    const viewSetData = ref(false);
    const addBorder = ref(false)
    const active = ref(0);
    const viewscene$ = ref(null);
    const showAddborder = ref(false);
    const loading = "";
    const borderData = ref({
        url:getBorderList,
        list:[],
        state: {
          pageNum: 1,
          pageSize: 12,
          total: 0
        },
    })
    const showDomain = ref(process.env.VUE_APP_SHOWVIEW_LINK);
    const getborderList = ()=>{
      axios.post(borderData.value.url, {
        pageNum:borderData.value.state.pageNum,
        pageSize:borderData.value.state.pageSize,
      }).then(res => {
        borderData.value.list = res.data.list
        borderData.value.state = res.data
      });
    }
    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(active,
      () =>{
        if(active.value == 0){
          borderData.value.state = {
            pageNum: 1,
            pageSize: 12,
            total: 0
          }
          exporFileinfo.value.sceneNum = ''
          getborderList()
        }else{
          exporFileinfo.value.tips = ''
          exporFileinfo.value.filePath = ''
          exporFileinfo.value.fileList = []
        }
      }
    );

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

    return {
      ...state,
      user,
      titleObj,
      addBorder,
      getborderList,
      borderData,
      setBorderData,
      active,
      mpStatus,
      viewscene$,
      loading,
      showDomain,
      viewSetData,
      headList,
      time,
      auth,
      getCategoryList,
      getDeptList,
      getFilterFolerSceneList,
      showAddborder,
      fileList,
      exporFileinfo,
    };
  },
  async mounted() {
    this.getborderList()
    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,
      });
      if(this.showAddborder){
        this.setBorderData.outlineImage = res.data;
      }else{
        this.oper.state.shopLogo = res.data;
      }
    },
    changAddshow(){
      this.showAddborder = true
    },
    submit() {
      this.handleDowmFile(this.active)
    },
    async setBorder(){
      this.loading = this.$loading({
        lock: true,
        text: "加載中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.4)",
        customClass: "loading",
      });
      await axios.post(addBorder, this.setBorderData);
      if (this.loading) {
        this.loading.close();
        this.loading = void 0;
      }
      this.getborderList()
      // this.showAddborder = false
      // this.setBorderData = {
      //   outlineName:'',
      //   outlineImage:'',
      // }
      this.$message({
        type: 'success',
        message: '更新成功'
      });
      this.showAddborder = false
    },
    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;
      }
    },
    borderSizeChange(attr){
      this.borderData.state.pageSize = attr
      this.getborderList()
    },
    borderCurrentChange(attr){
      this.borderData.state.pageNum = attr
      this.getborderList()
    },
    // borderSizeChange1(attr){
    //   this.borderData.state.size = attr
    // },
    // borderCurrentChange1(attr){
    //   this.borderData.value.state.currPage = attr
    // },
    handleDowmFile(type = 0){
      let filename = {
          0:'外框设置模板',
          1:'瀑布流模板',
          2:'精选推荐设置模板',
          3:'品牌推荐设置模板',
        }
      this.$alert(`是否确认${filename[type]}下载？`, "下载导入模板",{
        cancelButtonText:'取消',
        showCancelButton: true
      }).then(async ()=>{
        await axios({
            method: 'get',
            url: downTemplate,
            params: { type, sceneNum:this.exporFileinfo.sceneNum},
            responseType: 'blob'
        }).then(res => {
          console.log('handleDowmFile',res);
          dowmBlobfile(res,filename[type])
          this.exporFileinfo.show = false
        })
      })
    },
    async delBorder(id){
      if (await this.$confirm('確定要刪除此數據嗎？', '提示')) {
        await axios.post(delBorderApi, {
            id,
          });
        this.$alert('刪除成功')
        this.getborderList()
      }
    },
    handFileSuccess(file){
      let apiData = {
        filePath:file.data,
        type:0
      }
      axios.post(checkFile, apiData, ).then(async res => {
        if(res.data && res.data.length){
          let list = res.data, text = list.toString()
          if(res.data.length>6){
            list.length = 6
            text = list.toString() + '....'
          }
          return this.$alert(`第${text}行数异常`);
        }else{//自动提交
          await axios.post(uploadExcel, apiData)
          this.$alert('更新成功')
        }
      });
    },
    handFileSuccess1(file){
      let apiData = {
        filePath:file.data,
        type:this.active
      }
      axios.post(checkFile, apiData, ).then(async res => {
        if(res.data && res.data.length){
          let list = res.data, text = list.toString()
          if(res.data.length>6){
            list.length = 6
            text = list.toString() + '....'
          }
          this.exporFileinfo.tips = `第${text}行数异常`
          return this.$alert(this.exporFileinfo.tips);
        }else{//自动提交
          this.exporFileinfo.filePath = file.data
          this.handleUpload()
        }
      }).catch(() => {
        this.exporFileinfo.fileList = []
        this.exporFileinfo.filePath = ''
      });
    },
    async handleUpload(){
      let apiData = {
        filePath:this.exporFileinfo.filePath,
        type:this.active
      }
      await axios.post(uploadExcel, apiData)
      this.$alert('更新成功')

    }
  },
  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;
}
.other{
    .setFile{
        .upload{
            margin-top: 20px;
        }
    }
}
.upload-demo{
  width: 400px;
}
</style>
  