<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="treeLevel === 0" v-slot:left_action>
              <div class="apaas_button">
                <el-button type="primary" @click="addDocType">
                  <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-select v-model="filter.is_active" placeholder="请选择" style="width: 300px">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="已启用" :value="1"> </el-option>
                    <el-option label="已停用" :value="0"> </el-option>
                  </el-select>
                </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:is_active="{ row }">
                <el-switch
                  style="
                    --el-switch-on-color: #2b4695;
                    --el-switch-off-color: #cbced7;
                    height: 20px;
                  "
                  v-model="row.is_active"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  :before-change="() => beforeSwitchStatus(row)" />
              </template>

              <template v-slot:action="{ row }">
                <bg-table-btn @click="editCurType(row)"> 编辑 </bg-table-btn>
                <bg-table-btn @click="deleteCurType(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="secondTipsDialogConfig.visible"
      :title="secondTipsDialogConfig.title"
      width="520px">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        {{ secondTipsDialogConfig.content }}
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseSecondTipsDialog">取消</el-button>
          <el-button type="primary" @click="secondConfirm(secondTipsDialogConfig.type)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="formDialogConfig.visible"
      :title="formDialogConfig.title"
      width="600px"
      :before-close="handleCloseForm">
      <el-form label-width="80px" :model="formData" :rules="rules" ref="ruleForm">
        <el-form-item required label="上级类型" prop="parent_id">
          <el-tree-select
            v-model="formData.parent_id"
            :data="parentTypeData"
            :props="defaultProps"
            node-key="classify_id"
            :highlight-current="true"
            :filter-node-method="filterNode"
            check-strictly
            filterable
            :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="类型名称" prop="classify_name">
          <el-input v-model="formData.classify_name" placeholder="请输入"> </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number.trim="formData.sort" placeholder="请输入"> </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="describe">
          <el-input v-model="formData.describe" :rows="3" type="textarea" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="is_active">
          <el-switch
            style="--el-switch-on-color: #2b4695; --el-switch-off-color: #cbced7; height: 20px"
            v-model="formData.is_active"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseForm">取消</el-button>
          <el-button type="primary" @click="confirmForm">确定</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 { useRoute, 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 selectNode = ref(null);
const selectNodeObj = ref(null);
const filterTree = ref("");
const treeRef = ref(null);
//校验上级类型
const state = reactive({
  filter: {
    search: "",
    is_active: "",
    page: 1,
    limit: 10,
  },
  headers: [
    {
      label: "类型名称",
      prop: "classify_name",
      minWidth: 160,
    },
    {
      label: "上级类型名称",
      prop: "parent_classify_name",
      minWidth: 160,
    },
    {
      label: "启用状态",
      prop: "is_active",
    },

    {
      label: "操作",
      prop: "action",
      width: 220,
      fixed: "right",
    },
  ],
  tableRows: [],
  tableTotal: 0,
  formDialogConfig: {
    visible: false,
    title: "新增",
    type: "add",
  },
  formData: {
    parent_id: "",
    classify_name: "",
    sort: "",
    describe: "",
    is_active: 0,
  },
  rules: {
    parent_id: [
      {
        required: true,
        message: "请选择",
        trigger: "change",
      },
    ],
    classify_name: [
      {
        required: true,
        message: "请输入",
        trigger: "blur",
      },
    ],
  },
  //左侧类型树层级
  treeLevel: 0,
  //删除确认弹框
  secondTipsDialogConfig: {
    visible: false,
    title: "",
    type: "",
    content: "",
  },
  selectedRow: null,
});

const {
  filter,
  headers,
  tableRows,
  tableTotal,
  formDialogConfig,
  formData,
  rules,
  treeLevel,
  secondTipsDialogConfig,
} = toRefs(state);
onBeforeMount(() => {
  getTypeTree();
});
watch(filterTree, (val) => {
  treeRef.value.filter(val);
});
watch(selectNode, (val) => {
  state.formData.parent_id = val;
});
const filterAction = () => {
  changePage(1);
};
const filterClear = () => {
  state.filter = {
    search: "",
    is_active: "",
    page: 1,
    limit: 10,
  };
  changePage(1);
};

const router = useRouter();
const getTableRows = () => {
  let params = {
    ...state.filter,
    classify_id: selectNodeObj.value.id ? selectNodeObj.value.id : undefined,
  };
  axios
    .get(`/apaas/knowledge/v5/documentmgr/classify/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 addDocType = () => {
  state.formDialogConfig = {
    visible: true,
    title: "新增",
    type: "add",
  };
};

const handleNodeClick = (data) => {
  selectNode.value = data.classify_id;
  selectNodeObj.value = data;
  state.treeLevel = data.level;
  changePage(1);
};

const typeData = ref([]);
const parentTypeData = ref([]);
const defaultProps = {
  label: "classify_name",
  children: "children",
  value: "classify_id",
};
const getTypeTree = () => {
  axios.get(`/apaas/knowledge/v5/documentmgr/classify/tree`).then((res) => {
    if (res.data.code == 200) {
      const result = res.data.data || [];
      result.length ? (result[0].classify_id = "topLevel") : null;
      typeData.value = result;
      parentTypeData.value = getParentTree(typeData.value);
      selectNode.value = typeData.value.length > 0 ? typeData.value[0].classify_id : "";
      selectNodeObj.value = typeData.value.length > 0 ? typeData.value[0] : null;
      nextTick(() => {
        treeRef.value.setCurrentNode(selectNodeObj.value);
      });
      changePage(1);
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
//过滤掉level不为0的层级
const getParentTree = (data) => {
  let arr = [];
  data.forEach((item) => {
    if (item.level === 0) {
      let obj = { classify_id: item.classify_id, classify_name: item.classify_name };
      if (item.children) obj.children = getParentTree(item.children);
      arr.push(obj);
    }
  });
  return arr;
};
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 handleCloseForm = () => {
  state.formData = {
    parent_id: selectNode.value,
    classify_name: "",
    sort: "",
    describe: "",
    is_active: 0,
  };
  state.formDialogConfig.visible = false;
};
const editCurType = async (row) => {
  const res = await axios.get(`/apaas/knowledge/v5/documentmgr/classify/detail/${row.id}`);

  if (res.data.code == 200) {
    const data = res.data.data || {};
    state.formData = {
      parent_id: data.parent_id,
      classify_name: data.classify_name,
      sort: data.sort,
      describe: data.describe,
      is_active: data.is_active,
    };
    state.selectedRow = row;
    state.formDialogConfig = {
      visible: true,
      title: "编辑",
      type: "update",
    };
  } else {
    ElMessage.error(res.data.data);
  }
};
const confirmForm = () => {
  ruleForm.value.validate((valid, fields) => {
    let params = {
      ...state.formData,
      parent_id: state.formData.parent_id !== "topLevel" ? state.formData.parent_id : "",
    };
    if (state.formDialogConfig.type === "update") {
      params = { ...params, id: state.selectedRow.id };
    }
    if (valid) {
      axios
        .post(`/apaas/knowledge/v5/documentmgr/classify/${state.formDialogConfig.type}`, params)
        .then((res) => {
          if (res.data.code == 200) {
            getTypeTree();
            ElMessage.success(res.data.msg);
          } else {
            ElMessage.error(res.data.data);
          }
          handleCloseForm();
        });
    }
  });
};
const handleCloseSecondTipsDialog = () => {
  state.secondTipsDialogConfig.visible = false;
};
const deleteCurType = (row) => {
  if (row.is_active === 1) return ElMessage.warning("该文档类型已启用，请先停用后再删除！");
  state.selectedRow = row;
  state.secondTipsDialogConfig = {
    visible: true,
    title: "删除",
    type: "delete",
    content: "确定删除该文档类型吗？",
  };
};
const beforeSwitchStatus = (row) => {
  const text = row.is_active ? "停用" : "启用";
  state.selectedRow = row;
  state.secondTipsDialogConfig = {
    visible: true,
    title: text,
    type: "switchStatus",
    content: `确定${text}该文档类型吗？`,
  };
  return false;
};
const secondConfirm = () => {
  if (state.secondTipsDialogConfig.type === "delete") {
    axios.delete(`/apaas/knowledge/v5/documentmgr/classify/${state.selectedRow.id}`).then((res) => {
      if (res.data.code == 200) {
        getTypeTree();
        ElMessage.success(res.data.msg);
      } else {
        ElMessage.error(res.data.data);
      }
      handleCloseSecondTipsDialog();
    });
    return;
  }

  if (state.secondTipsDialogConfig.type === "switchStatus") {
    axios
      .get(`/apaas/knowledge/v5/documentmgr/classify/active/${state.selectedRow.id}`)
      .then((res) => {
        if (res.data.code == 200) {
          getTypeTree();
          ElMessage.success(res.data.msg);
        } else {
          ElMessage.error(res.data.data);
        }
        handleCloseSecondTipsDialog();
      });
    return;
  }
};
</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;
}

:deep() .el-switch__core {
  min-width: 44px;
}

.el-form {
  margin-top: 24px;
  :deep() .el-select {
    width: 100%;

    .el-input .el-select__caret {
      color: #b9b9b9;
    }
  }
}

.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>
