<template>
  <ifbp-page id="searchNew">
    <!-- 节点title -->
    <ifbp-breadcrumb name="搜索模板管理"></ifbp-breadcrumb>
    <!-- <md-page slot="master" title="搜索模板" show-footer="false">
      <el-tree
        :data="treeData" :props="defaultProps"
        style="height: 400px;overflow: auto;"
        accordion
        :highlight-current="true"
        @current-change="handleTreeChange"
      >
      </el-tree>
    </md-page> -->
    <!-- 按钮区域 -->
    <div class="searchBtnArea">
      <div class="fl">
        <el-button type="primary" @click="add" slot="toolbar">新增</el-button>
      </div>
        <div class="fr">
          <ifbp-search
          class="fr"
          :template-code="searchTplCode"
          @search="handleSearch"
          >
          </ifbp-search>
      </div>   
    </div>
    <!-- 主体区域 -->
    <ifbp-main-area type="list">
      <div class="ifbp-icon-line">
        <div class="fl">
          <el-cascader
                v-if="treeTableTree && treeTableTree.length"
                ref="treeCascader"
                class="searchFilterCascader"
                expand-trigger="hover"
                popper-class="treeCascaderMenu"
                :change-on-select="false"
                :show-all-levels="true"
                :options="treeTableTree"
                v-model="selectedTreeNode"
                placeholder="业务类型"
                label="业务类型"
                @change="handleTreeChange">
              </el-cascader>
        </div>
        <div class="fr">
          <i class="ifbp-icon-view-headline" :class='{"active":searchIconActive}' @click='tabFn("table")' title="列表"></i>
          <i class="ifbp-icon-view-module" :class='{"active":!searchIconActive}' @click='tabFn("card")' title="卡片"></i>
          <i class="ifbp-icon-setting" @click='tabFn("setting")' title="设置"></i>
        </div>
      </div>
      <!-- UI模板组件 -->
      <ifbp-template ref="searchTplTableRef"
        :funnode="funnode"
        :nexuskey="nexuskey"
        :tpl-data="tplTableData"
        show-type="table"
        :table-show-menu="false"
        :tpl-reset-fun="tplTableResetFun"
        @edit-table-click="tplTableEditClick"
        @delete-table-click="tplTableDeleteClick"
        v-show="searchIconActive"
      >
      </ifbp-template>
      <!-- 卡片 -->
      <ul class="cardArea" v-if="cardData && cardData.length && !searchIconActive">
        <li
          v-for="(column,index) in cardData"
        > 
          <div class="mainArea">
            <div class="fl lArea">
              <h3 :title="column.name">{{column.name}}</h3>
              <span>{{column.namespace}}</span>
              <span>{{column.scenecode}}</span>
            </div>
            <div class="rArea">
              <label>
                <span v-if="column.issys">系统预置</span>
              </label>
              <i class="ifbp-icon-search"></i>
            </div>
          </div>
          <div class="btnArea">
            <i class="ifbp-icon-edit" @click='tabFn("edit",index)' title="编辑"></i>
            <i class="ifbp-icon-delete" @click='tabFn("delete",index)' title="删除"></i>
          </div>
        </li>
      </ul>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalElements" 
      >
      </el-pagination>
    </ifbp-main-area>
    <!-- 新增模板 Dialog -->
    <el-dialog title="创建搜索模版" :modal="false" v-model="addDialogVisible">
      <el-form label-width="100px" ref="editForm">
        <el-form-item label="搜索模型视图:">
          <el-ref
            :is-muti-select="true"
            ref-code="pubscence_ref"
            field="ref_code"
            :template-value="dialogForm"
            :query-params="{busitypecode: busitypecode}"
            width="300px"
            :is-edit="true"
            @trigger="handleRefTrigger"
            ref="addDialogRef"
          >
          </el-ref>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCancel">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!--删除确认 Dialog -->
    <ifbp-del-dialog
      v-model="delDialogVisible"
      message="确认删除该数据？删除后无法恢复。"
      @click="deleteClick"
      >
    </ifbp-del-dialog>
  </ifbp-page>
</template>


<script>
export default {
  data() {
    // console.log(this.$route);
    var vm = this;
    return {
      /**
       * UI 模板传入参数
       */
      // tplTablePk: 'e42aba51-e0d7-494f-a606-4377932ab4b9',
      funnode:'CXMB',
      nexuskey:'CXGL_LIST',
      tplTableData: {},
      tplTableResetFun: function($node) {
        var $table = this.getNodeById($node, '1pep94ygldn');
        var operateHtml = this.getBaseTableOperateHtml(); // 操作列
        $table.append(operateHtml);
        var $isSys = this.getNodeById($node, 'wmz32gq6qzt'); // 是否系统预置
        $isSys.html(`
          <template scope="scope">
            <div>{{ scope.row.issys ? '是' : '否' }}</div>
          </template>
        `);
        return $node[0].outerHTML;
      },

      /**
       * 分页传入参数
       */
      totalElements: 0,
      currentPage: 1,
      pageSize: 10,

      /**
       * dialogs 相关
       */
      addDialogVisible: false,
      delDialogVisible: false,
      delId: '',
      dialogForm: {
        ref_code: null
      },

      // ref相关
      refCode: null,
      refId: null,

      currentTitle: '',
      treeData: [],
      tplTree: [],
      busitypecode: '',
      currentApp: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      // search template 相关
      searchTplCode: 'CXMB_001',
      searchTpl: null,
      //级联选择器
      selectedTreeNode: [],
      treeTableTree:[],
      //卡片列表切换
      searchIconActive: true,
      cardData:[]
    };
  },
  methods: {

    // 获取模板列表
    request() {
      console.log('currentPage:' + this.currentPage);
      console.log('pageSize:' + this.pageSize);
      if (!this.busitypecode) {
        this.$message('请选择有效的磁贴节点');
        return;
      }
      var requestUrl = '/ifbp-app-sm-qt-web/quyerTemplate/page';
      var requestData = {
        searchParams: {
          searchMap: {
            busicode: this.busitypecode
          }
        },
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize
      };
      if (this.searchTpl) {
        requestData.searchParams.searchMap.qtAggVO = JSON.stringify(this.searchTpl);
        // console.log(JSON.stringify(requestData));
      }
      this.$http({
        url: requestUrl,
        method: 'post',
        data: requestData,
        dataType: 'json'
      })
        .then(res => {
          if (res.data.success) {
            this.$nextTick(() => {
              if (this.$refs.searchTplTableRef) {
                this.cardData=res.data.data.content;
                this.$refs.searchTplTableRef.setTableData(res.data.data.content);
              } else {
                this.$set(this.searchTplTableRef, 'SMQueryTemplateEntity_t', res.data.data.content);
              }
            });
            this.totalElements = res.data.data.totalElements;
            this.pageSize = res.data.data.size;
          } else if (res.data.error && res.data.error.errorMessage) {
            console.log('信息获取失败', JSON.stringify(res.data.error));
            this.$message({
              message: '信息获取失败: ' + res.data.error.errorMessage,
              type: 'error'
            });
          }
        })
        .catch(() => {
          this.$message({
            message: '信息获取失败',
            type: 'error'
          });
        });
    },

    // 获取树的数据
    getTreeData() {
      this.$http({
        url:'/ifbp-app-sm/buz/display'
      }).then((res) => {
        if(res.data.success) {
          this.treeData = res.data.data;
          let fotmated = this.formatTreeLabel(this.treeData);
          this.treeTableTree=fotmated;
        } else if (res.data.error && res.data.error.errorMessage) {
          console.log('树获取失败', JSON.stringify(res.data.error));
          this.$message({
            message: '树获取失败: ' + res.data.error.errorMessage,
            type: 'error'
          });
        }
      }).catch((e) => {
        console.log(e);
        this.$message.error('请求出错');
      });
    },


    /**
     * UI模板方法
     */

    // table行的编辑操作
    tplTableEditClick(scope) {
      console.log(scope);
      this.$router.push('/searchTplEdit/' + scope.row.id);
    },
    // table行的删除操作
    tplTableDeleteClick(scope) {
      this.delDialogVisible = true;
      this.delId = scope.row.id;
    },
    // 卡片的编辑操作
    tplCardEditClick(row) {
      this.$router.push('/searchTplEdit/' + row.id);
    },
    // 卡片的删除操作
    tplCardDeleteClick(row) {
      this.delDialogVisible = true;
      this.delId = row.id;
    },
    // 删除
    deleteClick() {
      var delId = this.delId;
      // console.log("delete" + delId);
      this.delDialogVisible = false;
      var requestUrl = '/ifbp-app-sm-qt-web/quyerTemplate/deleteById';
      this.$http({
        url: requestUrl,
        method: 'post',
        data: delId,
        dataType: 'json',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          if (res.data && res.data.success) {
            this.$message('删除成功');
            this.request();
          }
        })
        .catch(() => {
          this.$message({
            message: '删除失败',
            type: 'error'
          });
        });
    },


    /**
     * 分页
     */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.request();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.request();
    },

    handleTreeChange(treeItem) {
      console.log(treeItem);
      if(Array.isArray(treeItem) && treeItem.length) {
        this.currentApp = treeItem[treeItem.length-1];
        //this.currentTitle = this.currentApp.label;
        this.busitypecode = this.currentApp;
        this.request();
      }
    },
    add() {
      if (this.currentApp === '') {
        this.$message('请选择有效的磁贴节点');
      } else {
        this.dialogForm.ref_code = null;
        this.addDialogVisible = true;
      }
    },
    addConfirm() {
      if (!this.refCode || !this.refId || !this.busitypecode) {
        this.$message('请选择有效的搜索模型视图');
        return;
      }
      this.addDialogVisible = false;

      // 解决跳转时 dialog 未关闭
      this.$nextTick(() => {
        this.$router.push('/searchTplCreate/' + this.busitypecode + '/' + this.refCode + '/' + this.refId);
      });
    },
    addCancel() {
      this.addDialogVisible = false;
      this.dialogForm.ref_code = null;
    },

    // 处理参照事件
    handleRefTrigger(type, data) {
      // console.log(type, data);
      if (type === 'change' && data && data.value && data.value[0]) {
        this.refCode = data.value[0].refcode;
        this.refId = data.value[0].id;
      }
    },

    // 处理高级搜索事件
    handleSearch(tpl) {
      if (!tpl) {
        return;
      }
      this.currentPage = 1;
      this.searchTpl = tpl;
      this.request();
    },
    // 格式化树状参照的显示(code + name)
    formatTreeLabel(dataArr) {
      if (!Array.isArray(dataArr)) {
        return dataArr;
      }
      for (let i = 0; i < dataArr.length; i++) {
        let refObj = dataArr[i];
        if (Object.prototype.toString.call(refObj) !== '[object Object]') {
          continue;
        }
        refObj.label = refObj.name;
        refObj.value = refObj.code;
        if (refObj.children) {
          refObj.children = this.formatTreeLabel(refObj.children);
        }
      }
      return dataArr;
    },
    // 格式化标签显示名
    formatTreeTableTree(dataArr) {
      dataArr.forEach(node => {
        node.label = node.refcode ? node.refcode + ' ' + node.name : node.name;
        node.value = node.code;
      });
      return dataArr;
    },
    //切换显示
    tabFn(name,index){
      if(name=="table"){
        this.searchIconActive = true;
      }else if(name=="card"){
        this.searchIconActive = false;
      }else if(name=="setting"){
        this.$refs.searchTplTableRef.setTransferVisible(true);
      }else if(name=="edit"){
        this.tplCardEditClick(this.cardData[index]);
      }else if(name=="delete"){
        this.tplCardDeleteClick(this.cardData[index]);
      }
    }
  },
  mounted() {
    this.getTreeData();
  }
};
</script>

<style>
  /* 按钮区域 */
  .searchBtnArea{
    background: #fff;
    padding: 16px;
  }
  .ifbp-icon-line{
    display: block;
    height: 32px;
  }
  /* 级联选择器样式 */
  .searchFilterCascader {
    margin-top: -5px;
    min-width: 80px;
  }
  .searchFilterCascader .el-input__inner{
      border: none;
      padding: 0;
  }

  .searchFilterCascader .el-input{
    position:absolute;
  }
  .searchFilterCascader .el-cascader__label{
    padding: 0 25px 0 0;
    top: -4px;
    position: relative;
    width: auto;
  }
  .searchFilterCascader input::-webkit-input-placeholder{   
  /* WebKit browsers */   
  color: #1f2e3d;   
  }   
  .searchFilterCascader input:-moz-placeholder{   
  /* Mozilla Firefox 4 to 18 */   
  color: #1f2e3d;   
  }   
  .searchFilterCascader input::-moz-placeholder{   
  /* Mozilla Firefox 19+ */   
  color: #1f2e3d;   
  }   
  .searchFilterCascader input:-ms-input-placeholder{   
  /* Internet Explorer 10+ */   
  color: #1f2e3d;   
  }
  /* 右侧功能按钮 */
  .ifbp-icon-line .fr i{
    color:#C8C8CD;
    font-size: 20px;
    /* margin: 0 12px 0 0; */
  }
  .ifbp-icon-line .fr i:last-child{
    margin:0;
  }
  .ifbp-icon-line .fr i:hover{
    cursor: pointer;
    color:#f00;
  }
  .ifbp-icon-line .fr i.active{
    cursor: pointer;
    color:#75787B;
  }
  /* 卡片样式 */
  .cardArea li{
    display: inline-block;
    width: 328px;
    height: 152px;
    margin: 16px 16px 0 0;
    padding: 16px 0 0 16px;
    box-sizing: border-box;
    background: #FFFFFF;
    border: 1px solid #F0F0F5;
    border-radius: 4px;
  }
  .cardArea li:hover{
    /* background: rgba(166, 183, 203, 0.3); */
    background: rgba(243,246,249,0.50);
    border: 1px solid #F0F0F5;
    box-shadow: 0 2px 4px 0 #E2E8EF;
  }
  .cardArea  .mainArea{
    height: 95px;
  }
  /* 卡片左侧内容 */
  .cardArea .lArea{
    width: 216px;
    overflow:hidden;
  }
  .cardArea .lArea h3{
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
    max-height: 48px;
    overflow: hidden;
    color: #2D2D2D;
    word-wrap:break-word;
    margin-bottom: 9px;
  }
  .cardArea .lArea span{
    display: block;
    font-size:14px;
    margin-bottom: 8px;
    color: #75787B;
  }
  /* 卡片右侧内容 */
  .cardArea .rArea{
    margin-left: 230px;

  }
  .cardArea .rArea label{
    display: inline-block;
    width: 80px;
    height: 18px;
    margin-bottom: 10px;
  }
  .cardArea .rArea span{
    display: inline-block;
    width: 100%;
    height: 100%;
    text-align: center;
    font-size: 12px;
    line-height: 18px;
    color: #fff;
    background: #A6B7CB;
    border-radius: 2px 0 0 2px;
  }
  .cardArea .rArea i{
    font-size: 64px;
    color: #F0F0F5;
  }
  /* 卡片功能按钮 */
  .cardArea  .btnArea{
    visibility: hidden;
    height: 40px;
    text-align: right;
    padding: 0 16px;
  }
  .cardArea li:hover .btnArea{
    visibility: inherit;
  }
  .cardArea  .btnArea i{
    margin: 12px 12px 0 0;
    font-size: 16px;
    color:#727171;
  }
  .cardArea  .btnArea i:last-child{
    margin: 12px 0 0 0;
  }
  .cardArea  .btnArea i:hover{
    cursor: pointer;
    color:#0089FA;
  }
</style>
