<template>
  <div class="app-container">
    <el-tabs v-model="activeName" style="background-color: #fff;" @tab-click="handleClick" type="card">
<!--      <el-tab-pane label="关键词打标签" name="1"></el-tab-pane>-->
      <el-tab-pane label="客户入群行为打标签" name="2"></el-tab-pane>
      <el-tab-pane label="分时段打标签" name="3"></el-tab-pane>
    </el-tabs>

    <div >
      <div v-if="activeName==='1'">
        <keyWordIndex></keyWordIndex>
      </div>
      <div v-if="activeName==='2'" >

        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="企微公司" prop="corpId">
                <el-select v-model="queryParams.corpId" placeholder="企微公司"  size="small" @change="updateCorpId()">
                  <el-option
                    v-for="dict in myQwCompanyList"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
          </el-form-item>
          <el-form-item label="规则名称:" prop="ruleName">
            <el-input
              v-model="queryParams.ruleName"
              placeholder="请输入规则名称"
              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-button
              type="primary"
              size="mini"
              plain
              icon="el-icon-plus"
              @click="handleAdd"
              v-hasPermi="['qw:autoTags:add']"
            >添加规则</el-button>
          </el-form-item>

        </el-form>
<!--        <div style="padding:0 0 15px 0">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            size="small"-->
<!--            plain-->
<!--            icon="el-icon-plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['shop:tags:add']"-->
<!--          >添加规则</el-button>-->
<!--        </div>-->

        <el-table v-loading="loading" :data="groupIndexList" border  height="550px">
          <el-table-column label="规则名称" align="center" prop="ruleName" />
          <el-table-column label="添加的标签" align="center" prop="tagIdsName" width="300px">
            <template slot-scope="scope">
              <div v-for="name in scope.row.tagIdsName" style="display: inline;">
                <el-tag type="success">{{ name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已打标签总数" align="center" prop="totalNumTagsCount" />
          <el-table-column label="规则状态" align="center" prop="isApply">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isApply"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="2"
                @change="switchChange(scope.row)">
              </el-switch>
              <span v-if="scope.row.isApply == '1'" style="margin-left: 10px;color: #13ce66">已启用</span>
              <span v-if="scope.row.isApply == '2'" style="margin-left: 10px;color: #ff4949">已关闭</span>
            </template>
          </el-table-column>
          <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="handleDetails(scope.row)"
                v-hasPermi="['qw:autoTags:query']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['qw:autoTags: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"
        />

      </div>
      <div v-if="activeName==='3'">
        <dayPartingIndex></dayPartingIndex>
      </div>


      <!-- 添加或修改自动打标签主对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>

        <el-form  ref="form" :model="form" :rules="rules" label-position="left"  label-width="120px">
          <div class="app-container">
            <div>
              <span style="font-size: 15px">规则基础信息</span>
              <el-divider></el-divider>
            </div>
            <el-alert
              title="设定规则，当用户加入规则内的群聊，自动给入群客户打标签"
              type="warning"
              style="font-size: 15px;margin-bottom: 2%;"
              :closable="false"
              show-icon>
            </el-alert>
            <el-form-item label="规则名称:" prop="ruleName" style="width: 400px">
              <el-input v-model="form.ruleName" placeholder="请输入规则名称(内部可见)" />
            </el-form-item>

            <div style="margin-top: 5%">
              <span style="font-size: 15px">设置打标签的规则</span>
              <el-divider></el-divider>
            </div>
            <div v-for="(item, index) in form.rulesTags" :key="index">
              <div style="background-color: #fbfbfb; padding: 10px; border: 1px solid #e6e6e6; margin-bottom: 20px;">
                <el-form ref="rulesTagsFrom" :rules="rulesTagsRules" :model="item">
                  <div style="display: flex">
                    <el-form-item prop="rules" style="width: 500px">
                      <div style="display: flex; align-items: center;">
                        <div style="width: 150px">
                          <span style="margin-right: 10px;">规则 {{ index + 1 }}：用户加入群聊</span>
                        </div>
                        <div @click="handleGroupChatList(item,index)" style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 350px">
                          <div style="min-height: 40px; max-height: 200px; overflow-y: auto;">
                            <el-tag
                              style="margin-left: 5px"
                              size="medium"
                              :key="list.chatId"
                              v-for="list in groupChatList[index]"
                              closable
                              :disable-transitions="false"
                              @close="handleClosegroupChat(list,index)">
                              {{list.name}}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                    <el-form-item prop="tags" style="width: 500px">
                      <div style="display: flex; align-items: center;">
                        <div style="width: 110px">
                          <span style="margin:0px 10px;">选择的标签：</span>
                        </div>
                        <div @click="handleChangeTags(item,index)" style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 390px">
                          <div style="min-height: 40px; max-height: 200px; overflow-y: auto;">
                            <el-tag type="success"
                                    closable
                                    :disable-transitions="false"
                                    v-for="list in tagListFormIndex[index]"
                                    :key="list.tagId"
                                    @close="handleCloseTag(list,index)"
                                    style="margin: 3px;"
                                   >{{list.name}}
                            </el-tag>
                          </div>
                        </div>

                      </div>
                    </el-form-item>
                    <el-link v-if="form.rulesTags.length>1" icon="el-icon-delete-solid" @click="delItemList(index)" type="text" style="color: rgb(24, 144, 255);margin-left:10px;height: 40px " ></el-link>
                  </div>
                </el-form>
              </div>
            </div>
            <div>
              <el-link type="primary" class="el-icon-plus" :underline="false" @click='addItemList()'>添加其他规则(最多5条)</el-link>
            </div>

          </div>
        </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>
    </div>

    <!-- 选择群聊    -->
    <el-dialog :title="groupChart.title" :visible.sync="groupChart.open" style="width: 1300px;height: 100%" append-to-body>
      <GroupChat ref="GroupChat" @selectGroupChatList="selectGroupChatList" :index="groupChart.index"></GroupChat>
    </el-dialog>


    <el-dialog title="添加标签" :visible.sync="tagChange.open" width="800px" append-to-body>
      <div>搜索标签：
        <el-input v-model="queryTagParams.name" placeholder="请输入标签名称" clearable size="small" style="width: 200px;margin-right: 10px" />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchTags">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="cancelSearchTags">重置</el-button>
      </div>
      <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>
      <pagination
        v-show="tagTotal>0"
        :total="tagTotal"
        :page.sync="queryTagParams.pageNum"
        :limit.sync="queryTagParams.pageSize"
        @pagination="getPageListTagGroup"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTagSubmitForm(tagChange.index)">确 定</el-button>
        <el-button @click="addTagCancel(tagChange.index)">重 置</el-button>
      </div>
    </el-dialog>

    <!-- 群规则详情    -->
    <el-drawer :title="detailFrom.title" :visible.sync="detailFrom.open" size="75%" style="font-weight: bolder">
        <groupIndexDetails :groupIndexFrom="detailListFrom"></groupIndexDetails>
    </el-drawer>

  </div>

</template>

<script>
import { listTags, getTags, delTags, addTags, updateTags, exportTags } from "@/api/qw/autoTags";
import qwUserList from '@/views/qw/user/qwUserList.vue'
import dayPartingIndex from '@/views/qw/autoTags/dayPartingIndex.vue'
import keyWordIndex from '@/views/qw/autoTags/keyWordIndex.vue'
import GroupChat from '@/views/qw/autoTags/groupChat.vue'
import { allListTagGroup } from '@/api/qw/tagGroup'
import {listTag, searchTags} from '@/api/qw/tag'
import groupIndexDetails from '@/views/qw/autoTags/groupIndexDetails.vue'
import { getMyQwUserList,getMyQwCompanyList } from "@/api/qw/user";
export default {
  name: "autoTags",
  components: {GroupChat, qwUserList,dayPartingIndex,keyWordIndex,groupIndexDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      activeName:'2',
      myQwCompanyList:[],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tagTotal:0,
      // 自动打标签主表格数据
      groupIndexList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //选择群聊
      groupChart:{
        title:"",
        open:false,
        index:null,
      },

      //选择的群聊
      groupChatList:[],

      //所有的标签组-标签
      tagGroupList:[],

      //所有的标签
      // tagList:[],

      //选择的标签
      tagListFormIndex:[],

      //标签弹窗选择
      tagChange:{
        open:false,
        index:null,
      },
      //详情抽屉
      detailFrom:{
        open:false,
        title:'',
      },

      queryTagParams: {
        pageNum: 1,
        pageSize: 5,
        total:0,
        name:null,
        corpId:null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 2,
        createName: null,
        applyUsers: null,
        ruleName: null,
        rulesTags: null,
        totalNumTags: null,
        numTagsTaday: null,
        isApply: null,
        corpId: null,
        companyId: null
      },
      // 表单参数
      form: {},
      //详情表单参数
      detailListFrom:{},
      // 表单校验
      rules: {
        ruleName:[{ required: true, message: "规则名称不能为空", trigger: "submit" }],
      },
      //规则验证
      rulesTagsRules:{
        rules: [
          { required: true, message: '请添加群', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    //所有的标签组-标签

    getMyQwCompanyList().then(response => {
            this.myQwCompanyList = response.data;
            if(this.myQwCompanyList!=null){
              this.queryParams.corpId=this.myQwCompanyList[0].dictValue;

              this.afreshData(this.queryParams.corpId)
              this.getList();

            }
    });
  },
  watch: {
    groupChatList: {
      handler(newList) {
        // 遍历 groupChatList 并将 chatId 放入对应位置的 rulesTags
        newList.forEach((group, index) => {
          if (!this.form.rulesTags[index]) {
            this.$set(this.form.rulesTags, index, { rules: [], tags: [] });
          }
          // 确保清空原来的 tags 数组
          this.form.rulesTags[index].rules = [];
          group.forEach(item => {
            // 将 chatId 放入对应位置的 rulesTags 中的 rules 数组
            this.form.rulesTags[index].rules.push(item.chatId);
          });
        });
      },
      deep: true
    },
    tagListFormIndex: {
      handler(newList) {
        // 遍历 tagListFormIndex 并将 tagId 放入对应位置的 tags
        newList.forEach((tags, index) => {
          if (!this.form.rulesTags[index]) {
            this.$set(this.form.rulesTags, index, { rules: [], tags: [] });
          }

          // 确保清空原来的 tags 数组
          this.form.rulesTags[index].tags = [];

          tags.forEach(item => {
            // 将 tagId 放入对应位置的 rulesTags 中的 tags 数组
            this.form.rulesTags[index].tags.push(item.tagId);
          });
        });
      },
      deep: true
    }
  },

  methods: {
    updateCorpId(){
      this.afreshData(this.queryParams.corpId)
      this.getList();
     },

    /**
     * 重新获取 部分数据
     */
    afreshData(value){

      this.resetSearchQueryTag()
      this.queryTagParams.corpId=value;

    },

    resetSearchQueryTag(){

      this.queryTagParams= {
        pageNum: 1,
        pageSize: 5,
        total:0,
        name:null,
      };
    },

    //选择的标签页
    handleClick(tab, event) {
      this.queryParams.type=tab.name
      this.getList();
    },
    //选择群聊弹窗
    handleGroupChatList(item,index){
      this.groupChart.title="选择群聊"
        setTimeout(() => {
                  this.$refs.GroupChat.getDetails(this.queryParams.corpId);
             }, 1);
      this.groupChart.open=true;
      this.groupChart.index=index
    },

    //选择群聊赋值
    selectGroupChatList(list,index){

      this.groupChart.open=false;

      // 如果 this.groupChatList[index] 不存在，则初始化为一个空数组
      if (!this.groupChatList[index]) {
        this.$set(this.groupChatList, index, []);
      }

      // 获取当前 groupChatList[index] 中的值
      let currentList = this.groupChatList[index];

      // 遍历 list 中的每个值
      list.forEach(item => {
        let itemIndex = currentList.findIndex(currentItem => currentItem.chatId === item.chatId);

        if (itemIndex !== -1) {
          // 如果当前 item 在 currentList 中已经存在，则不管
        } else {
          // 如果当前 item 不在 currentList 中，则插入
          currentList.push(item);
        }
      });

      // 更新 groupChatList[index]
      this.$set(this.groupChatList, index, currentList);
    },

    //删除一些选择了的群聊
    handleClosegroupChat(list,index){

      // 假设 list 对象具有一个 id 属性
      const ls = this.groupChatList[index].findIndex(t => t.chatId === list.chatId);
      if (ls !== -1) {
        this.groupChatList[index].splice(ls, 1);
      }
    },

    //选择标签弹窗
    handleChangeTags(item,index){

      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.tagChange.open=true;
      this.tagChange.index=index;

    },

    handleSearchTags(){

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

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

    },

    getPageListTagGroup(){

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

      allListTagGroup(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.tagTotal = response.total;
      });
    },


    cancelSearchTags(){
      this.afreshData(this.queryParams.corpId)
    },
    //标签的选择
    tagSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },

    //选择标签
    addTagSubmitForm(index){

      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) {
            if (!this.tagListFormIndex[index]) {
              this.$set(this.tagListFormIndex, index, []);
            }

            // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
            let tagExists = this.tagListFormIndex[index].some(
              tag => tag.id === this.tagGroupList[i].tag[x].id
            );

            // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
            if (!tagExists) {
              this.tagListFormIndex[index].push(this.tagGroupList[i].tag[x]);
            }
          }
        }
      }
      if (!this.tagListFormIndex[index] || this.tagListFormIndex[index].length === 0) {
        return this.$message('请选择标签');
      }

      this.tagChange.open = false;
    },

    //取消选择标签
    addTagCancel(index){
      this.tagChange.open = false;
      this.tagListFormIndex[index]=[];
    },
    //删除一些已经选择了的标签
    handleCloseTag(list,index){

      // 假设 list 对象具有一个 id 属性
      const ls = this.tagListFormIndex[index].findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.tagListFormIndex[index].splice(ls, 1);
        // 使用 Vue.set 方法
        this.$set(this.tagListFormIndex, index, [...this.tagListFormIndex[index]]);
      }
    },

    //删除某一个规则
    delItemList(index){
      this.form.rulesTags.splice(index,1)
      this.tagListFormIndex.splice(index,1)
      this.groupChatList.splice(index,1)
    },

    //添加规则
    addItemList(){
      if (this.form.rulesTags.length >=5) {
        return this.$message.error('当前规则已达上限，无法添加规则');
      }
      this.form.rulesTags.push({rules:[],tags:[]})
    },


    /** 查询自动打标签主列表 */
    getList() {
      this.loading = true;
      listTags(this.queryParams).then(response => {

        this.groupIndexList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: 2,
        createName: null,
        applyUsers: null,
        ruleName: null,
        rulesTags: [{rules:[],tags:[]}],
        totalNumTags: null,
        numTagsTaday: null,
        isApply: 1,
        createTime: null,
        companyId: null
      };
      //选择的群
      this.groupChatList=[];

      //选择的标签
      this.tagListFormIndex=[];

      //规则
      this.form.rulesTags=[{rules:[],tags:[]}];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId= this.myQwCompanyList[0].dictValue
      this.afreshData(this.queryParams.corpId)
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规则";


      this.getPageListTagGroup();

      //所有的标签
      listTag({corpId:this.queryParams.corpId}).then(response => {
        this.tagList = response.rows;
      });

    },
    handleAddThree(){

    },

    /** 详情按钮操作 */
    handleDetails(row) {

      this.reset();

      // 深拷贝表单数据
      const requestData = { ...row };
      // 将 `数据` 转为 JSON
      requestData.rulesTags = JSON.parse(row.rulesTags);

      this.detailListFrom = requestData;
      this.detailFrom.open=true;
      this.detailFrom.title='规则详情';


    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.corpId=this.queryParams.corpId;
          const itemForms = this.$refs.rulesTagsFrom;
          if (Array.isArray(itemForms)) {
            let allValid = true;

            itemForms.forEach((itemFormRef, index) => {
              itemFormRef.validate((itemValid) => {
                allValid = itemValid;

                if (index === itemForms.length - 1 && allValid) {
                  //全表单验证通过
                  this.commitForm();
                }
              });
            });
          }
        }


      });

    },

    //提交form表单
    commitForm(){

      // 深拷贝表单数据
      const requestData = { ...this.form };
      // 将 `form.rulesTags` 转为 JSON 字符串
      requestData.rulesTags = JSON.stringify(this.form.rulesTags);
        requestData.corpId=this.queryParams.corpId;
      if (this.form.id != null) {
        updateTags(requestData).then(response => {
          this.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addTags(requestData).then(response => {
          this.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },

    //状态开关
    switchChange(row){
      updateTags(row).then(response => {
        this.msgSuccess("修改成功");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除自动打标签规则名称为【' + row.ruleName + '】的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTags(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).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; /* 可选：设置圆角 */
}
.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;
}
.text-container {
  max-height: 5em; /* 设置最大高度为6行，根据字体大小调整 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  line-height: 1.5em; /* 行高设置，确保每行高度一致 */
}
/* 新增的滚动容器样式（不影响原有样式） */
.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>
