<template>
  <div class="warpper">
    <el-row type="flex" justify="space-between" class="toolbar">
      <!--工具条-->
      <el-row type="flex">
        <el-form :inline="true">
          <el-form-item>
            <el-input
              @keydown.enter.native="search"
              v-model="searchKey"
              placeholder="场景名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-on:click="search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="downloadSceneData"
          >下载MP场景数据</el-button
        >
      </el-row>
      <!-- 生成大场景someData -->
      <el-row type="flex" class="addScene">
        <el-button type="primary" @click="handModelDownload(mutiTargetObj,'age')"
          >下载四维看看场景数据</el-button
        >
        <el-button type="primary" @click="handModelDownload(mutiTargetObj,'bigScene')" >下载大场景数据</el-button>
        <el-button type="warning" style="margin-right: 20px" @click="logout"
          >登出</el-button
        >
      </el-row>
    </el-row>
    <!-- 表格 -->
    <el-table
      :data="scenes"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column type="index" width="50" label="序号"></el-table-column>
      <el-table-column prop="sceneTitle" width="200" label="场景名称">
      </el-table-column>
      <el-table-column prop="sceneCode" width="200" label="MP场景码">
      </el-table-column>
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <span>{{ manage_scene_status[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        width="400"
        label="备注"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        width="200"
        label="创建时间"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        width="200"
        label="更新时间"
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <a :href="scope.row.webSite" target="_blank">查看</a>
          <a @click="handModelDownload(scope.row, 'obj')">模型下载</a>
          <a @click="handModelUpload(scope.row, 'obj')">模型上传</a>
          <a @click="handModelDownload(scope.row, 'pano')">全景图下载</a>
          <a @click="handModelUpload(scope.row, 'pano')">全景图上传</a>
        </template>
      </el-table-column>
    </el-table>

    <div class="p-con">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="size"
        layout="prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 场景码下载 -->
    <el-dialog title="下载MP场景数据" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item
          label="场景码"
          :label-width="formLabelWidth"
          prop="sceneCode"
        >
          <el-input
            type="sceneCode"
            v-model="form.sceneCode"
            autocomplete="off"
            placeholder="请输入场景码"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item
          label="场景名称"
          :label-width="formLabelWidth"
          prop="sceneTitle"
        >
          <el-input
            type="sceneTitle"
            v-model="form.sceneTitle"
            autocomplete="off"
            placeholder="请输入场景名称"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            v-model="form.description"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sceneCodeSubmit('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 文件上传 -->
    <el-dialog title="上传模型" :visible.sync="dialogFilesVisible">
      <el-form ref="form1" label-width="100px" class="add-frome">
        <el-form-item label="全景图文件">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            ref="upload"
            accept=".zip"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="onSuccess"
            :on-error="onError"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFilesVisible = false">取 消</el-button>
        <el-button
          type="primary"
          v-loading.fullscreen.lock="fullscreenLoading"
          @click="submitUpload"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MANAGE_SCENE_STATUS } from "@/config/data";
export default {
  name: "list",
  data() {
    return {
      searchKey: "",
      scenes: [],
      url: "",
      currentPage: 1,
      total: 0,
      size: 15,
      fileList: [],
      uploadUrl: "",
      fullscreenLoading: false,
      targetObj: null,
      mutiTargetObj:[],
      manage_scene_status: MANAGE_SCENE_STATUS,
      dialogFormVisible: false,
      dialogFilesVisible: false,
      form: {
        sceneCode: "",
        sceneTitle: "",
        description: "",
      },
      rules: {
        sceneCode: [
          { required: true, message: "场景码不能为空", trigger: "blur" },
        ],
        sceneTitle: [
          { required: true, message: "场景名称不能为空", trigger: "blur" },
        ],
        description: [],
      },
      formLabelWidth: "120px",
    };
  },
  async created() {
    this.getScenes();
  },
  watch: {
    currentPage() {
      this.getScenes();
    },
  },
  methods: {
    // 处理勾选
    handleSelectionChange(val) {
      console.log("val", val);
      this.mutiTargetObj = val;
    },
    handleRemove(file) {
      let index = this.fileList.findIndex((item) => {
        return item.uid === file.uid;
      });
      this.fileList.splice(index, 1);
    },
    handleChange(file) {
      this.fileList = this.fileList.length === 0 ? this.fileList : [];
      this.fileList.push(file["raw"]);
    },
    onSuccess(res) {
      this.$alert("上传成功", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          console.log("上传成功");
          this.dialogFilesVisible = false;
        },
      });
    },
    onError(res) {
      this.$alert("上传失败", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          console.log("上传失败");
        },
      });
    },
    async submitUpload() {
      var that = this;
      if (this.fileList.length === 0) {
        this.$alert("请上传附件", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {
            console.log("上传失败");
          },
        });
        return;
      }
      let formData = new FormData();
      this.fileList.forEach((file) => {
        formData.append("file", file);
      });
      this.fullscreenLoading = true;
      let res = await this.$http.post(
        `/manage/scene/upload/${this.targetObj.uploadType}/${this.targetObj.sceneCode}`,
        formData,
        {
          "Content-Type": "multipart/form-data",
        }
      );
      this.fullscreenLoading = false;
      if (res["code"] === 0) {
        that.onSuccess(res);
      } else {
        that.onError(res);
      }
    },
    search() {
      this.currentPage === 1 ? this.getScenes() : (this.currentPage = 1);
    },
    sceneCodeSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.sceneCodeSendHttp();
        }
      });
    },
    sceneCodeSendHttp() {
      let { sceneCode, description,sceneTitle } = this.form;
      let body = {
        description,
        sceneCode,
        sceneTitle
      };
      this.$http.post("/manage/scene/download", body).then((res) => {
        this.$message(res["msg"]);
        if (res["code"] === 0) {
          console.log("下载成功");
          this.getScenes()
          this.dialogFormVisible = false;
        } else {
        }
      });
    },
    downloadSceneData() {
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    async getScenes() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.size,
        searchKey: this.searchKey,
      };
      let res = await this.$http.post("/manage/scene/list", params);
      this.scenes = res.data.list;
      this.total = res.data.total;
      this.currentPage = res.data.pageNum;
    },
    //模型下载 全景下载 下载四维看看数据 下载大场景数据
    async handModelDownload(item,type) {
      console.log("item", item,'type',type);
      if(!Array.isArray(item)){
          this.fullscreenLoading = true;
          try{
              let res = await this.$http.get(`/manage/scene/download/${type}/${item.sceneCode}`,{ params: { code: item.sceneCode } });
              this.fullscreenLoading = false;
              if (res && res["code"] === 0) {
                let url = `/download${res["data"]}`
                window.open(url);
              } else {}
          }catch(e){
            this.fullscreenLoading = false;
            console.log('e',e)
          }
        
      } 
      else {
        let target = item;
        if(target.length === 0) {
          this.$message('请勾选选项');
          return;
        }
        target.forEach(item=>{
          this.$http.get(`/manage/scene/download/${type}/${item.sceneCode}`,{ params: { code: item.sceneCode } }).then(res=>{
            if (res && res["code"] === 0) {
              let url = `/download${res["data"]}`
              window.open(url);
            } else {}
          })
        })
      }
      
    },
    handModelUpload(item,type) {
      this.dialogFilesVisible = true;
      this.targetObj = {...item,uploadType:type};
      this.fileList = [];
    },
    async delScene(name) {
      if (confirm("删除后将无法恢复！你确定要删除这个场景吗?")) {
        await this.$http.get(`/manage/scene/removes/${name}`);
        this.getScenes();
      }
    },
    logout() {
      console.log("登出");
      window.localStorage.setItem("cjt_token", "");
      this.$router.push("/login");
      // this.$http({
      //   method: 'get',
      //   url: '/admin/logout',
      //   headers: {
      //     Authorization: window.localStorage.getItem('token')
      //   }
      // }).then(res => {
      //   if (res.code === 5001 || res.code === 5002) return
      //   if (res.code === 0) {
      //     window.localStorage.setItem('cjt_token', '')
      //     this.$token = ''
      //     this.$alert('退出成功', '提示', {
      //       confirmButtonText: '确定',
      //       callback: action => {
      //         window.localStorage.setItem('menu', '')
      //         this.$router.push('/login')
      //       }
      //     })
      //   }
      // })
    },
  },
};
</script>

<style scoped>
.warpper {
  border: 1px solid #dfe6ec;
  max-width: 1680px;
  margin: 0 auto;
}
.toolbar {
  background: #f2f2f2;
  padding: 10px;
}
.el-form-item {
  margin-bottom: 0;
}
.addScene {
  width: 450px;
}
.p-con {
  text-align: center;
  padding: 20px 0;
}
</style>
