<template lang="html">
  <div class="sceneManage-list">
    <div class="sceneManage-header">
      <div class="title-header">
        <h2 class="name">模型视图管理</h2>
      </div>
      <div class="sceneManage-opr">
        <div class="fl">
          <el-button type="primary" @click="sceneAdd">新增</el-button>
          <el-button type="primary" @click="" v-if="showDeleteButton">删除</el-button>
        </div>
        <!-- <div class="fr">
          <el-button type="text" @click="sceneManageShowSearch">
            高级
            <i class="el-icon-arrow-down" v-if="this.isHide"></i>
            <i class="el-icon-arrow-up" v-if="!this.isHide"></i>
          </el-button> -->
          <!-- <el-button type="primary" @click="backInfo">返回</el-button> -->
        <!-- </div> -->
      </div>
    </div>
    <div class="sceneManage-main">
      <div class="sceneManage-left fl">
        <el-tree :data="sceneTreeData" :props="idDefaultProps" @node-click="handleNodeClick" :highlight-current="true"></el-tree>
      </div>
      <div class="sceneManage-right fl">
        <ifbp-template ref="template-table"
                      tplId="customer-table-template"
                      :tplData="sceneTableData"
                      show-type="table"
                      :funnode="funnode"
                      :nexuskey="nexuskey"
                      :page-comp="this"
                      :tplResetFun="sceneTableResetFun"
                      :methods="sceneTableMethods">
        </ifbp-template>
        <!--分页组件-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalElements"
          >
        </el-pagination>
        <el-dialog
          title="提示"
          v-model="delDialogVisible"
          @update:visible="val => delDialogVisible = val"
          :modal="true"
          size="tiny">
          <span>确认删除该数据？删除后无法恢复。</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="delDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteClick">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
        v-model="tableDialogVisible"
        @update:visible="val => tableDialogVisible = val"
        :modal="true"
        @close="tableDialogVisibleClose"
        >
        <div class="sceneSyncOpr">
          <ul class="fl">
            <li class="fl" :class="{'sceneActive':isRead === 0 }" @click="showMsg(0)">未读</li>
            <li class="fl allRead" :class="{'sceneActive':isRead === 2 }" @click="showMsg(2)">全部</li>
          </ul>
          <el-button type="primary" class="fr readReset" @click="syncSetRaed">标记为已读</el-button>
          <!-- <div class="fr readReset" @click="syncSetRaed">

          </div> -->
          <ifbp-template ref="scene-sync-table"
                        tplId="customer-table-template"
                        :tplData="sceneSyncTableData"
                        show-type="table"
                        :show-header="false"
                        :funnode="funnodesync"
                        :nexuskey="nexuskeysync"
                        :page-comp="this"
                        @selection-change="syncHandleSelectionChange"
                        :tplResetFun="sceneSyncTableResetFun"
                        :methods="sceneSyncTableMethods">
          </ifbp-template>
          <el-pagination
            @size-change="syncHandleSizeChange"
            @current-change="syncHandleCurrentChange"
            :current-page="syncCurrentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="syncSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="syncTotalElements"
            >
          </el-pagination>

        </div>
        <!-- <el-tabs type="border-card">
          <el-tab-pane label="未读">用户管理</el-tab-pane>
          <el-tab-pane label="全部">配置管理</el-tab-pane>
        </el-tabs> -->
        </el-dialog>
      </div>
    </div>
  </div>

</template>

<script>
export default {
  data() {
    var scenePath = this.$root.$router.currentRoute.path;
    var self = this;
    return {
      isHide:false,
      sceneTreeData:[],
      readData:[],
      scenePath : scenePath,
      isRead:0,
      idDefaultProps: {
        children: 'children',
        label: 'name'
        },
        // scenePk:'c31006ed-b410-46ca-954c-46234427a34d',
        sceneSyncPk:'07900091-034a-498f-b166-f13e2286d142',
        funnode:'CJGL',
        nexuskey:'scene_list',
        funnodesync:'CJGL',
        nexuskeysync:'CJTB_LIST',
        // sceneInterval:,
        pkScene:[],
        syncC:0,
        syncS:10,
        scenePag:false,
        totalElements: 0,
        currentPage: 1,
        size: 10,
        totalpages:0,
        syncSize:10,
        syncTotalElements:0,
        syncCurrentPage:1,
        showDeleteButton:false,
        delDialogVisible:false,
        tableDialogVisible:false,
        sceneDelId:'',
        sceneMsgId:'',
        sceneTableData: {},
        sceneSyncTableData:{},
        // unRead:[],
        sceneCode:'',
        sceneTableMethods: {

          handleSelectionChange: function(selection) {
            if (selection && selection.length > 0) {
              self.showDeleteButton = true;
            } else {
              self.showDeleteButton = false;
            }
          },
          tableEditClick: function(scope) {
            // debugger;
            // clearInterval(this.sceneInterval);
            location.hash = "/sceneManage/detail/" + scope.row.id;
          },
          tableDeleteClick: function(scope) {
            self.delDialogVisible = true;
            self.sceneDelId = scope.row.id;
          },
          sceneViewMsg:function(data){
            // debugger;
            self.sceneMsgId = data;
            self.tableDialogVisible = true;
            self.showMsg(0,10,0);
            // console.log(data);

          }
        },
        sceneTableResetFun: function($node) {
          // this.scenePag = true;
          var $table = this.getNodeById($node, "cckklhonjw8");
          var operateArr = [
            {
              title: "编辑",
              click: "tableEditClick",
              icon: "edit"
            },
            {
              title: "删除",
              click: "tableDeleteClick",
              icon: "delete"
            }
          ];
          var operateHtml = this.getTableOperateHtml(operateArr);
          $table.append('<el-table-column label="同步消息" width="120"><template scope="scope"><div v-if="!scope.row.num" @click="sceneViewMsg(scope.row.id)">暂无</div><el-badge :value="scope.row.num" class="item" v-else><el-button size="small" @click="sceneViewMsg(scope.row.id)">未读</el-button></el-badge></template></el-table-column>')
          $table.append(operateHtml);
          $table.attr("v-on:selection-change", "handleSelectionChange");
          return $node[0].outerHTML;
        },
        sceneSyncTableResetFun: function($node) {
          // var $syncTable = this.getNodeById($node, "jfpza5d3b1r");
          // $syncTable.attr("v-on:selection-change", "syncHandleSelectionChange");
        },
        sceneSyncTableMethods: function() {

        }
    };
  },
  methods: {
    tableDialogVisibleClose() {
      // debugger;
      this.isRead = 0;
    },
    syncSetRaed() {
      if(this.pkScene.length > 0){
        this.$http({
          url: "/ifbp-app-sm-infoset-web/scene_sync/updateMsgState",
          method: 'post',
          dataType: 'json',
          data:this.pkScene,
          contentType: 'application/json',
        }).then((res) => {
          if (res.data.success === true) {
            // debugger;
            this.showMsg(0,10,this.isRead);

          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(() => {
          this.$message({
            message: 'Network error',
            type: 'error'
          });
        });
      }
    },
    syncHandleSelectionChange(selection){
      // debugger
      selection.forEach((v) => {
        if (this.pkScene.indexOf(v.pk) === (-1)) {
          this.pkScene.push(v.pk);
        }
      });
      // console.log(this.pkScene);
    },
    showMsg(isRead) {
      // debugger;
      // this.isRead = 0;
      var data;
      // console.log(e);
      // if(e){
      //   var tar = e.currentTarget;
      //   var children = tar.parentNode.children;
      //   for (let i = 0; i < children.length; i++) {
      //     $(children[i]).removeClass("sceneActive");
      //   }
      //   $(tar).addClass("sceneActive");
      // }
      // if(n === undefined) {
      //   this.syncC = 0;
      //   this.syncS = 10;
      // } else {
      //   this.syncC = n;
      //   this.syncS = s;
      // }
      if(isRead === undefined){
        this.isRead = 0;
      }else{
        this.isRead = isRead;
      }
       data= {
        pageNum:this.syncCurrentPage-1,
        pageSize:this.syncSize,
        "searchParams": {
          "searchMap": {
            pk_scene:this.sceneMsgId,
            isread:this.isRead
          }
        }
      };
      this.$http({
        url: "/ifbp-app-sm-infoset-web/scene_sync/page",
        method: 'post',
        dataType: 'json',
        data:data,
        contentType: 'application/json',
      }).then((res) => {
        if (res.data.success === true) {
          // debugger;
          // if(!this.$refs["scene-sync-table"]) {
          //   return;
          // }
          this.$nextTick(() => {
            this.$nextTick(() =>{
              if(this.$refs["scene-sync-table"]) {
                 // this.$refs["scene-sync-table"].setTableData(res.data.data);
                 this.$refs["scene-sync-table"].setData(
                   "SceneSyncResultEntity_t",
                   res.data.data.content
                 );
               } else {
                 this.$set(this.sceneSyncTableData, 'SceneSyncResultEntity_t', res.data.data.content);
               }

            });
            // this.$refs["scene-sync-table"].setData(
            //   "SceneSyncResultEntity_t",
            //   res.data.data.content
            // );
          });

          this.syncSize = res.data.data.size;
          this.syncTotalElements =  res.data.data.totalElements;
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(() => {
        this.$message({
          message: '同步消息获取失败',
          type: 'error'
        });
      });

    },
    // sceneViewMsg() {
    //   debugger;
    // },
    // ss(){
    //   debugger;
    // },
    // treeOpro(treeNode) {
    //   // console.log(treeNode);
    //   if(treeNode) {
    //     var children = treeNode.querySelector(".el-tree-node__children");
    //     // debugger;
    //     if(children && children.innerHTML) {
    //       var cTreeNode = children.querySelector(".el-tree-node");
    //       return this.treeOpro(cTreeNode);
    //     } else {
    //       return treeNode;
    //     }
    //   }
    // },
    handleSizeChange(val) {
      this.size = val;
      this.currentPage = 1;
      this.sceneTableRequest();
    },
    handleCurrentChange(val) {
      this.size = 10;
      this.currentPage = val;
      this.sceneTableRequest();
    },
    syncHandleSizeChange(val) {
      this.syncCurrentPage = 1;
      this.syncSize = val;
      this.showMsg(this.isRead);
    },
    syncHandleCurrentChange(val) {
      this.syncCurrentPage = val;
      this.syncSize = 10;
      this.showMsg(this.isRead);
    },
    sceneTreeRequest() {
      // debugger;
      this.$http({
        url: "/ifbp-app-sm/buz/display",
        method: 'GET',
        dataType: 'json',
        contentType: 'application/json',
      }).then((res) => {
        if (res.data.success === true) {
          this.sceneTreeData = res.data.data;
          // this.$nextTick(() => {
          //   var treeNode = document.querySelector(".el-tree > .el-tree-node");
          //   var node = this.treeOpro(treeNode);
          //   if(node) {
          //     node.click();
              // this.sceneTableRequest(0,10);
            // }
            // document.querySelectorAll(".el-tree > .el-tree-node")[0].querySelectorAll(".el-tree-node__children > .el-tree-node:first-child")[1].click();
          // });
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(() => {
        this.$message({
          message: 'Network error',
          type: 'error'
        });
      });
    },
    sceneTableRequest() {
      // var url;
      // debugger;
      var vm = this;
      var data = {
        pageNum:this.currentPage-1,
        pageSize:this.size,
        "searchParams": {
          "searchMap": {"busitypecode":this.sceneCode}
        }
      };
      // if (n === undefined) {
      //   data = {
      //     "pageNum":0,
      //     "pageSize":10,
      //     "searchParams": {
      //       "searchMap": {"busitypecode":this.sceneCode}
      //     }
      //   };
      // } else {
      //   data = {
      //     "pageNum":n,
      //     "pageSize":s,
      //     "searchParams": {
      //       "searchMap": {"busitypecode":this.sceneCode}
      //     }
      //   };
      // }
      this.$http({
        url: "/ifbp-app-sm-infoset-web/scene/page",
        method: 'POST',
        dataType: 'json',
        data:data,
        contentType: 'application/json',
      }).then((res) => {
        if (res.data.success === true) {
          // debugger;
          var ids = [];
          this.originalValue = res.data.data.content;
          for (var i = 0; i < res.data.data.content.length; i++) {
            ids.push(res.data.data.content[i].id);
          }
          this.$nextTick(() => {
            if(this.$refs["template-table"]){
              // this.$refs["template-table"].setTableData(this.originalValue);
              this.$refs["template-table"].setData(
                "PubSceneEntity_t",
                JSON.parse(JSON.stringify(this.originalValue))
              );
            } else{
              this.$set(this.sceneTableData, 'PubSceneEntity_t', this.originalValue);
            }
            // this.$refs["template-table"].setData(
            //   "PubSceneEntity_t",
            //   JSON.parse(JSON.stringify(this.originalValue))
            // );
          });
          this.totalElements = res.data.data.totalElements;
          this.size = res.data.data.size;
          var refresh = function() {
            this.$http({
              url: "/ifbp-app-sm-infoset-web/scene_sync/querySyncMessageNum",
              method: 'POST',
              dataType: 'json',
              data:ids,
              contentType: 'application/json',
            }).then((res) => {
              if (res.data.success === true) {
                // debugger;
                this.unRead = res.data.data;
                for(var i = 0; i < res.data.data.length;i++){
                  this.originalValue[i].num = res.data.data[i].num;
                }
                this.$nextTick (() =>{
                   if(this.$refs["template-table"]) {
                      // this.$refs["template-table"].setTableData(res.data.data);
                      this.$refs["template-table"].setData(
                        "PubSceneEntity_t",
                        JSON.parse(JSON.stringify(this.originalValue))
                      );
                    } else {
                      this.$set(this.sceneTableData, 'PubSceneEntity_t', this.originalValue);
                    }
                  // this.$refs["template-table"].setData(
                  //   "PubSceneEntity_t",
                  //   JSON.parse(JSON.stringify(this.originalValue))
                  // );
                })
              }
            }).catch(() => {
              this.$message({
                message: '场景同步消息条数获取失败',
                type: 'error'
              });
            });
          };
          refresh.apply(vm);
          clearInterval(window.sceneInterval);
          // debugger;
            window.sceneInterval = setInterval(() => {
              // debugger;
              if(location.hash !== '#/sceneManage' || ids.length < 1 ){
                return;
              }
              refresh.apply(vm);
            }, 12000);
          // }

        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(() => {
        this.$message({
          message: '模型视图消息获取失败',
          type: 'error'
        });
      });
    },
    handleNodeClick(data) {
      if(data.children && data.children.length > 0 ){
        return;
      }
      this.sceneCode = data.code;
      this.sceneTableRequest(0,10);
    },
    sceneManageShowSearch() {
      this.isHide = !this.isHide;
    },
    backInfo() {
      // clearInterval(this.sceneInterval);
      this.$router.push('/appArea');
    },
    sceneAdd() {
      // clearInterval(this.sceneInterval);
      // debugger;
      location.hash = "/sceneManage/add/" + this.sceneCode;
    },
    deleteClick() {
      // debugger;
      var data = this.sceneDelId;
      this.$http({
        url: "/ifbp-app-sm-infoset-web/scene/deleteById",
        method: "post",
        dataType:"application/json",
        headers: {
            "Content-Type": "application/json"
          },
        data:data
      })
        .then(res => {
          if (res.data.success === true) {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.delDialogVisible = false;
            this.sceneTableRequest(0,10);
          } else {
            this.$message({
              message: res.data.msg,
              type: "error"
            });
          }
        })
        .catch(() => {
          this.$message({
            message: "Network error",
            type: "error"
          });
        });
    }
  },
  created() {

  },
  mounted() {
    // debugger;
    this.sceneTreeRequest();
    // this.showMsg(0);
    // this.sceneTableRequest(0,10);
  },

}
</script>
<style>
.sceneManage-list{
  /*width:100%;*/
  height:100%;
  padding:20px 30px;
}
.sceneManage-list .sceneManage-opr{
  height: 56px;
  background: #fff;
  line-height: 56px;
  padding: 0 0.5rem;
}
.sceneManage-list .sceneManage-main {
  margin-top: 0.5rem;
  height:calc(100% - 60px);
  /*display:flex;*/
}
.sceneManage-list .sceneManage-left{
  width: 20%;
  height:100%;
  background: #fff;
  overflow-y: scroll;
}
.sceneManage-list .sceneManage-right{
  width: calc(80% - 10px);
  /*flex:1;*/
  height:100%;
  background: #fff;
  margin-left: 10px;
}
.sceneManage-list .sceneManage-left .el-tree{
  border: none !important;
}
.sceneManage-list .el-badge {
  display:inherit;
  width:24px;
  /*height:15px;*/
}
.sceneManage-list .el-badge .el-button{
  padding: 5px 3px;
}
.sceneManage-list .el-badge__content.is-fixed{
  top: 9px !important;
  right: -7px !important;
}

.sceneSyncOpr>ul{
  height:32px;
  margin: 10px 0;
}
.sceneSyncOpr>ul .allRead{
  margin-left: 10px;
}
.sceneSyncOpr>ul>li{
  width:50px;
  line-height: 32px;
  background: #fff;
  text-align: center;
  border: 1px solid #fdfdfd;
  border-radius: 5px;
  cursor: pointer;
}
.sceneActive{
  background: #20a0ff !important;
  color:#fff;
}
.readReset{
  margin: 10px 0 0 10px;
}
.sceneSyncOpr .yon-uitemplate{
  margin-top: 10px;
  clear:both;
}
</style>
