<template>
  <div id="file_moddle_manage" v-loading="loading">
    <!-- 左边模型文件夹列表 -->
    <div class="col_left">
      <div class="grid-content grid-left">
        <el-card class="box-card" :body-style="{ padding: '0px', height: '100%' }">
          <div class="top_hand left_top_hand">
            <div class="folder-box">
              <el-tooltip class="item" effect="dark" content="新建文件夹" placement="top-start">
                <el-button icon="el-icon-folder-add" @click="addFolder" class="icon_font"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除文件夹" placement="top-start">
                <el-button icon="el-icon-folder-remove" class="icon_font" @click="removeFolder"></el-button>
              </el-tooltip>
            </div>
            <div class="file-box">
              <el-tooltip class="item" effect="dark" content="编辑文件夹" placement="top-start">
                <el-button @click="editFolder" icon="el-icon-edit" class="icon_font"></el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="folder-list">
            <div class="head">建筑模型文件夹
              <span>(建议按建筑模型进行命名)</span>
            </div>
            <ul class="lists">
              <el-scrollbar style="height:100%;">
                <li @click="openFolder(index,item)" v-for="(item,index) in navigationModel" :key="index"
                  :class="[choiceIndex == index + 1 ? 'li-active' : '']">
                  <i :class="[choiceIndex == index + 1 ?  'el-icon-folder-opened':'el-icon-folder','icon_font']" width="40" height="40"></i>
                  <span :title="item.Name">{{item.Name}}</span>
                </li>
              </el-scrollbar>
            </ul>
          </div>
        </el-card>
      </div>
    </div>
    <!-- 右边文件表格 -->
    <div class="col_right">
      <el-card class="box-card" :body-style="{ padding: '0px', height:'100%' }">
        <!-- 顶部操作栏 -->
        <div class="top_hand right_top_hand">
          <el-button @click="addFloorFile">添加楼层文件</el-button>
          <el-button @click="queryFloorFile(currentFolderId)">刷新</el-button>
        </div>
        <!-- 列表 -->
        <floorTable v-loading="tableLoading" ref="floorTable" :tableData="tableData" :modelFolderName="currentFolderName" @openModelLog="queryModelLog"
          @replaceModel="repliaceModel" @percentFinish="queryFloorFile(currentFolderId)"
          :persentList="persentList"></floorTable>
      </el-card>
    </div>
    <!-- 弹窗 开始-->

    <!-- 模型日志弹窗 -->
    <modelLog :modelLogVisible="modelLogVisible" :modelFolderName="currentFolderName" @deleteFinish="updataLog"
      @CloseModelLogDia="modelLogVisible=false" :logData="logData"></modelLog>
    <!-- 替换模型弹窗 -->
    <repliceModel :repliceModelVisible="repliceModelVisible" @closeReplaceModelDia="repliceModelVisible=false" :replaceModelItem="replaceModelItem"
      @updataModel="updateModelFile"></repliceModel>
    <!-- 新增楼层 -->
    <addFloorDialog :addFloorFileVisible="addFloorFileVisible" :floorList="tableData" :FolderName="currentFolderName" :FolderId="currentFolderId"
      @closeAddFloorDia="addFloorFileVisible=false" @finishCreateFloor="uploadModelFIle"></addFloorDialog>
    <!-- 新增文件夹名称 -->
    <addFolder :addFolderVisible="addFolderVisible" @closeAddFolderVisible="addFolderVisible=false;folderName=''" :folderName="folderName"
      @getfolderModel="queryModel"></addFolder>
    <!-- 编辑文件夹名字 -->
    <changeFolderName :currentFolderId="currentFolderId" :changeFolderNameVisible="changeFolderNameVisible" :folderName="folderName"
      @finishChangeFolderName="queryModel" @closeChangeFolderVisible="changeFolderNameVisible=false;folderName=''"></changeFolderName>
    <!-- 弹窗 结束-->
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import request from "@/api/model/file.js";
import Bus from '@/utils/bus.js'
import dasBoard from "@/views/dasboard/index";
import modelLog from "@/components/model/file/modelLog"; //模型日志弹窗
import repliceModel from "@/components/model/file/replaceModelDialog"; //替换模型弹窗
import addFloorDialog from "@/components/model/file/addFloorDialog"; //新增楼层弹窗
import addFolder from "@/components/model/file/addFolder"; //新增文件夹
import changeFolderName from "@/components/model/file/changeFolderName"; //编辑名字
import floorTable from "@/components/model/file/floorTable"; //右侧list表
export default {
  computed: {
    ...mapGetters("layout", ["projectId", "userInfo", "userId", "secret", "uploaderList"])
  },
  components: {
    dasBoard,
    modelLog,
    repliceModel,
    addFloorDialog,
    addFolder,
    changeFolderName,
    floorTable
  },
  data() {
    return {
      addFolderVisible: false, //是否显示新增文件夹弹窗
      addFloorFileVisible: false, //是否显示增加楼层文件弹窗
      repliceModelVisible: false, //是否显示替换楼层模型弹窗
      modelLogVisible: false, //是否显示模型日志弹窗
      changeFolderNameVisible: false, //是否显示编辑文件夹弹窗
      folderName: "", //新建文件夹名称
      navigationModel: [
        {
          Name: ""
        }
      ], //文件夹模型list
      choiceIndex: 0, //当前文件夹index
      currentFolderId: "", //当前选择的文件夹id
      currentFolderName: "", //当前选择文件夹的Name
      currentFloorModelId: "", //当前选择的楼层文件id
      tableData: [],
      loading: false, //加载loading
      tableLoading: false, //表格加载loading
      logData: [], //楼层文件对应的模型日志
      replaceModelItem: null, //替换文件的item
      uploadFloorModelIdList: [], //上传楼层文件得数组，上传完成则为空
      //请求头
      headers: {
        ProjectId: ""
      },
      updataData: {
        model: {}
      },
      persentList: [], //请求进度列表
      isJump: true //是否可以调整页面
    };
  },
  mounted() {
    // // 文件选择后的回调
    // Bus.$on('fileAdded', () => {
    //   console.log('文件已选择')
    // });
    // // 文件上传成功的回调
    // Bus.$on('fileSuccess', () => {
    //   console.log('文件上传成功')
    // });
  },
  destroyed() {
    // Bus.$off('fileAdded');
    // Bus.$off('fileSuccess');
  },
  methods: {
    // 以下是模型文件夹

    // 打开模型文件夹
    openFolder(index, item) {
      this.choiceIndex = index + 1;
      this.currentFolderId = item.Id;
      this.currentFolderName = item.Name;
      // 获取模型文件夹对应得楼层文件
      this.queryFloorFile(this.currentFolderId);
    },
    //新增模型文件夹
    addFolder() {
      this.folderName = "";
      this.addFolderVisible = true;
    },
    //删除模型文件夹
    removeFolder() {
      this.$alert(`确定要删除文件夹 <${this.currentFolderName}> 吗?`, "提示", {
        confirmButtonText: "确定",
        callback: action => {
          if (action == "confirm") {
            let params = {
              Id: this.currentFolderId,
              ProjectId: this.projectId
            };
            request.deleteModel(params, res => {
              this.$message({
                message: "删除成功!",
                type: "success"
              });
              this.queryModel();
            });
          } else {
            this.$message({
              type: "info",
              message: `取消操作`
            });
          }
        }
      });
    },
    //编辑文件夹
    editFolder() {
      this.folderName = this.currentFolderName;
      this.changeFolderNameVisible = true;
    },
    // 查询所有文件夹模型
    queryModel() {
      this.loading = true;
      request.queryModel("", res => {
        this.navigationModel = res.Content;
        this.loading = false;
        if (this.navigationModel.length) {
          //默认选择第一个文件夹
          this.choiceIndex = 1;
          this.currentFolderName = this.navigationModel[0].Name;
          this.currentFolderId = this.navigationModel[0].Id;
          this.queryFloorFile(this.currentFolderId);
        } else {
          this.tableData = []
        }
      });
    },

    ///一下是楼层文件

    //获取楼层文件
    /**
     * @param currentFolderId 当前选择的文件夹id
     */
    queryFloorFile(currentFolderId) {
      if(currentFolderId){
        this.tableData = [];
        this.tableLoading = true;
        let data = {
          FolderId: currentFolderId,
          ProjectId: this.projectId
        };
        return new Promise((resolve, reject) => {
          request.queryFloorList(data, res => {
            res.Content.map(item => {
              /**
               * @info: 状态显示说明
               * 0: 上传中（上传的用户可操作：中止）
               * 1: 等待检查
               * 10: 模型检查中
               * 11: 未通过检查
               * 2、20、21、3、31: 正常（所有用户可操作：下载、查看历史）
               * 4: 正常（所有用户可操作：下载、替换、查看历史）
               */
              if (item.Status == 2 || item.Status == 20 || item.Status == 21 || item.Status == 3 || item.Status == 31 || item.Status == 4) {
                Object.assign(item, { precent: 0 });
              } else {
                Object.assign(item, { precent: 100 });
                if (this.persentList.length != 0) {
                  this.persentList.forEach(pItem => {
                    if (item.Id == pItem.Id) {
                      Object.assign(item, { precent: pItem.precent ? pItem.precent : 0 });
                    }
                  });
                }
              }

              //删除错误模型(多人登录会有问题)
              /****状态为0,上传人为本人并且上传列表无对应的模型文件 */
              // if (item.Status == 0 && item.UserName == this.userInfo.userName && !this.uploaderList.some(file => {return file.modelId == item.CurrentModelId})) {
              //   request.deleteModelFileList({Id: item.CurrentModelId}, res => {console.log('删除错误模型:',item.CurrentModelId)})
              // }
            });
            this.tableData = res.Content;
            this.tableLoading = false;
            resolve();
          });
        });
      }
    },
    //添加楼层文件
    addFloorFile() {
      this.addFloorFileVisible = true;
    },

    //以下是文件模型

    //打开替换文件模型
    repliaceModel(item) {
      this.replaceModelItem = item;
      this.repliceModelVisible = true;
    },
    // 上传模型文件
    uploadModelFIle(data) {
      Bus.$emit('openUploader', { 
        uploadId: data.uploadId, 
        modelId: data.modelId,
        systemId: 'revit', //系统名称
        secret: '63afbef6906c342b', //系统密码
      }, data.file.raw)
      // 在列表中添加
      this.persentList.push({
        Id: data.floorId,
        precent: 0
      });
      this.queryFloorFile(this.currentFolderId);
    },
    //更新模型文件；
    updateModelFile(data) {
      let params = {
        FileName: data.file.name,
        FloorName: data.replaceModelItem.FloorName,
        FolderId: data.replaceModelItem.FolderId,
        Note: data.replaceModelItem.Note,
        ProjectId: this.projectId,
        ReplaceReason: 0,
        Size: data.file.size,
        UserName: this.userInfo.userName,
        UserId: this.userInfo.userId
      };
      //  替换模型文件
      request.modelFileUpload(params, res => {
        //  上传
        this.persentList.push({
          Id: data.replaceModelItem.Id,
          precent: 0
        });
        // 修改precent得值
        this.tableData.map(item => {
          if (item.Id == data.replaceModelItem.Id) {
            item.precent = 0;
          }
        });
        this.queryFloorFile(this.currentFolderId);
        Bus.$emit('openUploader', { 
          uploadId: res.UploadId, 
          modelId: res.ModelId,
          systemId: 'revit', //系统名称
          secret: '63afbef6906c342b', //系统密码
        }, data.file.raw)
      });
    },
    //查看模型日志
    queryModelLog(item) {
      this.FloorModelId = item.Id; //楼层模型文件
      request.queryModelFile(this.FloorModelId, res => {
        this.logData = res.Content;
        this.modelLogVisible = true;
      });
    },
    // 刷新日志
    updataLog() {
      request.queryModelFile(this.FloorModelId, res => {
        this.logData = res.Content;
      });
    },
  },
  watch: {
    projectId() {
      this.queryModel()
    }
  },
  mounted() {
    this.queryModel();
    Bus.$on('modelStatusChange', message => {
      this.queryFloorFile(this.currentFolderId);
    })
    // 十秒刷新次楼层列表
    // setInterval(()=>{
    //    this.queryFloorFile(this.currentFolderId)
    // },10000)
  }
};
</script>
<style lang="less" scoped>
#file_moddle_manage {
  width: 100%;
  height: 100%;
  display: flex;
  overflow: hidden !important;
  .col_left {
    width: 280px;
    height: 100%;
  }
  .col_right {
    width: calc(100% - 280px);
    height: 100%;
  }
  .grid-content {
    height: 100%;
  }
  .box-card {
    height: 100%;
  }
  .grid-left {
    padding-right: 10px;
    box-sizing: border-box;
  }
  // 顶部
  .top_hand {
    height: 60px;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
  }
  .left_top_hand {
    align-items: center;
    justify-content: space-between;
    .folder-box {
      display: flex;
      height: 40px;
      flex-direction: row;
    }
    .box-icon {
      width: 40px;
      height: 40px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      float: left;
    }
  }
  // 左侧文件夹列表
  .folder-list {
    width: 100%;
    height: calc(100% - 60px);
    .head {
      height: 42px;
      width: 100%;
      padding-left: 10px;
      box-sizing: border-box;
      background: #d9d9d9;
      color: #2b2b2b;
      display: flex;
      justify-content: left;
      align-items: center;
      font-weight: bold;
      span{
        font-weight: normal;
        font-size: 12px;
        color: #606266;
      }
    }
    .lists {
      width: 100%;
      margin-top: 10px;
      height: calc(100% - 52px);
      overflow-y: auto;
      li {
        height: 42px;
        display: flex;
        justify-content: left;
        align-items: center;
        padding-left: 20px;
        box-sizing: border-box;
        color: #555;
        cursor: pointer;
        span {
          padding-left: 6px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      li:hover {
        background-color: #f5f7fa;
        color: #000;
      }
      .li-active {
        background-color: #f5f7fa;
        color: #000;
      }
    }
  }
  .icon_font {
    font-size: 18px;
  }
}
/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
