<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企微账号" prop="corpId">
        <el-select v-model="queryParams.corpId" placeholder="企微账号" clearable size="small"
                   @change="updateQwuser()">
          <el-option
            v-for="dict in myQwUserList"
            :key="dict.corpId"
            :label="dict.corpName"
            :value="dict.corpId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签id" prop="tagId">
        <el-input
          v-model="queryParams.tagId"
          placeholder="请输入标签id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="FastGptExtUserTagList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="企业名称" align="center" prop="corpId">
        <template slot-scope="scope">
          {{ getCorpNameById(scope.row.corpId) }}
        </template>
      </el-table-column>
      <el-table-column label="标签名称" align="center" prop="tagName">
        <template slot-scope="scope">
          {{ getTagNameById(scope.row.tagId) }}
        </template>
      </el-table-column>
      <el-table-column label="标签id" align="center" prop="tagId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['FastGptExtUserTag:FastGptExtUserTag:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改处理新客标签对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签id" prop="tagId">
          <el-input v-model="form.tagId" placeholder="请输入标签id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量添加标签" :visible.sync="tagOpen" width="800px" append-to-body>
      <div>搜索标签：
        <el-input v-model="tagChange.tagName" placeholder="请输入标签名称" clearable size="small" style="width: 200px;margin-right: 10px" />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchTags(tagChange.tagName)">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="cancelSearchTags">重置</el-button>
      </div>
      <el-form ref="form" :model="addTagFormByWatch"  label-width="80px">
        <div v-for="item in tagGroupList" :key="item.id" >
          <div style="font-size: 20px;margin-top: 20px;margin-bottom: 20px;">
            <span class="name-background">{{ item.name }}</span>
          </div>
          <!-- 添加外层滚动容器 -->
          <div class="scroll-wrapper">
            <div class="tag-container">
              <a
                v-for="tagItem in item.tag"
                class="tag-box"
                @click="tagSelection(tagItem)"
                :class="{ 'tag-selected': tagItem.isSelected }"
              >
                {{ tagItem.name }}
              </a>
            </div>
          </div>
        </div>
      </el-form>
      <pagination
        v-show="tagTotal>0"
        :total="tagTotal"
        :page.sync="queryTagParams.pageNum"
        :limit.sync="queryTagParams.pageSize"
        @pagination="updateQwuser"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTagSubmitForm()">确 定</el-button>
        <el-button @click="addTagCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFastGptExtUserTag,addFastGptTagByCorpId,getMyQwUserList, getFastGptExtUserTag, delFastGptExtUserTag, addFastGptExtUserTag, updateFastGptExtUserTag, exportFastGptExtUserTag } from "@/api/fastGpt/FastGptExtUserTag";
import {allListTagGroup, getAllListTagGroup} from "@/api/qw/tagGroup";
import {searchTags} from "@/api/qw/tag";
export default {
  name: "FastGptExtUserTag",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 处理新客标签表格数据
      FastGptExtUserTagList: [],
      myQwUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tagOpen: false,
      queryTagParams: {
        pageNum: 1,
        pageSize: 5,
        total: 0,
        name: null,
        tagName: null,
        corpId: null,
      },
      //标签弹窗选择
      tagChange: {
        open: false,
        index: null,
      },
      addTagFormByWatch: {
        tagIds: [],
        corpId: null,
      },
      tagGroupList: [],
      showTagGroupList: [],
      tagTotal: 0,


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagId: null,
        tagIds: [],
        tagName: null,
        corpId: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    getMyQwUserList().then(response => {
      this.myQwUserList = response.data;
      // 如果myQwUserList不为空，默认选中第一个
      if (this.myQwUserList && this.myQwUserList.length > 0) {
        this.queryParams.corpId = this.myQwUserList[0].corpId;
        // 重新加载列表以显示选中企业的数据
        this.getList();
      }
    });
  },
  methods: {
    /** 查询处理新客标签列表 */
    getList() {
      this.loading = true;
      listFastGptExtUserTag(this.queryParams).then(response => {
        this.FastGptExtUserTagList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    addTagCancel() {
      this.addTagFormByWatch = {
        tagIds: [],
        corpId: null,
      };
      this.tagOpen = false;
      // 清除标签选择状态
      this.clearTagSelections();
    },
    handleSearchTags(name) {

      if (!name) {
        return this.$message.error("请输入要搜索的标签")
      }

      this.queryTagParams.name = name;
      this.queryTagParams.corpId = this.queryParams.corpId;

      searchTags(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.total = response.total;
      });


    },
    tagSelection(row) {
      row.isSelected = !row.isSelected;
      this.$forceUpdate();
    },
    cancelSearchTags() {
      this.resetSearchQueryTag()
    },
    resetSearchQueryTag() {

      this.queryTagParams = {
        pageNum: 1,
        pageSize: 5,
        total: 0,
        name: null,
      };
    },
    updateQwuser() {
      this.getList();
      this.queryTagParams.corpId = this.queryParams.corpId
      allListTagGroup(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.tagTotal = response.total;
      });
      getAllListTagGroup(this.queryTagParams).then(response => {
        this.showTagGroupList = response.rows;
      });
    },
    addTagSubmitForm() {

      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          if (this.tagGroupList[i].tag[x].isSelected == true) {
            this.addTagFormByWatch.tagIds.push(this.tagGroupList[i].tag[x].tagId)
          }
        }
      }
      if (this.addTagFormByWatch.tagIds == [] || this.addTagFormByWatch.tagIds == null || this.addTagFormByWatch.tagIds == "") {
        return this.$message('请选择标签');
      }

      if (this.queryParams.corpId == [] || this.queryParams.corpId == null || this.queryParams.corpId == "") {
        return this.$message('请选择企微账号');
      }


      let loadingRock = this.$loading({
        lock: true,
        text: '正在执行中请稍后~~请不要刷新页面！！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.addTagFormByWatch.corpId =  this.queryParams.corpId;

      addFastGptTagByCorpId(this.addTagFormByWatch).then(response => {
        this.tagOpen = false;
        loadingRock.close();
        this.addTagFormByWatch = {
          tagIds: [],
          corpId: null,
        };
        this.getList()
      }).finally(res => {
        loadingRock.close();
      });
      // 清除标签选择状态
      this.clearTagSelections();

    },
    // 清除所有标签的选中状态
    clearTagSelections() {
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          this.tagGroupList[i].tag[x].isSelected = false;
        }
      }
      this.$forceUpdate();
    },
    /** 根据tagId获取tagName */
    getTagNameById(tagId) {
      // 在tagList中查找匹配的标签
      for (let i = 0; i < this.showTagGroupList.length; i++) {
        for (let x = 0; x < this.showTagGroupList[i].tag.length; x++) {
          if (this.showTagGroupList[i].tag[x].tagId === tagId) {
           return this.showTagGroupList[i].tag[x].name;
          }
        }
      }
      // 如果找不到匹配的标签，返回空字符串
      return '';
    },

    // 取消按钮
    cancel() {
      //this.open = false;
      this.tagOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tagId: null,
        corpId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.queryParams.corpId == [] || this.queryParams.corpId == null || this.queryParams.corpId == "") {
        return this.$message('请选择企微账号');
      }
      // 清除标签选择状态
      this.clearTagSelections();
      this.tagOpen = true;
      this.title = "添加新客标签";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFastGptExtUserTag(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改处理新客标签";
      });
    },
    getCorpNameById(corpId) {
      if (!corpId) return '';
      const corp = this.myQwUserList.find(item => item.corpId === corpId);
      return corp ? corp.corpName : corpId;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFastGptExtUserTag(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFastGptExtUserTag(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除处理新客标签编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delFastGptExtUserTag(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有处理新客标签数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportFastGptExtUserTag(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
<style scoped>
/* CSS 样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap; /* 超出宽度时自动换行 */
  gap: 8px; /* 设置标签之间的间距 */
}

.name-background {
  display: inline-block;
  background-color: #abece6; /* 背景颜色 */
  padding: 4px 8px; /* 调整内边距，让背景包裹文字 */
  border-radius: 4px; /* 可选：设置圆角 */
}

/* CSS 样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap; /* 超出宽度时自动换行 */
  gap: 8px; /* 设置标签之间的间距 */
}

.name-background {
  display: inline-block;
  background-color: #abece6; /* 背景颜色 */
  padding: 4px 8px; /* 调整内边距，让背景包裹文字 */
  border-radius: 4px; /* 可选：设置圆角 */
}

.tag-box {
  padding: 8px 12px;
  border: 1px solid #989797;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.tag-selected {
  background-color: #00bc98;
  color: #fff;
  border-color: #00bc98;
}

.el-tag + .el-tag {
  margin-left: 10px;
}


.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

/* 新增的滚动容器样式（不影响原有样式） */
.scroll-wrapper {
  max-height: 130px; /* 大约三行的高度 */
  overflow-y: auto; /* 垂直滚动 */
  padding-right: 5px; /* 为滚动条留出空间 */
}

/* 美化滚动条（可选） */
.scroll-wrapper::-webkit-scrollbar {
  width: 6px;
}

.scroll-wrapper::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}
</style>
