<template>
  <div class="tag-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="标签名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入标签名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="所属分类">
          <el-select
            v-model="queryParams.category_id"
            placeholder="请选择分类"
            clearable
          >
            <el-option
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-button
      type="primary"
      :disabled="selectedTags.length === 0"
      @click="handleBatchCategory"
      >批量绑定分类</el-button
    >
    <el-button
      type="danger"
      :disabled="selectedTags.length === 0"
      @click="handleBatchDelete"
      >批量删除</el-button
    >
    <!-- 添加全选控制区域 :title="selectionText"-->
    <div class="selection-control" v-if="selectedTags.length > 0">
      <el-alert
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 10px"
      >
        <template v-if="!isAllDataSelected">
          <span
            type="text"
            style="cursor: pointer; color: #409eff"
            @click="handleSelectAllData"
          >
            选择全部{{ total }}条数据
          </span>
        </template>
        <template v-else>
          <span
            type="text"
            style="cursor: pointer; color: #409eff"
            @click="handleCancelAllSelection"
          >
            取消全选
          </span>
        </template>
      </el-alert>
    </div>
    <!-- 数据表格 -->
    <el-table
      :data="tagList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @select-all="handleSelectAll"
      ref="tagTable"
      :row-key="getRowKey"
    >
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true"
      ></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="标签名称"></el-table-column>
      <el-table-column prop="category.name" label="所属分类"></el-table-column>
      <el-table-column prop="" label="已绑定文献数量"
        ><template slot-scope="scope">
          <span v-if="scope.row.literature_id !== null">{{
            JSON.parse(scope.row.literature_id).length
          }}</span>
          <span v-else>0</span></template
        ></el-table-column
      >
      <el-table-column prop="create_time" label="创建时间" sortable>
        <template slot-scope="scope">
          {{
            new Date(scope.row.create_time)
              .toLocaleString("zh-CN", {
                year: "numeric",
                month: "2-digit",
                day: "2-digit",
                hour: "2-digit",
                minute: "2-digit",
                second: "2-digit",
                hour12: false,
                formatMatcher: "basic",
              })
              .replace(/\//g, "-")
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入标签名称(以,隔开可批量增加)"
          ></el-input>
        </el-form-item>
        <!-- 新增分类选择 -->
        <el-form-item label="所属分类">
          <el-select
            v-model="form.category_id"
            placeholder="请选择分类"
            clearable
          >
            <el-option
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 批量绑定 -->
    <el-dialog
      title="绑定分类"
      :visible.sync="categoryDialogVisible"
      width="400px"
    >
      <el-form :model="categoryForm">
        <el-form-item label="选择分类">
          <el-select
            clearable
            v-model="categoryForm.category_id"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="categoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategoryBinding"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  add_tags,
  get_literature_tags,
  remove_tags,
  search_tags,
  edit_tags,
  categories,
  categoriesUpdata,
} from "@/api/knowledge";
import axios from "axios";
export default {
  name: "TagManagement",
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        category_id: "", // 新增分类搜索参数
      },
      // 标签列表数据
      tagList: [],
      // 总记录数
      total: 0,
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: "",
      // 表单对象
      form: {
        id: undefined,
        name: "",
        category_id: null, // 新增分类字段
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      // 加载状态
      loading: false,
      selectedTags: [], // 新增：选中的标签数组
      categoriesList: [],
      categoryDialogVisible: false,
      categoryForm: {
        category_id: null,
      },
      selectedTags: [], // 当前页选中的标签
      allSelectedTags: new Map(), // 存储所有页面选中的标签
      isAllDataSelected: false, // 是否选中所有数据
    };
  },
  created() {
    this.getList();
    this.cateList();
  },
  computed: {
    // 选择提示文本
    selectionText() {
      const selectedCount = this.isAllDataSelected
        ? this.total
        : this.allSelectedTags.size;
      return `已选择 ${selectedCount} 项`;
    },
  },
  methods: {
    // 处理选择全部数据
    async handleSelectAllData() {
      try {
        // 获取所有数据的ID
        const params = {
          page: 1,
          pagesize: this.total, // 获取所有数据
          keyword: this.queryParams.name,
          category_id: this.queryParams.category_id,
        };

        const response = await search_tags(params);

        if (response.status === 200) {
          const allData = response.data.data.items || [];
          // 清空之前的选择
          this.allSelectedTags.clear();
          // 将所有数据添加到选中集合
          allData.forEach((item) => {
            this.allSelectedTags.set(item.id, item);
          });

          this.isAllDataSelected = true;

          // 选中当前页显示的所有行
          this.$nextTick(() => {
            if (this.$refs.tagTable) {
              this.tagList.forEach((row) => {
                this.$refs.tagTable.toggleRowSelection(row, true);
              });
            }
          });

          this.$message.success(`已选中全部${this.total}条数据`);
        }
      } catch (error) {
        console.error("获取全部数据失败:", error);
        this.$message.error("选择全部数据失败");
      }
    },

    // 取消全选
    handleCancelAllSelection() {
      this.clearSelection();
      this.isAllDataSelected = false;
      this.$message.info("已取消全部选择");
    },
    // 获取行的唯一标识
    getRowKey(row) {
      return row.id;
    },

    // 修改选择变化处理
    handleSelectionChange(selection) {
      this.selectedTags = selection;

      if (!this.isAllDataSelected) {
        // 更新所有选中数据
        selection.forEach((item) => {
          this.allSelectedTags.set(item.id, item);
        });

        // 当前页取消选中的数据从总选中集合中移除
        this.tagList.forEach((row) => {
          if (!selection.find((item) => item.id === row.id)) {
            this.allSelectedTags.delete(row.id);
          }
        });
      }
    },

    // 处理全选
    handleSelectAll(selection) {
      if (selection.length > 0) {
        this.$message.success(`已全选当前页${selection.length}个标签`);
      } else {
        // 取消当前页所有选择
        this.tagList.forEach((row) => {
          this.allSelectedTags.delete(row.id);
        });
        this.$message.info("已取消选中当前页全部标签");
      }
    },

    // 修改分页切换方法
    async handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      await this.getList();

      // 恢复选中状态
      this.$nextTick(() => {
        if (this.$refs.tagTable) {
          this.tagList.forEach((row) => {
            if (this.allSelectedTags.has(row.id)) {
              this.$refs.tagTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },

    // 修改每页条数切换方法
    async handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      await this.getList();

      // 恢复选中状态
      this.$nextTick(() => {
        if (this.$refs.tagTable) {
          this.tagList.forEach((row) => {
            if (this.allSelectedTags.has(row.id)) {
              this.$refs.tagTable.toggleRowSelection(row, true);
            }
          });
        }
      });
    },

    // 修改批量绑定分类方法
    handleBatchCategory() {
      const selectedCount = this.isAllDataSelected
        ? this.total
        : this.allSelectedTags.size;
      if (selectedCount === 0) {
        this.$message.warning("请至少选择一个标签");
        return;
      }
      this.categoryDialogVisible = true;
    },

    async submitCategoryBinding() {
      try {
        const params = {
          tag_ids: this.selectedTags.map((tag) => tag.id), // 将数组转换为JSON字符串
          category_id: this.categoryForm.category_id,
        };

        const response = await categoriesUpdata(params);

        if (response.status === 200) {
          this.$message.success("分类绑定成功");
          this.categoryDialogVisible = false;
          this.getList();
        } else {
          this.$message.error(response.msg || "分类绑定失败");
        }
      } catch (error) {
        console.error("绑定分类出错:", error);
        this.$message.error("分类绑定失败");
      }
    },
    /* 获取标签分类 */
    cateList() {
      categories().then((res) => {
        if (res.status !== 200) return;
        this.categoriesList = res.data.data.items;
      });
    },

    // 修改批量操作相关方法
    handleBatchDelete() {
      const selectedCount = this.isAllDataSelected
        ? this.total
        : this.allSelectedTags.size;
      if (selectedCount === 0) {
        this.$message.warning("请至少选择一个标签");
        return;
      }

      this.$confirm(`确认删除选中的 ${selectedCount} 个标签吗？`, "提示", {
        type: "warning",
      }).then(async () => {
        try {
          let tagIds;
          if (this.isAllDataSelected) {
            // 如果是全选，需要获取所有数据的ID
            const response = await search_tags({
              page: 1,
              size: this.total,
              keyword: this.queryParams.name,
              category_id: this.queryParams.category_id,
            });
            tagIds = response.data.data.items.map((item) => item.id);
          } else {
            tagIds = Array.from(this.allSelectedTags.keys());
          }

          const idObject = { tag_ids: tagIds };
          const response = await remove_tags(idObject);

          if (response.status === 200) {
            this.$message.success(`成功删除${selectedCount}个标签`);
            this.clearSelection();
            this.getList();
          } else {
            this.$message.error(response.msg || "批量删除失败");
          }
        } catch (error) {
          console.error("批量删除标签出错:", error);
          this.$message.error("批量删除失败");
        }
      });
    },

    // 获取列表数据
    async getList() {
      try {
        this.loading = true;
        const params = {
          page: this.queryParams.pageNum,
          pagesize: this.queryParams.pageSize,
          keyword: this.queryParams.name,
          category_id: this.queryParams.category_id,
        };

        const response = await (this.queryParams.name
          ? search_tags(params)
          : search_tags(params));
        console.log(response);
        if (response.status === 200) {
          this.tagList = response.data.data.items || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.msg || "获取标签列表失败");
        }
      } catch (error) {
        console.error("获取标签列表出错:", error);
        this.$message.error("获取标签列表失败");
      } finally {
        this.loading = false;
      }
    },

    // 删除按钮点击
    handleDelete(row) {
      this.$confirm("确认删除该标签吗？", "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const idObject = { tag_ids: [row.id] };
            const response = await axios.post(
              `${process.env.VUE_APP_BASE_API}/literature-tags/remove_tags/`,
              idObject,
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            );
            if (response.status === 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error(response.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除标签出错:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          // 取消删除操作
        });
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            if (!this.form.id) {
              // 新增
              /* const response = await add_tags({
                tag_names: this.form.tag_names.split(','),
              }); */
              const idObject = {
                tag_names: this.form.name.split(","),
                category_id: this.form.category_id,
              };
              const response = await axios.post(
                `${process.env.VUE_APP_BASE_API}/literature-tags/add_tags/`,
                idObject,
                {
                  headers: {
                    "Content-Type": "application/json",
                  },
                }
              );
              if (response.status === 200) {
                this.$message.success("添加成功");
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(response.msg || "添加失败");
              }
            } else {
              edit_tags({
                name: this.form.name,
                id: this.form.id,
                category_id: this.form.category_id,
              }).then((res) => {
                if (res.status !== 200) return;
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.getList();
              });
            }
          } catch (error) {
            console.error("提交表单出错:", error);
            this.$message.error("操作失败");
          }
        }
      });
    },
    // 查询按钮点击
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 修改清空选择方法
    clearSelection() {
      if (this.$refs.tagTable) {
        this.$refs.tagTable.clearSelection();
      }
      this.selectedTags = [];
      this.allSelectedTags.clear();
      this.isAllDataSelected = false;
    },
    // 修改重置查询方法
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: "",
        category_id: "",
      };
      this.clearSelection(); // 清空选择
      this.getList();
    },
    // 新增按钮点击
    handleAdd() {
      this.dialogTitle = "添加标签";
      this.form = {
        id: undefined,
        name: "",
      };
      this.dialogVisible = true;
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.dialogTitle = "编辑标签";
      this.form = {
        id: row.id,
        name: row.name,
        category_id: row.category.id, // 回显分类ID
      };
      this.dialogVisible = true;
    },
  },
};
</script>
  
  <style scoped>
.button-group {
  margin-bottom: 20px;
}
.tag-container {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>