<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" style="border: 1px solid transparent">
      <el-form-item label="销售公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="销售公司"  size="small" @change="getAllUserlist(queryParams.companyId)">
          <el-option
              v-for="dict in qwCompanyList"
              :key="dict.companyId"
              :label="dict.companyName"
              :value="dict.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售账号" prop="companyUserName">
        <el-select v-model="queryParams.companyUserName" placeholder="销售账号"  size="small" clearable>
          <el-option
              v-for="dict in companyUserNameList"
              :key="dict.userId"
              :label="dict.userName"
              :value="dict.userName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企微微信" prop="companyUserName">
        <el-select v-model="queryParams.qwUserId" placeholder="企微微信"  size="small" clearable>
          <el-option
              v-for="dict in qwUserList"
              :key="dict.id"
              :label="dict.qwUserName"
              :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户会员id" prop="fsUserId">
        <el-input
          v-model="queryParams.fsUserId"
          placeholder="请输入客户会员id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="企微客户id" prop="extId">
        <el-input
          v-model="queryParams.extId"
          placeholder="请输入客户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="客户名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="销售企微昵称" prop="qwUserName">
        <el-input
            v-model="queryParams.qwUserName"
            placeholder="请输入销售企微昵称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择用户类别" clearable size="small">
          <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="状态" clearable size="small">
          <el-option
              v-for="dict in genderOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="level">
        <el-select v-model="queryParams.level" placeholder="客户等级" clearable size="small">
          <el-option
              v-for="dict in ratingType"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="等级升降" prop="levelType">
        <el-select v-model="queryParams.levelType" placeholder="等级升降" clearable size="small">
          <el-option
              v-for="dict in ratingUpFall"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="电话号码" prop="remarkMobiles">
        <el-input
            v-model="queryParams.remarkMobiles"
            placeholder="请输入备注电话号码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="来源" prop="addWay">

        <el-select v-model="queryParams.addWay" placeholder="来源" clearable size="small">
          <el-option
              v-for="dict in addWayOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">

        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="转接状态" prop="addWay">

        <el-select v-model="queryParams.transferStatus" placeholder="转接状态" clearable size="small">
          <el-option
              v-for="dict in transferStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否绑定会员" prop="isBindMini">
        <el-select v-model="queryParams.isBindMini" placeholder="是否绑定会员" clearable size="small" @change="handleQuery" >
          <el-option
              v-for="dict in isBindMiniOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tagIds">
        <div @click="hangleChangeTags()" style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 250px">
          <div style="min-height: 35px; max-height: 200px; overflow-y: auto;">
            <el-tag type="success"
                    closable
                    :disable-transitions="false"
                    v-for="list in this.selectTags"
                    :key="list.tagId"
                    @close="handleCloseTags(list)"
                    style="margin: 3px;"
            >{{list.name}}
            </el-tag>
          </div>
        </div>


      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属销售" prop="companyUser">
        <el-input
            v-model="queryParams.companyUser"
            placeholder="请输入昵称或者手机号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="添加时间">
        <el-date-picker v-model="daterange" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>




      <el-form-item label="流失时间" prop="lossTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.lossTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择流失时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="删除时间" prop="delTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.delTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择删除时间">
        </el-date-picker>
      </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="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          :loading="exportLoading"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['qw:externalContact:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          :loading="exportUnionidLoading"-->
<!--          @click="handleExportUnionId"-->
<!--          v-hasPermi="['qw:externalContact:export']"-->
<!--        >导出unionid</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="externalContactList" @selection-change="handleSelectionChange" border>
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="企微客户ID"  align="center" prop="id" />
    <el-table-column label="客户会员ID"  align="center" prop="fsUserId" />
    <el-table-column label="企微客户头像" align="center" prop="avatar" width="100px">
      <template slot-scope="scope">
        <el-popover
            placement="right"
            title=""
            trigger="hover">
          <img slot="reference" :src="scope.row.avatar" width="60px">
          <img :src="scope.row.avatar" style="max-width: 200px;">
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="企微客户名称"  prop="name" width="110px"/>
    <el-table-column label="销售企微昵称" align="center" prop="qwUserName" width="120px"/>
    <el-table-column label="企微部门" align="center" prop="departmentName" width="120px"/>
    <el-table-column label="用户类别" align="center" prop="type">
      <template slot-scope="scope">
        <dict-tag :options="typeOptions" :value="scope.row.type"/>
      </template>
    </el-table-column>
    <el-table-column label="性别" align="center" prop="gender">
      <template slot-scope="scope">
        <dict-tag :options="genderOptions" :value="scope.row.gender"/>
      </template>
    </el-table-column>
    <el-table-column label="备注" align="center" prop="remark" />
    <el-table-column label="描述信息" align="center" prop="description" />
    <el-table-column label="标签" align="center" prop="tagIdsName" width="250px">
      <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="status" width="120px" >
      <template slot-scope="scope">
        <dict-tag :options="statusOptions" :value="scope.row.status"/>
      </template>
    </el-table-column>
    <el-table-column label="客户等级" align="center" prop="level" width="120px" >
      <template slot-scope="scope">
        <dict-tag :options="ratingType" :value="scope.row.level"/>
      </template>
    </el-table-column>
    <el-table-column label="等级状态" align="center" prop="levelType" width="120px" >
      <template slot-scope="scope">
        <dict-tag :options="ratingUpFall" :value="scope.row.levelType"/>
      </template>
    </el-table-column>

    <el-table-column label="添加时间" align="center" prop="createTime" width="100px" />
    <el-table-column label="流失时间" align="center" prop="lossTime" width="100px" />
    <el-table-column label="删除时间" align="center" prop="delTime" width="100px" />
    <el-table-column label="备注电话号码" align="center" prop="remarkMobiles" width="150px">
      <template slot-scope="scope">
        <div v-for="i in JSON.parse(scope.row.remarkMobiles)" :key="i">{{i}}</div>
      </template>
    </el-table-column>
    <el-table-column label="备注企业名称" align="center" prop="remarkCorpName" />
    <el-table-column label="来源" align="center" prop="addWay" width="100px">
      <template slot-scope="scope">
        <dict-tag :options="addWayOptions" :value="scope.row.addWay"/>
      </template>
    </el-table-column>

    <el-table-column label="转接状态" align="center" prop="transferStatus" width="100px" >
      <template slot-scope="scope">
        <dict-tag :options="transferStatusOptions" :value="scope.row.transferStatus"/>
      </template>
    </el-table-column>
    <el-table-column label="企业id" align="center" prop="corpId" />
    <el-table-column label="是否绑定会员" width="100px" align="center" fixed="right">
      <template slot-scope="scope">
        <el-tag v-if="scope.row.fsUserId" >已绑定</el-tag>
        <el-tag v-else type="info"> 未绑定</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="修改" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">
      <template slot-scope="scope">
<!--        <el-button-->
<!--            v-if="scope.row.status==0||scope.row.status==2"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['qw:externalContact:edit']"-->
<!--        >修改备注</el-button>-->
<!--        <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-user-solid"-->
<!--            @click="handleAppellation(scope.row)"-->
<!--        >修改客户称呼</el-button>-->
<!--      </template>-->
<!--    </el-table-column>-->
<!--    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">-->
<!--      <template slot-scope="scope">-->
<!--        <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit-outline"-->
<!--            @click="handleUpdateUser(scope.row)"-->
<!--        >-->
<!--          <span v-if="scope.row.fsUserId">换绑会员</span>-->
<!--          <span v-else>绑定会员</span>-->
<!--        </el-button>-->

<!--        <el-button-->
<!--            v-if="scope.row.fsUserId"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-thumb"-->
<!--            @click="handleUnBindUserId(scope.row)"-->
<!--            v-hasPermi="['qw:externalContact:unBindUserId']"-->
<!--        >-->
<!--          <span>解除会员绑定</span>-->
<!--        </el-button>-->
        <el-button
            size="mini"
            type="text"
            @click="handledetails(scope.row)"
        >AI获取用户信息
        </el-button>
      </template>
    </el-table-column>
    </el-table>

    <pagination-more
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
    <!--  搜索标签   -->
    <el-dialog :title="changeTagDialog.title" :visible.sync="changeTagDialog.open" style="width:100%;height: 100%" 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(queryTagParams.name)">搜索</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="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>

      <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="tagSubmitForm()">确 定</el-button>
        <el-button @click="tagCancel()">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="info.title" :visible.sync="info.open"   width="1100px" append-to-body>
      <externalContactInfo  ref="Details" />
    </el-dialog>

  </div>
</template>

<script>
import { listExternalContact, getExternalContact, delExternalContact, addExternalContact, updateExternalContact, exportExternalContact, exportUnionId } from "@/api/qw/externalContact";
import {getCompanyList} from "@/api/company/company";
import {getAllUserlist} from "@/api/company/companyUser";
import {getQwUserInfo} from "@/api/qw/qwUser";
import { allListTagGroup} from "@/api/qw/tagGroup";
import {searchTags,} from "@/api/qw/tag";
import PaginationMore from '@/components/PaginationMore/index.vue'
import externalContactInfo from "../externalContact/info";

export default {
  name: "ExternalContact",
  components: { PaginationMore,externalContactInfo },
  data() {
    return {
      daterange: [],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      exportUnionidLoading: false,
      //等级状态
      ratingUpFall: [],
      // 性别字典
      genderOptions: [],
      // 用户类别字典
      typeOptions: [],
      //状态
      statusOptions:[],
      //客户等级
      ratingType: [],
      // 来源字典
      addWayOptions: [],
      //转接状态
      transferStatusOptions:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业微信客户表格数据
      externalContactList: [],
      //销售员工数据
      companyUserNameList:[],
      //企微用户信息数据
      qwUserList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      info:{
        title:"用户信息",
        open:false,
      },
      //标签
      tagGroupList: [],
      // 查询参数
      queryParams: {
        extId:null,
        companyUser:null,
        pageNum: 1,
        pageSize: 10,
        qwUserName:null,
        userId: null,
        externalUserId: null,
        name: null,
        avatar: null,
        type: null,
        gender: null,
        description: null,
        tagIds: null,
        remarkMobiles: null,
        remarkCorpName: null,
        addWay: null,
        operUserid: null,
        corpId: null,
        companyId: null,
        companyUserId: null,
        qwUserId: null,
        customerId: null,
        transferStatus: null,
        status: null,
        stageStatus: null,
        transferTime: null,
        transferNum: null,
        lossTime: null,
        delTime: null,
        state: null,
        wayId: null,
        fsUserId: null,
        openId: null,
        unionid: null,
        uploadAddWxStatus: null,
        uploadRegisterStatus: null,
        uploadFinishedStatus: null,
        welcomeStatus: null,
        isInteract: null,
        level: null,
        companyUserName:null,
        levelType: null,
        firstTime: null,
        lastWatchTime: null,
        isRepeat: null,
        commentStatus: null,
        isBindMini:null,
        sTime:null,
        eTime:null,
      },
      //标签
      changeTagDialog:{
        title:"",
        open:false,
      },
      selectTags:[],
      tagTotal:0,
      queryTagParams:{
        pageNum: 1,
        pageSize: 10,
        total:0,
        name:null,
        corpId:null,
      },
      isBindMiniOptions:[
        {dictLabel:"已绑定",dictValue:'isBindMini'},
        {dictLabel:"未绑定",dictValue:'noBindMini'},
      ],
      qwCompanyList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    //用户类别
    this.getDicts("sys_qw_externalContact_type").then(response => {
      this.typeOptions = response.data;
    });

    //客户等级
    this.getDicts("sys_qw_sop_rating_type").then(response => {
      this.ratingType = response.data;
    });

    //等级状态
    this.getDicts("sys_qw_sop_rating_upFall").then(response => {
      this.ratingUpFall = response.data;
    });

    //性别
    this.getDicts("sys_sex").then(response => {
      this.genderOptions = response.data;
    });

    //状态
    this.getDicts("sys_qw_external_contact_status").then(response => {
      this.statusOptions = response.data;
    });

    //来源
    this.getDicts("sys_qw_externalContact_addWay").then(response => {
      this.addWayOptions = response.data;
    });

    //转接状态
    this.getDicts("sys_qw_transfer_status").then(response => {
      this.transferStatusOptions = response.data;
    });

    //获取企业
    getCompanyList().then(response => {
      this.qwCompanyList = response.data;
      if(this.qwCompanyList!=null){
        this.queryParams.companyId=this.qwCompanyList[0].companyId;
        this.getAllUserlist(this.queryParams.companyId);
      }
    });
  },
  methods: {
    handledetails(row){
      this.info.open=true;
      setTimeout(() => {
        this.$refs.Details.getDetails(row.id);
      }, 1);
    },

    /** 获取销售账号列表 **/
    getAllUserlist(companyId){
      if(companyId){
        this.getList();
        getAllUserlist({companyId}).then(response => {
          this.companyUserNameList=response.data;
        });
        //企业微信
        getQwUserInfo({companyId}).then(response => {
          this.qwUserList=response.data;
        })
      }
    },
    tagSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },
    /** 查询企业微信客户列表 */
    getList() {
      this.loading = true;
      if(this.daterange!=null){
        this.queryParams.sTime=this.daterange[0];
        this.queryParams.eTime=this.daterange[1];
      }else{
        this.queryParams.sTime=null;
        this.queryParams.eTime=null;
      }
      listExternalContact(this.queryParams).then(response => {
        this.externalContactList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extId:null,
        userId: null,
        externalUserId: null,
        name: null,
        avatar: null,
        type: null,
        gender: null,
        remark: null,
        description: null,
        tagIds: null,
        remarkMobiles: null,
        remarkCorpName: null,
        addWay: null,
        operUserid: null,
        corpId: null,
        companyId: null,
        companyUserId: null,
        qwUserId: null,
        customerId: null,
        transferStatus: 0,
        status: 0,
        stageStatus: "0",
        createBy: null,
        updateBy: null,
        updateTime: null,
        transferTime: null,
        transferNum: null,
        lossTime: null,
        delTime: null,
        state: null,
        wayId: null,
        fsUserId: null,
        openId: null,
        unionid: null,
        uploadAddWxStatus: 0,
        uploadRegisterStatus: 0,
        uploadFinishedStatus: 0,
        welcomeStatus: 0,
        isInteract: null,
        level: null,
        levelType: null,
        firstTime: null,
        lastWatchTime: null,
        isRepeat: null,
        commentStatus: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      //验证是否选择企业
      if(!this.queryParams.companyId){
        return this.$message.warning({
          message: "请先选择企业！",
          duration: 3000
        })
      }

      if (this.selectTags!=null && this.selectTags.length>0){
        // 确保 this.form.tags 是数组
        if (!this.queryParams.tagIds) {
          this.queryParams.tagIds = []; // 如果未定义，初始化
        } else {
          this.queryParams.tagIds = []; // 清空已有数据
        }

        // 遍历并添加 tagId
        this.selectTags.forEach(tag => {
          if (tag.tagId) { // 确保 tagId 存在
            this.queryParams.tagIds.push(tag.tagId);
          }
        });
        this.queryParams.tagIds=this.queryParams.tagIds.join(",");
      }else {
        this.queryParams.tagIds=null;
      }

      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId= this.qwCompanyList[0].dictValue;
      this.selectTags=[];
      this.queryParams.qwUserId = null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.externalContactList=[];
      this.daterange=[];
      if(this.qwCompanyList!=null){
        this.queryParams.companyId=this.qwCompanyList[0].companyId;
        this.getAllUserlist(this.queryParams.companyId);
      }
    },
    handleSearchTags(name){

      searchTags({name:name,corpId:this.queryParams.corpId}).then(response => {
        this.tagGroupList = response.rows;
      });

    },
    cancelSearchTags(){
      this.resetSearchQueryTag()

      this.getPageListTagGroup();
    },
    resetSearchQueryTag(){

      this.queryTagParams= {
        pageNum: 1,
        pageSize: 10,
        total:0,
        name:null,
      };
    },
    //确定选择标签
    tagSubmitForm(){


      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.selectTags) {
              this.selectTags = [];
            }
            // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
            let tagExists = this.selectTags.some(
                tag => tag.id === this.tagGroupList[i].tag[x].id
            );

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

      this.changeTagDialog.open = false;
    },
    getPageListTagGroup(){
      this.queryTagParams.corpId=this.queryParams.corpId
      allListTagGroup(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.tagTotal = response.total;
      });
    },
    //取消选择标签
    tagCancel(){
      this.changeTagDialog.open = false;
    },
    //删除一些选择的标签
    handleCloseTags(list){
      const ls = this.selectTags.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.selectTags.splice(ls, 1);
        this.selectTags = [...this.selectTags];
      }

      if (this.selectTags!=null && this.selectTags.length>0){
        // 确保 this.form.tags 是数组
        if (!this.queryParams.tagIds) {
          this.queryParams.tagIds = []; // 如果未定义，初始化
        } else {
          this.queryParams.tagIds = []; // 清空已有数据
        }

        // 遍历并添加 tagId
        this.selectTags.forEach(tag => {
          if (tag.tagId) { // 确保 tagId 存在
            this.queryParams.tagIds.push(tag.tagId);
          }
        });
        this.queryParams.tagIds=this.queryParams.tagIds.join(",");
      }else {
        this.queryParams.tagIds=null;
      }

    },
    //搜索的标签
    hangleChangeTags(){

      this.changeTagDialog.title="搜索的标签"
      this.changeTagDialog.open=true;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(
          (this.selectTags || []).map(tagItem => tagItem?.tagId)
      );

      this.queryTagParams.name=null;

      this.getPageListTagGroup();

      setTimeout(() => {
        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 = selectedTagIds.has(this.tagGroupList[i].tag[x].tagId);
          }
        }
      }, 200);


    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业微信客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExternalContact(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业微信客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExternalContact(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExternalContact(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 delExternalContact(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      //验证是否选择企业
      if(!this.queryParams.companyId){
        return this.$message.warning({
          message: "请先选择企业！",
          duration: 3000
        })
      }
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业微信客户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportExternalContact(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 导出Unionid按钮操作 */
    handleExportUnionId() {
      //验证是否选择企业
      if(!this.queryParams.companyId){
        return this.$message.warning({
          message: "请先选择企业！",
          duration: 3000
        })
      }
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业微信客户unionid数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportUnionidLoading = true;
          return exportUnionId(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportUnionidLoading = 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;
}
</style>
