<template>
  <el-card class="category-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="handleAdd"
          >增加</el-button
        >
        <el-popconfirm
          title="确定删除吗？"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="handleDelete"
        >
          <template #reference>
            <el-button type="danger" :icon="Delete">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>
    <el-table
      ref="multipleTable"
      :data="state.tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="categoryName" label="分类名称"> </el-table-column>
      <el-table-column prop="categoryRank" label="排序值" width="120">
      </el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="200">
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="handleEdit(scope.row.categoryId)"
            >修改</el-button
          >
          <el-button
            type="primary"
            link
            @click="handleEditSecondaryCategory(scope.row.categoryId)"
            >二级类目管理</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            confirmButtonText="确定"
            cancelButtonText="取消"
            @confirm="handleDeleteOne(scope.row.categoryId)"
          >
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
      class="mt-4 justify-end"
      background
      layout="prev, pager, next"
      :total="state.total"
      :page-size="state.pageSize"
      :current-page="state.currentPage"
      @current-change="changePage"
    />
    <DialogAddCategory ref="addCate" :reload="getCategory" :type="state.type" />
    <DialogSecondaryCategory
      v-model:show="state.visibleSecondaryCategory"
      :id="state.parent_id"
    />
  </el-card>
</template>

<script lang="ts" setup>
import {
  onMounted,
  onUnmounted,
  reactive,
  ref,
  toRefs,
  watchEffect
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { request } from "@/utils";
import DialogAddCategory from "./components/DialogAddCategory.vue";
import DialogSecondaryCategory from "./components/DialogSecondaryCategory.vue";

const addCate = ref(null);
const router = useRouter(); // 声明路由实例
const route = useRoute(); // 获取路由参数
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  type: "add", // 操作类型
  level: 1,
  parent_id: 0,
  visibleSecondaryCategory: undefined // 二级类目管理
});
const multipleTable = ref(null);
onMounted(() => {
  getCategory();
});
watchEffect(() => {
  console.log(state.pageSize);
});
const unwatch = router.afterEach(to => {
  // 每次路由变化的时候，都会触发监听时间，重新获取列表数据
  if (["category", "level2", "level3"].includes(to.name)) {
    getCategory();
  }
});
onUnmounted(() => {
  unwatch();
});
// 获取分类列表
const getCategory = () => {
  const { level = 1, parent_id = 0 } = route.query;
  state.loading = true;
  request
    .get("/mallService/mechanism/category", {
      params: {
        page: state.currentPage,
        pageSize: state.pageSize,
        categoryLevel: level,
        parentId: parent_id
      }
    })
    .then(res => {
      state.tableData = res.data.list;
      state.total = res.data.total;
      state.loading = false;
      state.level = level;
    });
};
const changePage = val => {
  state.currentPage = val;
  getCategory();
};
const handleNext = item => {
  const levelNumber = item.categoryLevel + 1;
  if (levelNumber == 4) {
    ElMessage.error("没有下一级");
    return;
  }
  router.push({
    name: `level${levelNumber}`,
    query: {
      level: levelNumber,
      parent_id: item.categoryId
    }
  });
};
// 添加分类
const handleAdd = () => {
  state.type = "add";
  addCate.value.open();
};
// 修改分类
const handleEdit = id => {
  state.type = "edit";
  addCate.value.open(id);
};

//  修改二级类目
const handleEditSecondaryCategory = id => {
  state.visibleSecondaryCategory = true;
  state.parent_id = id;
};
// 选择项
const handleSelectionChange = val => {
  state.multipleSelection = val;
};
// 批量删除
const handleDelete = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error("请选择项");
    return;
  }
  request
    .delete("/categories", {
      data: {
        ids: state.multipleSelection.map(i => i.categoryId)
      }
    })
    .then(() => {
      ElMessage.success("删除成功");
      getCategory();
    });
};
// 单个删除
const handleDeleteOne = id => {
  request
    .delete("/mallService/mechanism/category", {
      ids: [id]
    })
    .then(() => {
      ElMessage.success("删除成功");
      getCategory();
    });
};
</script>

<style></style>
