<template>
  <div class="page_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="flex_row">
      <div class="flex_left bgc_white">
        <div class="tree_header">文档类型</div>
        <div class="tree_content">
          <div class="search">
            <el-input v-model="filterTree" placeholder="请输入文档名称" :prefix-icon="Search" />
          </div>
          <div class="tree">
            <el-tree
              ref="treeRef"
              :data="typeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              node-key="classify_id"
              :highlight-current="true"
              :filter-node-method="filterNode"
              :default-expand-all="true">
              <template #default="{ node, data }">
                <div class="custom_tree_node">
                  <span class="label-text" :title="node.label">{{ node.label }} </span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
      <div class="flex_right bgc_white">
        <div class="main_container">
          <bg-filter-group
            @search="changeSearch"
            v-model="filter.search"
            placeholder="请输入文档类型名称">
            <template v-if="showAdd" v-slot:left_action>
              <div class="apaas_button">
                <el-button type="primary" @click="addDoc">
                  <bg-icon
                    style="font-size: 12px; color: #fff; margin-right: 8px"
                    icon="#bg-ic-add"></bg-icon>
                  新增
                </el-button>
              </div>
            </template>
            <template v-slot:filter_group>
              <div class="left-filter filter_list">
                <div class="filter_item">
                  <span class="filter_title">更新时间</span>
                  <el-date-picker
                    v-model="filter.time"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 300px; flex: 0 0 auto" />
                </div>
              </div>
              <div class="right-action apaas_button">
                <el-button type="primary" @click="filterAction"> 查询 </el-button>
                <el-button type="default" @click="filterClear"> 重置 </el-button>
              </div>
            </template>
          </bg-filter-group>
          <div class="table_container apaas_scroll">
            <bg-table
              ref="dataTable"
              :headers="headers"
              :rows="tableRows"
              :isIndex="true"
              :stripe="true">
              <template v-slot:action="{ row }">
                <bg-table-btn @click="editCurDoc(row)"> 编辑 </bg-table-btn>
                <bg-table-btn @click="deleteCurDoc(row)"> 删除 </bg-table-btn>
              </template>
            </bg-table>
            <div class="pagination_box">
              <bg-pagination
                :page="filter.page"
                :size="filter.limit"
                :total="tableTotal"
                @change-page="changePage"
                @change-size="changeSize">
              </bg-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="deleteDialogVisible" title="删除" width="520px">
      <div class="warning_info delete_tips">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        <span
          >删除后，该文档将不再{{ selectedRow.classify_name }}里展示且<span style="color: red"
            >删除后无法撤销</span
          >,确定要删除吗？</span
        >
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDeleteDialog">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { watch, nextTick, reactive, toRefs, ref, computed, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";

const dataTable = ref(null);
const ruleForm = ref(null);
const selectNodeObj = ref({});
const filterTree = ref("");
const treeRef = ref(null);
const typeData = ref([]);
const defaultProps = {
  label: "classify_name",
  children: "children",
  value: "classify_id",
};
//校验上级类型
const state = reactive({
  filter: {
    search: "",
    time: [],
    page: 1,
    limit: 10,
  },
  headers: [
    {
      label: "文档名称",
      prop: "title",
      minWidth: 160,
    },
    {
      label: "文档类型",
      prop: "classify_name",
      minWidth: 160,
    },
    {
      label: "操作人",
      prop: "updated_by",
    },
    {
      label: "最后更新时间",
      prop: "updated_time",
    },
    {
      label: "操作",
      prop: "action",
      width: 220,
      fixed: "right",
    },
  ],
  tableRows: [],
  tableTotal: 0,

  //是否展示新增按钮，只有当选择没有子节点的叶子节点才展示
  showAdd: false,
  //删除确认弹框
  deleteDialogVisible: false,
  selectedRow: null,
});

const { filter, headers, tableRows, tableTotal, showAdd, deleteDialogVisible, selectedRow } =
  toRefs(state);
onBeforeMount(() => {
  getTypeTree();
});
watch(filterTree, (val) => {
  treeRef.value.filter(val);
});

const filterAction = () => {
  changePage(1);
};
const filterClear = () => {
  state.filter = {
    search: "",
    time: [],
    page: 1,
    limit: 10,
  };
  changePage(1);
};

const router = useRouter();
const getTableRows = () => {
  let params = {
    ...state.filter,
    start_at: state.filter.time ? state.filter.time[0] : undefined,
    end_at: state.filter.time ? state.filter.time[1] : undefined,
    classify_id: selectNodeObj.value.id ? selectNodeObj.value.id : undefined,
  };
  delete params.time;
  axios
    .get(`/apaas/knowledge/v5/documentmgr/document/list`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data || [];
        state.tableTotal = res.data.total;
      } else {
        ElMessage.error(res.data.data);
      }
    });
};
//新增文档
const addDoc = () => {
  router.push({
    path: "/support/document/add",
    query: {
      classify_id: selectNodeObj.value.classify_id,
    },
  });
};

const handleNodeClick = (data) => {
  selectNodeObj.value = data;
  state.showAdd = !(data.children && data.children.length);
  changePage(1);
};

const getTypeTree = () => {
  axios.get(`/apaas/knowledge/v5/documentmgr/classify/tree`).then((res) => {
    if (res.data.code == 200) {
      const result = res.data.data || [];
      typeData.value = result;
      selectNodeObj.value = typeData.value.length > 0 ? typeData.value[0] : {};
      nextTick(() => {
        treeRef.value.setCurrentNode(selectNodeObj.value);
      });
      changePage(1);
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.classify_name.includes(value);
};

const changeSize = (size) => {
  state.filter.limit = size;
  state.filter.page = 1;
  changePage(1);
};

const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
};

const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
}; // 表格关键字筛选

const editCurDoc = async (row) => {
  router.push({
    path: "/support/document/edit",
    query: {
      id: row.id,
      classify_id: row.classify_id,
    },
  });
};
const handleCloseDeleteDialog = () => {
  state.deleteDialogVisible = false;
};
const deleteCurDoc = (row) => {
  state.selectedRow = row;
  state.deleteDialogVisible = true;
};

const confirmDelete = () => {
  axios.delete(`/apaas/knowledge/v5/documentmgr/classify/${state.selectedRow.id}`).then((res) => {
    if (res.data.code == 200) {
      changePage(1);
      ElMessage.success(res.data.msg);
    } else {
      ElMessage.error(res.data.data);
    }
    handleCloseDeleteDialog();
  });
};
</script>

<style lang="scss" scoped>
.tree_header {
  height: 40px;
  line-height: 40px;
  background-color: #f7f7f9;
  border-radius: 6px 6px 0px 0px;
  font-size: 16px;
  letter-spacing: 0px;
  color: #202531;
  padding-left: 16px;
}
.tree_content {
  overflow: hidden;
  height: calc(100% - 45px);
}
.search {
  padding: 16px;
}
.tree {
  overflow: auto;
  height: calc(100% - 65px);
}
.tree :deep() .el-tree-node > .el-tree-node__children {
  overflow: unset;
}
.tree :deep().noFocus:focus > .el-tree-node__content {
  background-color: #fff;
}
.custom_tree_node {
  width: 100%;
  font-size: 14px;
  color: #202531;
  padding-right: 16px;
}
.label-text:hover {
  padding: 3px 0;
  background-color: var(--el-tree-node-hover-bg-color);
}
.main_container {
  height: 100%;
}
.table_container {
  height: calc(100% - 30px);
  overflow: auto;
  padding: 0 16px;
}
.delete_tips {
  display: flex;
  align-items: baseline;
  line-height: 20px;
}
.pagination_box {
  position: sticky;
  position: -webkit-sticky;
  margin-top: 16px;
  bottom: 25px;
  background-color: #fff;
  z-index: 1024;
  height: 40px;
  line-height: 40px;
  padding-top: 5px;
}
.bg-pagination {
  bottom: unset;
  margin-top: 0px;
}
</style>
