<template>
  <div>
    <div class="app-container">
    </div>
    <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="请选择企微公司"  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="AI客服" prop="aiCustomerRoleId">
          <el-select
            v-model="queryParams.aiCustomerRoleId"
            placeholder="请选择AI客服角色"
            clearable
            size="small"
            @keyup.enter.native="handleQuery">
            <el-option
              v-for="item in aiCustomerRoleOptions"
              :key="item.id"
              :label="item.callRoleName"
              :value="item.id">
            </el-option>
          </el-select>
        </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" @click="handleAdd()" v-hasPermi="['qw:groupVoiceMsg:add']">新建群呼</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="groupMsgList" @selection-change="handleSelectionChange" border>
        <el-table-column label="AI外呼客服" align="left" prop="aiCallRoleName"/>
        <el-table-column label="任务类型" align="center" prop="chatType">
          <template slot-scope="scope">
            <span v-if="scope.row.chatType === 1">AI外呼群发</span>
            <span v-else-if="scope.row.chatType === 2">手动</span>
            <span v-else-if="scope.row.chatType === 3">sop模板提醒</span>
            <span v-else-if="scope.row.chatType === 4">新客对话</span>
            <span v-else-if="scope.row.chatType === 5">sop任务</span>
            <span v-else>{{scope.row.chatType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="呼叫时效" align="center" prop="isTimerSend">
          <template slot-scope="scope">
            <span v-if="scope.row.isTimerSend === 1">定时呼叫</span>
            <span v-else-if="scope.row.isTimerSend === 2">立即呼叫</span>
            <span v-else>{{scope.row.isTimerSend}}</span>
          </template>
        </el-table-column>
        <el-table-column label="呼叫时间" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isTimerSend===2">{{scope.row.createTime}}</span>
            <span v-else>{{ scope.row.timerSend }}</span>
          </template>
        </el-table-column>


        <el-table-column label="呼叫状态" align="center"  width="110px">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.isSend===1"
              type="success"
              size="mini"
              plain>
              呼叫成功
            </el-tag >
            <el-tag
              v-else-if="scope.row.isSend===0"
              type="danger"
              size="mini"
              plain>
              呼叫失败
            </el-tag >
            <el-tag
              v-else-if="scope.row.isSend===3"
              type="warning"
              size="mini"
              plain>
              待呼叫
            </el-tag >
          </template>
        </el-table-column>
        <el-table-column label="已呼数" align="center" prop="calledCallUserSum" />
        <el-table-column label="待呼数" align="center" prop="pendingCalledCallUserSum" />
        <el-table-column label="失败数" align="center" prop="failCallUserSum" />
        <el-table-column label="总呼数" align="center" prop="callUserSum" />
        <el-table-column label="创建人" align="center" prop="createName" width="120px" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160px"/>
        <el-table-column label="操作" align="center" class-name="small-padding" width="180px" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-notebook-2"
              @click="hangdleDitels(scope.row)"
              v-hasPermi="['qw:groupVoiceMsg:query']"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['qw:groupVoiceMsg: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 v-loading="loading" :title="title" :visible.sync="open" width="1500px" @close="closeData" style="font-weight: bold;font-size: 20px" append-to-body>
        <div style="display: flex;flex-wrap: wrap">
          <div style="width: 1000px;">
            <el-form ref="form" :model="form" :rules="rules" label-width="160px" size="medium" style="font-size: 20px" >
              <div>
                <span style="font-size: 20px">基础信息</span>
                <el-divider></el-divider>
              </div>

              <el-form-item label="选择外呼成员账号:" prop="userIdsSelectList" style="font-size: 30px">
                <div>
                  <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <el-button
                      size="medium"
                      icon="el-icon-circle-plus-outline"
                      plain
                      @click="handlelistUser">请选择外呼账号</el-button>
                    <div style="margin-left: 15px; color: #909399; font-size: 14px; display: flex; align-items: center;">
                      <i class="el-icon-info" style="margin-right: 5px;"></i>
                      <span>外呼账号需先在【系统管理】-【员工管理】-【操作】-【绑定外呼角色】后才能选择外呼成员</span>
                    </div>
                  </div>
                  <div>
                    <el-tag
                      style="margin-left: 5px; margin-top: 5px;"
                      size="medium"
                      :key="list.id"
                      v-for="list in userSelectList"
                      closable
                      :disable-transitions="false"
                      @close="handleClosegroupUser(list)">
                      {{list.qwUserName}}({{list.nickName}})
                    </el-tag>
                  </div>
                </div>
              </el-form-item>


              <el-form-item label="选择客户：">
                <el-radio-group v-model="form.selectType" @input="clearExpectCountCustomer" size="medium ">
                  <el-radio :label="item.dictValue" v-for="item in groupMsgTypeOptions"  >{{item.dictLabel}}</el-radio>
                </el-radio-group>
                <div style="background-color:#ecf8fe;width: 100%;margin-top: 1%" v-if="form.selectType==1">
                  <span style="padding: 3%;font-size: 15px" >查看该消息预计呼叫人数:</span>
                  <el-link style="color: #1aa4ff;" v-if="this.expectCountCustomer==null" @click="viewReceiveNum">点我查看
                  </el-link>
                  <span style="color: #d440ec;margin-left: 2%" v-if="this.expectCountCustomer!=null">{{this.expectCountCustomer}} 人</span>
                </div>
                <div v-if="form.selectType==2" style="padding-top: 1%;background-color: #fbfbfb">
                  <el-form-item label="按性别筛选客户:" class="elFormItemClass">
                    <el-radio-group v-model="form.gender"  @input="clearExpectCountCustomer">
                      <el-radio v-for="item in sysUserSex" :label="item.dictValue">{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="按所在群聊筛选:" class="elFormItemClass">
                    <div>
                      <div>
                        <el-button
                          icon="el-icon-s-comment"
                          plain
                          @click="handleGroupChatList">请选择群聊</el-button>
                      </div>
                      <div>
                        <div>
                          <el-tag
                            style="margin-left: 5px"
                            size="medium"
                            :key="list.chatId"
                            v-for="list in groupChatList"
                            closable
                            :disable-transitions="false"
                            @close="handleClosegroupChat(list)">
                            {{list.name}}
                          </el-tag>

                        </div>
                      </div>
                    </div>

                  </el-form-item>
                  <el-form-item label="按添加时间筛选" class="elFormItemClass">
                    <div style="width: 100%;display: flex">
                      <el-date-picker
                        v-model="form.timeScreenCharge"
                        @change="clearExpectCountCustomer"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        :default-time="['00:00:00', '23:59:59']">
                      </el-date-picker>
                    </div>

                  </el-form-item>
                  <el-form-item label="按客户标签筛选:" class="elFormItemClass">
                    <div>
                      <div>
                        <el-button icon="el-icon-s-check" plain @click="hangleChangeTags">请选择标签</el-button>
                      </div>
                      <el-tag type="success"
                              closable
                              :disable-transitions="false"
                              v-for="list in tagsIdsChangeSelectList"
                              :key="list.tagId"
                              @close="handleCloseTags(list)"
                              style="margin: 3px;"
                      >{{list.name}}
                      </el-tag>
                    </div>
                  </el-form-item>

                  <el-form-item label="排除标签筛选" class="elFormItemClass">
                    <div>
                      <div>
                        <el-button icon="el-icon-s-check" plain @click="hangleChangeOutTags">请选择排除的标签</el-button>
                      </div>

                      <div>
                        <el-tag type="success"
                                closable
                                :disable-transitions="false"
                                v-for="list in outTagsIdsChangeSelectList"
                                :key="list.tagId"
                                @close="handleCloseOutTags(list)"
                                style="margin: 3px;"
                        >{{list.name}}
                        </el-tag>
                      </div>

                    </div>
                  </el-form-item>

                  <div style="background-color:#ecf8fe;width: 100%;height: 10%;margin-top: 3%">
                    <span style="margin-left: 2%;font-size: 15px" v-if="this.expectCountGroupChat==null">查看该消息预计呼叫人数:</span>
                    <el-link style="color: #1aa4ff;margin-left: 3%" v-if="this.expectCountGroupChat==null" @click="viewReceiveGroupChatNum">点我查看
                    </el-link>
                    <span style="color: #d440ec;margin-left: 2%" v-if="this.expectCountGroupChat!=null">{{this.expectCountGroupChat}} 人</span>
                  </div>
                </div>


              </el-form-item>
              <div>
                <span>AI外呼客服选择</span>
                <el-divider></el-divider>
              </div>
            </el-form>
          </div>
        </div>

        <WelComeAddAIVoice ref="WelComeAddAIVoice"></WelComeAddAIVoice>

        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 选择群发账号弹窗   -->
      <el-dialog :title="listUser.title" :visible.sync="listUser.open" width="1600px"  append-to-body>
        <qwUserList ref="qwUserList" @selectUserList="selectUserList"></qwUserList>
      </el-dialog>

      <!-- 选择群聊    -->
      <el-dialog :title="groupChart.title" :visible.sync="groupChart.open" width="1300px"  append-to-body>
        <group-chat ref="GroupChat" @selectGroupChatList="selectGroupChatList"></group-chat>
      </el-dialog>

      <!--  选择的标签   -->
      <el-dialog :title="changeTagDialog.title" :visible.sync="changeTagDialog.open" width="1000px"  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>
        <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>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="tagSubmitForm(changeTagDialog.type)">确 定</el-button>
          <el-button @click="tagCancel(changeTagDialog.type)">取消</el-button>
        </div>
      </el-dialog>

      <!--  详情  -->
      <el-drawer :title="detailsDialog.title" :visible.sync="detailsDialog.open" size="80%" style="font-weight: bolder">
        <div style="background-color:  rgb(240 242 245)">
          <div style="width: 100%">
            <customer-group-details ref="customerGroupDetails" :rowDetailFrom="formDetails"></customer-group-details>
          </div>
        </div>
      </el-drawer>
    </div>

  </div>
</template>

<script>
import {
  myList,
  getGroupVoiceMsg,
  delGroupVoiceMsg,
  addGroupVoiceMsg, remindGroupVoiceMsg
} from '@/api/qw/groupVoiceMsg'
import GroupMsgUser from '@/views/qw/groupMsgUser/groupMsg'
import ImageUpload from "@/views/qw/material/ImageUpload";
import qwUserList from "@/views/qw/user/qwUserList"
import { selectCountCustomer } from '@/api/qw/externalContact'
import CustomerGroupDetails from '@/views/qw/groupVoiceMsg/customerGroupDetails'
import { getMyQwCompanyList } from "@/api/qw/user";
import {allListTagGroup} from "@/api/qw/tagGroup";
import {listTag, searchTags} from "@/api/qw/tag";
import  MaterialQw  from "@/views/qw/materialQw/index.vue";
import WelComeAddAIVoice from "../welcome/welComeAddAIVoice.vue";
import {listRole} from "../../../api/aiSopCall/aiSopCallRole";
export default {
  name: "GroupVoiceMsg",
  components: { CustomerGroupDetails, GroupMsgUser,ImageUpload,qwUserList,WelComeAddAIVoice,MaterialQw},
  data() {
    return {
      imageArr:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      myQwCompanyList:[],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      dialogImageUrl:null,
      dialogVisible:false,

      // 客户群发记录主表格数据
      groupMsgList: [],

      //发送类型
      groupMsgTimerType:[],
      //呼叫ai客服角色
      aiCustomerRoleOptions: [],

      //选择客户类型
      groupMsgTypeOptions:[],
      //是否允许成员在待发送列表中再次选择
      allowSelectOptions:[],

      //消息类型
      msgTypeOptions:[],
      //客户性别
      sysUserSex:[],
      genderSex:null,
      //预期发送客户人数
      expectCountCustomer:null,

      //部分客户预期发送客户人数
      expectCountGroupChat:null,

      //客户群选择列表
      groupChatList:[],

      //成员选择列表
      userSelectList:[],

      //查询预计通知人数
      countList:{
        //根据成员查
        userIds:{},
        //根据筛选客户条件查
        //1.群聊
        chartIds:{},

      },

      //选择的标签
      tagsIdsChangeSelectList:null,
      //排除的标签
      outTagsIdsChangeSelectList:null,

      //选择群发账号列表
      listUser:{
        title:"",
        open:false
      },
      //选择所在群聊里的人
      groupChart:{
        title:"",
        open:false,
      },

      //标签弹窗选择
      tagChange:{
        open:false,
        index:null,
      },
      //选择标签
      changeTagDialog:{
        title:"",
        open:false,
        type:null,
      },
      detailsDialog:{
        title:"",
        open:false,
        type:null,
      },
      //标签组
      tagGroupList:[],
      //所有标签
      tagList:[],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chatType: 1,
        sender: null,
        allowSelect: null,
        textContent: null,
        msgid: null,
        qwMsgId:null,
        corpId: null,
        companyId: null,
        tagNames: null,
        groupChatNames: null,
        fromUserCount: null,
        toUserCount: null,
        fromUserNum: null,
        toUserNum: null,
        aiCustomerRoleId: null,
      },
      // 表单参数
      form: {},
      //详情
      formDetails:{},
      // 表单校验
      rules: {

        chatType: [
          { required: true, message: "群发任务类型 好几种暂定 1AI外呼群发的  2手动的 3 sop模板提醒的", trigger: "change" }
        ],

        userIdsSelectList: [
          { required: true, message: "发送企业群发消息的成员账号不能为空", trigger: "blur" }
        ],
        allowSelect: [
          { required: true, message: "是否允许成员在待发送客户列表中重新进行选择，默认为true", trigger: "blur" }
        ],
        textContent:[
          { required: true, message: "消息文本不能为空噢", trigger: "blur" }
        ],
        createName:[
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ]

      },
      //日期快捷选择
      pickerOptions: {
        shortcuts: [
          {
            text: '最近三天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },

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

    listRole().then(response => {
      this.aiCustomerRoleOptions = response.rows;
    });

    //全部客户还是部分客户
    this.getDicts("sys_qw_groupMsg_type").then(response => {
      this.groupMsgTypeOptions = response.data;
    });

    //文本类型字典(复用)
    this.getDicts("sys_qw_welcome_type").then(response => {
      this.msgTypeOptions = response.data;
    });


    //发送类型
    this.getDicts("sys_qw_group_msg_timer_type").then(response => {
      this.groupMsgTimerType = response.data;
    });

    //客户性别
    this.getDicts("sys_qw_external_contact_gender").then(response => {
      this.sysUserSex = response.data;

      // 要添加的新对象数据
      let newUserData = {
        dictValue: "99",
        dictLabel: '全部',
      };
      // 添加对象到数组
      this.sysUserSex.push(newUserData);

    });

    //是否允许成员在待发送列表中再次选择
    this.getDicts("sys_qw_allow_select").then(response => {
      this.allowSelectOptions = response.data;
    });
  },

  watch:{
    // 监听 userSelectList 的变化，并同步更新 form.userIdsSelectList
    userSelectList(newList) {
      this.form.userIdsSelectList = newList.map(item => item.qwUserId);
    },
    groupChatList(newList){
      this.form.groupChatSelectList=newList.map(item=>item.chatId)
    },
  },
  methods: {
    updateCorpId(){
           this.getList();
     },

    //关闭弹窗-清空页面
    closeData(){
      this.reset();
    },
    /** 查询客户群发记录主列表 */
    getList() {
      this.loading = true;
      myList(this.queryParams).then(response => {
        this.groupMsgList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    //标签的选择
    tagSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },
    /** 提醒成员群发 */
    triggerremindGroupVoiceMsg(row){
      this.queryParams.qwMsgId=row.msgId
      remindGroupVoiceMsg(this.queryParams).then(res=>{

        if (res.code==200){

          if (res.data.errcode==0){
            return this.msgSuccess("提醒成员群发成功")
          }else if (res.data.errcode==41094){
            return this.msgWarning("此条记录的每日提醒次数超过限制了噢")
          }else {
            return this.msgError(res.data.errmsg)
          }

        }else {
          return this.msgError(res.msg)
        }
      })
    },
    handleSearchTags(name){

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

    },
    cancelSearchTags(){
      this.afreshData()
    },
    //清除点我查看
    clearExpectCountCustomer(){

      //选择全部客户的统计
      this.expectCountCustomer=null;
      //选择部分客户的统计
      this.expectCountGroupChat=null;
    },

    //查看预计接收人数
    viewReceiveNum(){
      if (this.userSelectList.length===0){
        return this.msgError("请选择群发成员账号");
      }else {
        this.form.corpId=this.queryParams.corpId;
        selectCountCustomer(this.form).then(res=>{
          this.expectCountCustomer=res.data;
        })
      }
    },

    //查看部分客户预计接收人数
    viewReceiveGroupChatNum(){

      if (this.userSelectList.length===0){
        return  this.msgError("请选择群发成员账号");
      }else {

        // 使用 map 方法和解构赋值提取每个子数组的第一个元素
        // 选择的标签
        if (this.tagsIdsChangeSelectList!=null){
          this.form.tagsIdsSelectList=this.tagsIdsChangeSelectList.map(item => item.tagId);
        }

        //排除的标签
        if (this.outTagsIdsChangeSelectList!=null){
          this.form.outTagsIdsSelectList = this.outTagsIdsChangeSelectList.map(item => item.tagId);
        }
        this.form.corpId=this.queryParams.corpId;
        selectCountCustomer(this.form).then(res=>{
          this.expectCountGroupChat=res.data;
        })

      }
    },

    //选择的成员账号列表
    selectUserList(list){
      this.listUser.open=false;
      //用于显示
      this.userSelectList=list;

    },

    //选择的部分客户时,选择的群聊里的
    selectGroupChatList(list){

      this.groupChart.open=false;
      //用于显示
      this.groupChatList=list;

    },
    //确定选择标签
    tagSubmitForm(type){
        if (type===1){
          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.tagsIdsChangeSelectList) {
                  this.tagsIdsChangeSelectList = [];
                }

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

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

        }else if (type===2){

          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.outTagsIdsChangeSelectList) {
                  this.outTagsIdsChangeSelectList = [];
                }

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

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

        }



      this.changeTagDialog.open = false;
    },

    //取消选择标签
    tagCancel(){
      this.changeTagDialog.open = false;
    },

    //删除一些选择了的账号
    handleClosegroupUser(list){

      // 假设 list 对象具有一个 id 属性
      const index = this.userSelectList.findIndex(t => t.id === list.id);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
      //表单同时清除
      // this.form.userIdsSelectList= this.userSelectList.map(item => item.id);
    },

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

      // 假设 list 对象具有一个 id 属性
      const index = this.groupChatList.findIndex(t => t.chatId === list.chatId);
      if (index !== -1) {
        this.groupChatList.splice(index, 1);
      }
      // //表单同时清除
      // this.form.groupChatSelectList=this.groupChatList.map(item=>item.chatId);
    },

    //删除一些选择的标签
    handleCloseTags(list){
      // 假设 list 对象具有一个 id 属性
      const ls = this.tagsIdsChangeSelectList.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.tagsIdsChangeSelectList.splice(ls, 1);
        this.tagsIdsChangeSelectList = [...this.tagsIdsChangeSelectList];
      }
    },

    //删除一些排除的标签
    handleCloseOutTags(list){
      // 假设 list 对象具有一个 id 属性
      const ls = this.outTagsIdsChangeSelectList.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.outTagsIdsChangeSelectList.splice(ls, 1);
        this.outTagsIdsChangeSelectList = [...this.outTagsIdsChangeSelectList];
      }
    },

    //选择群发的企业成员账号
    handlelistUser(){
      this.listUser.title="选择企业成员"
      this.listUser.open=true;
      setTimeout(() => {
        this.$refs.qwUserList.getBindAiUser(this.queryParams.corpId,1)
      }, 200);


      //预计人数制空
      this.expectCountCustomer=null;
    },

    //选择群聊
    handleGroupChatList(){

      this.groupChart.title="选择所在群聊里的客户"
      this.groupChart.open=true;

      setTimeout(() => {
        this.$refs.GroupChat.getDetailsList(this.queryParams.corpId)
      }, 200);

      //预计人数制空
      this.expectCountGroupChat=null;

    },

    //选择标签
    hangleChangeTags(){

      this.changeTagDialog.title="选择标签"
      this.changeTagDialog.open=true;
      this.changeTagDialog.type=1;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(this.tagsIdsChangeSelectList.map(tagItem => tagItem.tagId));
      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);
        }
      }

      // setTimeout(() => {
      //    this.$refs.TagGroupList.getTagGroupList(this.queryParams.corpId)
      // }, 200);


      //预计人数制空
      this.expectCountGroupChat=null;
    },

    //选择排除标签
    hangleChangeOutTags(){
      this.changeTagDialog.title="选择排除的标签"
      this.changeTagDialog.open=true;
      this.changeTagDialog.type=2;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(this.outTagsIdsChangeSelectList.map(tagItem => tagItem.tagId));
      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);
        }
      }

      // setTimeout(() => {
      //   this.$refs.TagGroupList.getTagGroupList(this.queryParams.corpId)
      // }, 200);
      //

      //预计人数制空
      this.expectCountGroupChat=null;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chatType: 1,
        sender: null,
        gender:"99",
        allowSelect: "Y",
        textContent: null,
        msgid: null,
        corpId: null,
        companyId: null,
        tagNames: null,
        groupChatNamesList: [],
        fromUserCount: null,
        toUserCount: null,
        fromUserNum: null,
        toUserNum: null,
        createTime: null,
        updateTime: null,
        msgType:null,
        mediaId: null,
        mediaPicUrl: null,
        title: null,
        picurl: null,
        description: null,
        url: null,
        miniprogramTitle: null,
        miniprogramPicMediaId: null,
        miniprogramPicUrl: null,
        miniprogramAppid: null,
        miniprogramPage: null,
        fileMediaId: null,
        fileUrl: null,
        videoMediaId: null,
        videoUrl: null,
        //选择的成员账号
        userIdsSelectList:[],
        //选择的群聊
        groupChatSelectList:[],
        //选择的时间
        timeScreenCharge:[],

        //全部客户还是部分客户
        selectType:'1',

        //选择的标签列表
        tagsIdsSelectList:[],

        //排除的标签
        outTagsIdsSelectList:[],
      };
      this.userSelectList=[];
      this.expectCountCustomer=null;
      this.groupChatList=[];
      this.tagsIdsChangeSelectList=[];
      this.outTagsIdsChangeSelectList=[];
      this.expectCountGroupChat=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    hangdleDitels(row){
      this.reset();
      const id = row.id || this.ids
      getGroupVoiceMsg(id).then(response => {
        this.formDetails = response.data;
        this.detailsDialog.open = true;
        this.detailsDialog.title = "客户外呼记录";
      });
    },
    /** 重置按钮操作 */
    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() {
      // 检查是否选择了企微公司
      if (!this.queryParams.corpId) {
        this.msgError("请先选择要操作的企微公司");
        return;
      }
      this.reset();
      this.open = true;
      this.form.msgType="1"
      this.title = "新建外呼";
      this.afreshData();
    },
    /**
     * 重新获取 部分数据
     */
    afreshData(){
      //所有的标签组
      allListTagGroup({corpId:this.queryParams.corpId}).then(response => {
        this.tagGroupList = response.rows;
      });

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

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGroupVoiceMsg(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户群发记录主";
      });
    },

    openImageViewer(url) {
      // 打开大图预览对话框
      this.dialogImageUrl=url
      this.dialogVisible = true;
    },

    /** 提交按钮 */
    async  submitForm() {
      // 选择的标签
      if (this.tagsIdsChangeSelectList!=null){
        this.form.tagsIdsSelectList=this.tagsIdsChangeSelectList.map(item => item.tagId);
      }

      //排除的标签
      if (this.outTagsIdsChangeSelectList!=null){
        this.form.outTagsIdsSelectList = this.outTagsIdsChangeSelectList.map(item => item.tagId);
      }
      this.form.corpId=this.queryParams.corpId;
      try {
        // 验证子组件表单
        await this.$refs.WelComeAddAIVoice.validateChildForm();
        // 父组件表单验证逻辑
        await this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              return this.msgError("没有修改选项");
            } else {
              this.loading=true;
              Object.assign(this.form, this.$refs.WelComeAddAIVoice.form);

              this.form.chatType= 1 ;

              addGroupVoiceMsg(this.form).then(response => {
                  this.msgSuccess("创建成功");
                  this.open = false;
                  this.loading = false;
                  this.getList();
              }).catch(error => {
                this.open=true;
                this.loading = false;
                this.msgError("创建失败:"+ error);
              }).finally(
                  () => {
                    this.$refs["form"].resetFields();
                    this.$refs.WelComeAddAIVoice.reset();
                    this.userSelectList=[];
                    this.reset();
                  }
              );
            }
          }
        });

      } catch (error) {
        console.error('表单编辑群发信息验证不用过:', error.message);
      }


    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除客户群发记录主编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delGroupVoiceMsg(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
<style scoped>
.elFormItemClass{
  margin: 20px 0px

}

.message-stayle span {
  word-break: break-all;
}


/* 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;
}

</style>
