<template>
  <com-head :options="headList" >
    <el-form label-width="84px" inline="true">
      <el-form-item label="场景标题：">
        <el-input v-model="search.state.sceneTitle" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="拍摄时间：">
        <el-date-picker
          v-model="time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="searh-btns" style="grid-area: 1 / 3 / 2 / 4;">
        <el-button type="primary" @click="search.submit">查询</el-button>
        <el-button type="primary" plain @click="search.reset">重置</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer">
    <div class="body-head">
      <h3 style="visibility: hidden;">场景管理</h3>
      <div class="table-ctrl-right">
        <el-button type="primary" v-power="'sync'" v-if="auth.delete" @click="asynccj">同步场景</el-button>
      </div>
    </div>

    <el-table
      ref="multipleTable"
      :data="dataList.state"
      tooltip-effect="dark"
      style="width: 100%"
      @row-click="selectRow"
      @selection-change="dataList.changeSelectRows"
    >
      <!-- -1 计算失败  0 计算中 1 计算成功并可以外网访问，不能编辑 2计算成功只能内网，能编辑 -->
      <el-table-column label="序号" width="55" v-slot:default="{ $index }">
        <div style="text-align: center">{{ pag.state.size * (pag.state.currPage - 1) + $index + 1 }}</div>
      </el-table-column>
      <el-table-column label="场景标题" prop="sceneName"></el-table-column>
      <el-table-column label="S/N码" prop="snCode"></el-table-column>
      <el-table-column label="浏览数量" prop="viewCount"></el-table-column>
      <el-table-column
        label="拍摄时间"
        prop="createTime"
        v-slot:default="{ row }"
      >
        {{ row.createTime.substr(0, 11) }}</el-table-column
      >
      <el-table-column label="操作" v-slot:default="{ row }">
        <span class="oper-span" v-power="'view'" @click="shareHandle(row)">查看</span>
        <span class="oper-span" v-power="'edit'" @click="editModel(row)">编辑</span>
        <span class="oper-span" @click="download(row)" v-if="row.num" >下载</span>
        <span class="oper-span" v-power="'del'" @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"/>
    
  
    <com-dialog
      title="场景归属"
      v-model:show="editCompany.show"
      @submit="updateItemCompany"
    >
      <el-form ref="form" :model="form" label-width="84px" class="vrmodel-from">
        <el-form-item label="所属架构：" class="mandatory">
          <com-company v-model="editCompany.data.deptId" hideAll />
        </el-form-item>
      </el-form>
    </com-dialog>

    
    <com-dialog
      title="选择相机"
      :width="480"
      v-model:show="cameraCompany.show"
      @submit="updateCameraCompany"
      enterText="确 定"
    >
      <el-form ref="form" :model="form" label-width="90px" class="vrmodel-from">
        <el-form-item label="选择相机：" class="mandatory">
          <el-select v-model="cameraCompany.data" placeholder="请选择">
            <el-option
              v-for="item in cameras"
              :key="item.snCode"
              :label="item.snCode"
              :value="item.snCode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </com-dialog>

    <com-dialog
      title="场景离线包下载"
      :width="500"
      v-model:show="cameraDownload.show"
      :hideFloor="cameraDownload.data.type == '1'"
      enterText="下 载"
      @quit="suspend"
      @submit="downloadItemCompany"
    >
      <div>
        <div class="title">
          {{
            cameraDownload.data.type == "0"
              ? "下载场景离线数据包，可在本地运行查看。"
              : cameraDownload.data.type == "1"
              ? "正在打包场景离线数据"
              : cameraDownload.data.name
          }}
        </div>
        <div style="marginTop:20px" v-if="cameraDownload.data.type == '0'">
          当前剩余下载次数：<span>{{ cameraDownload.data.value }}</span
          >次
        </div>
        <div v-else-if="cameraDownload.data.type == '1'">
          <div
            class="text"
            style="display:flex;justify-content: space-between;margin-top:15px"
          >
            <span>{{ cameraDownload.data.name }}</span>
            <span>{{ cameraDownload.data.percent }}%</span>
          </div>
          <div>
            <el-slider
              :disabled="true"
              v-model="cameraDownload.data.percent"
              :show-tooltip="false"
            >
            </el-slider>
          </div>
        </div>
      </div>
    </com-dialog>

    <com-dialog
      title="同步场景"
      v-model:show="asyncSceneCompany"
      @submit="asyncSceneCompany = false"
      enterText="确 定"
    >
      <com-async :data="cameraCompany.data" v-if="cameraCompany.data" />
    </com-dialog>
  </div>
</template>

<script>
import { ref, watch } from "vue";
import getTableState from "@/state/tableRef";
import auth from "@/state/viewAuth";
import user from '@/state/user'
import comAsync from "./async";
import comHead from "@/components/head";
import comDialog from "@/components/dialog";
import comPagination from "@/components/pagination";
import comCompany from "@/components/company-select";
import { getApp } from '@/app'
import { dateFormat } from '@/util'
import { ADMIN_USER_ID } from '@/constant'
import {
  getSceneList,
  deleteScene,
  // getCameraOptions,
  getCameraListByUser,
  checkHasDownload,
  getDownloadProcess,
  downloadScene,
} from '@/request/config'
import axios from 'axios';


export default {
  name: 'vrmodel',
  setup() {
    const state = getTableState({
      getUrl: getSceneList,
      delUrl: deleteScene,
      delAttr: {'sceneNum': 'num'},
      searchAttr: { start: "", end: '', sceneTitle: '', snCode: '' }
    });
    const editCompany = ref({data: {}, show: false})
    const cameraCompany = ref({data: null, show: false})
    const asyncSceneCompany = ref(false)
    const cameras = ref([])
    const headList = ref([{ name: "场景管理", value: 2 }]);
    const currModel = ref(1)
    const time = ref(null)
    const cameraDownload = ref({ data: { type: 0, value: 0 }, show: false });

    watch(time, () => {
      if (time.value) {
        console.log(time.value[0], time.value[1])
        let start1 = new Date(time.value[0])
        let start2 = new Date(time.value[1])
        if (start2.getTime() - start1.getTime() < 0) {
          getApp().$message.error('结束日期必须大于开始日期', '提示')
        } else {
          state.search.value.state.start = dateFormat(start1, 'yyyy-MM-dd')
          state.search.value.state.end = dateFormat(start2, 'yyyy-MM-dd')
        }
      } else {
        state.search.value.state.start = state.search.value.state.end = ''
      }
    })
    watch(
      [() => state.search.value.state.start, () => state.search.value.state.end],
      () => {
        if (!state.search.value.state.start || !state.search.value.state.end) {
          time.value = null
        }
      }
    )

    watch(asyncSceneCompany, () => {
      asyncSceneCompany.value || state.dataList.value.refer()
    })

    return { ...state, headList, currModel, time, auth, editCompany, cameras, cameraCompany, asyncSceneCompany, user,cameraDownload,ADMIN_USER_ID };
  },
  methods: {
    download(item) {
      //查询下载进度   0未创建  1打包中  2等待下载
      let statelist = {
        0:0,
        1:1,
        2:0,
        3:2,
      }
      axios
        .get(checkHasDownload + item.num, { sceneNum: item.num, isTiles: true })
        .then((res) => {
          console.log("type---> res :", res.data);
          this.cameraDownload.data = {
            type: statelist[res.data.downloadStatus],
            downloadStatus:res.data.downloadStatus,
            sceneNum: item.num,
            value: res.data.count,
            name: item.sceneName + ".zip",
            url: res.data.downloadUrl,
            percent:0,
          };
          if(res.data.count == 0 && (res.data.downloadStatus == 0 || res.data.downloadStatus == 2)){
            return this.$message.error("暂无剩余下载次数!", "提示");
          }else{
          this.cameraDownload.show = true;
          }
          if(res.data.downloadStatus == 1){//下载中
            this.downloadItemCompany()
          }
        });
    },
    async activated() {
      let res = await axios.get(getCameraListByUser)
      this.cameras = res.data.list
    },
    editModel(item) {
      window.open(process.env.VUE_APP_DOMAIN + '/epc.html?m=' + item.num + '&token=' + user.value.token)
    },
    shareHandle(item) {
      window.open(process.env.VUE_APP_DOMAIN + '/spc.html?m=' + item.num)
    },
    suspend(){
      clearTimeout(this.timer)
    },
    downloadItemCompany() {
      //查询下载进度   0未创建  1打包中  2等待下载
      //查询进度
      let that = this
      const { sceneNum, url,downloadStatus } = this.cameraDownload.data;
      let download = (downloadUrl) =>{
        let iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = downloadUrl
        document.body.appendChild(iframe);
        that.cameraDownload.show = false;
      }
      console.log('downloadStatus',downloadStatus)
      if(downloadStatus == 3){
        return download(url)
      }else if(downloadStatus == 0 || downloadStatus == 2 ){
        axios.get(downloadScene+sceneNum).then((resdata) => {
          if(resdata.data.downloadStatus !== 1){
            clearTimeout(this.timer)
            that.cameraDownload.show = false;
            return this.$message.error("暂无剩余下载次数!", "提示");
          }
        });
      }
      let fn = () => {
        that.timer = setTimeout(() => {
          callback();
        }, 1000);
        // downIngs[this.scene.num] = this.timer;
      };
      let callback = () => {
      axios.get(getDownloadProcess, {
        params:{
          sceneNum: sceneNum,
          isTiles: true,
        }
        }).then((res) => {
          const { percent,url } = res.data
          that.cameraDownload.data.type  = 1
          that.cameraDownload.data.percent  = parseInt(percent)
          if(!url){
            fn()
          }else{ //拿到下载链接
            url&&download(url)
          }
        });
      }
      fn()
      // if (type !== 2) {
      //   this.cameraDownload.data = {
      //     ...cameraDownloaddata,
      //     type: 1,
      //     value: 50,
      //   };
      // }
    },
    updateCameraCompany() {
      if (!this.cameraCompany.data) {
        return this.$message.error('请选择相机!', '提示')
      }
      this.cameraCompany.show = false
      this.asyncSceneCompany = true
    },
    asynccj(){
    this.activated()
    this.cameraCompany.show = true
  },
  },
  components: {
    "com-head": comHead,
    "com-dialog": comDialog,
    "com-company": comCompany,
    "com-async": comAsync,
    "com-pagination": comPagination
    
  },
};
</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);
    }
  }
}

.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;

  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;
}

.vrmodel-from {
  // width: 320px;
  // margin: 0 auto;
}
</style>

<style>
.vrmodel-from .el-select {
  width: 100%;
}
.el-slider__button-wrapper {
  top: -6px !important;
}
</style>