<template>
  <ifbp-page>
    <!-- 节点title -->
    <ifbp-breadcrumb name="搜索模板管理"></ifbp-breadcrumb>
    <!-- 按钮区域 -->
    <ifbp-button-area>
      <el-button type="primary" @click="add">新增</el-button>
      <ifbp-search
      class="fr"
      :template-code="searchTplCode"
      @search="handleSearch"
      >
      </ifbp-search>   
    </ifbp-button-area>
    <!-- 主体区域 -->
    <ifbp-main-area type="list">
      <div class="ifbp-btn-line">
        <div class="fl">
          <el-cascader
            v-if="treeTableTree && treeTableTree.length"
            ref="treeCascader"
            expand-trigger="hover"
            :options="treeTableTree"
            v-model="selectedTreeNode"
            placeholder="业务类型"
            @change="handleTreeChange">
          </el-cascader>
        </div>
        <div class="fr">
          <ifbp-table-card-icon 
            :show-table="showTable" 
            @update:showTable="value => this.showTable = value">
          </ifbp-table-card-icon>
          <i class="ifbp-icon-setting" :class='{"disabled":!showTable}' @click="showHeaderSetting" 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="showTable">
      </ifbp-template>
      <!-- 卡片 -->
      <ifbp-search-tpl-mgr-card
        v-show="!showTable"
        :card-data="cardData"
        @cardEditClick="tplCardEditClick"
        @cardDeleteClick="tplCardDeleteClick">
      </ifbp-search-tpl-mgr-card>
      <!-- 分页组件 -->
      <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>
import ifbpSearchTplMgrCard from "./ifbp-search-tpl-mgr-card";
export default {
  components: { ifbpSearchTplMgrCard },
  data() {
    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 $table = this.getTableDom($node);
        var operateHtml = this.getBaseTableOperateHtml(); // 操作列
        $table.append(operateHtml);
        var $isSys = $node.find("[v-model='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: [],
      //卡片列表切换
      showTable: true,
      cardData: []
    };
  },
  methods: {
    // 获取模板列表
    request() {
      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
        );
      }
      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) {
            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) {
            this.$message({
              message: "树获取失败: " + res.data.error.errorMessage,
              type: "error"
            });
          }
        })
        .catch(e => {
          this.$message.error("请求出错");
        });
    },
    /**
     * UI模板方法
     */

    // table行的编辑操作
    tplTableEditClick(scope) {
      this.$router.push("/searchTplEdit/" + scope.row.id);
    },
    // table行的删除操作
    tplTableDeleteClick(scope) {
      this.delDialogVisible = true;
      this.delId = scope.row.id;
    },
    // 卡片的编辑操作
    tplCardEditClick(index) {
      let rowData = this.cardData[index];
      this.$router.push("/searchTplEdit/" + rowData.id);
    },
    // 卡片的删除操作
    tplCardDeleteClick(index) {
      let rowData = this.cardData[index];
      this.delDialogVisible = true;
      this.delId = rowData.id;
    },
    // 删除
    deleteClick() {
      var delId = this.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) {
      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) {
      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;
    },
    //设置表头
    showHeaderSetting() {
      if (this.showTable) {
        this.$refs.searchTplTableRef.setTransferVisible(true);
      }
    }
  },
  mounted() {
    this.getTreeData();
  }
};
</script>