<template>
  <div >
    <div style="padding: 10px">
      <div style="border-bottom: 1px solid #e6e6e6;background-color: white; display: flex;justify-content: left;padding-top: 20px;">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <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="name">
                <el-input
                  v-model="queryParams.name"
                  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="skipVerify">
          <el-select v-model="queryParams.skipVerify" placeholder="是否无需验证" clearable size="small">
            <el-option
              v-for="dict in isOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>


<!--        <el-form-item label="用户" prop="userIds">
          <el-select v-model="queryParams.userIds" filterable  placeholder="公司员工"  >
            <el-option style="width: 300px;"
              v-for="dict in companyUserList"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item> -->


<!--         <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        <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>
      </div>

    <div style="height: 700px;width: auto; display: flex;margin-top: 10px;">
      <div style="background-color: white;height: 100%;width: 15%; border: 1px solid #e6e6e6; ">
          <div >
            <contactWayGroup ref="contactWayGroup" @selectGroupScreen="selectGroupScreen" @getGroupList="getGroupList" ></contactWayGroup>
          </div>
      </div>
      <div style="height: 100%;width: 1%">

      </div>

      <div style="background-color: white;height: 100%;width: 85%;border: 1px solid #e6e6e6; ">
        <el-row :gutter="10" class="mb8" style="margin-top: 10px;margin: 15px;">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['qw:contactWay:add']"
            >新增</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="['qw:contactWay:export']"
            >导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="sync"
              v-hasPermi="['qw:contactWay:add']"
            >同步</el-button>
          </el-col>
        </el-row>
        <div style=" height: calc(100% - 40px); overflow-y: auto;">
          <el-table v-loading="loading" :data="contactWayList" @selection-change="handleSelectionChange" border>
            <el-table-column label="id" align="center" prop="id" />
            <el-table-column label="名称" align="center" prop="name" />
            <el-table-column label="二维码" align="center" prop="qrCode" width="150px" >
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  title=""
                  trigger="hover">
                  <img slot="reference" :src="scope.row.qrCode" width="100px">
                  <img :src="scope.row.qrCode" style="max-width: 350px;">
                </el-popover>
              </template>
            </el-table-column>
            <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="remark" />
            <el-table-column label="是否免验证" align="center" prop="skipVerify">
              <template slot-scope="scope">
                <dict-tag :options="isOptions" :value="scope.row.skipVerify"/>
              </template>
            </el-table-column>
            <el-table-column label="state参数" align="center" prop="state" />
            <el-table-column label="用户" align="center" prop="userIds" width="200px">
              <template slot-scope="scope">
                <div v-for="i in JSON.parse(scope.row.userIds)" :key="i" style="display: inline;">
                <el-tag type="success" v-for="ii in companyUserList" :key="ii.id" style="margin: 3px;" v-if="ii.qwUserId==i">{{ii.qwUserName}}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="添加人数" align="center" prop="addNum" />
            <el-table-column label="删除人数" align="center" prop="deleteNum" />
            <el-table-column label="净人数" align="center" prop="num" />

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="170px">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['qw:contactWay:edit']"
                >修改</el-button>
                <el-button
                   size="mini"
                   type="text"
                   @click="handledetails(scope.row)"
                   >数据统计
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['qw:contactWay:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination style="margin: 10px;"
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
          </div>
      </div>

     </div>



    <!-- 添加或修改企微活码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
           <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="客服类型" prop="userType" >
          <el-radio-group v-model="form.userType">
             <el-radio :key="1":label="1" >全天在线</el-radio>
             <el-radio :key="2":label="2" >自动上下线</el-radio>
             </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="userTimeJson" v-if="form.userType==2">
          <div v-for="(item, index) in userTimeJson"    >
            <el-row>
              <el-col :span="22">
                <div style="background-color: #fbfbfb;padding: 15px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                  <el-form :model="item"  label-width="80px">
                    <el-form-item label="员工选择">
                      <div>
                        <el-button
                          size="medium"
                          icon="el-icon-circle-plus-outline"
                          plain
                          @click="handleListUserForTimeSlot(index)">请选择使用员工
                        </el-button>
                      </div>
                      <div style="margin-top: 10px;">
                        <el-tag
                          style="margin-left: 5px; margin-top: 5px;"
                          size="medium"
                          :key="user.id"
                          v-for="user in item.userList || []"
                          closable
                          :disable-transitions="false"
                          @close="handleCloseTimeSlotUser(index, user)">
                          {{ user.qwUserName }}
                        </el-tag>
                      </div>
                    </el-form-item>
                    <el-form-item label="工作周期" prop="week" style="height: 50px;" >
                       <el-select v-model="item.week" remote multiple placeholder="请选择" filterable  style="width: 100%;">
                         <el-option
                           v-for="dict in weekOptions"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value">
                         </el-option>
                       </el-select>
                    </el-form-item>
                    <el-form-item label="上线时间"  style="height: 50px;">
                       <el-time-select style="margin-right: 20px; width: 150px;"
                          placeholder="起始时间"
                          v-model="item.startTime"
                          :picker-options="{
                            start: '00:00',
                            step: '00:15',
                            end: '24:00'
                          }">
                        </el-time-select>
                        <el-time-select style="width: 150px;"
                          placeholder="结束时间"
                          v-model="item.endTime"
                          :picker-options="{
                            start: '00:00',
                            step: '00:15',
                            end: '24:00',
                            minTime: item.startTime
                          }">
                        </el-time-select>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
              <el-col :span="1" :offset="1">
                 <i class="el-icon-delete-solid" @click="delUserTime(index)" style="margin-top: 165px;" v-if="userTimeJson.length>1"></i>
              </el-col>
            </el-row>
          </div>
           <el-link type="primary" class="el-icon-plus" :underline="false" @click='addUserTime()'>添加其他工作周期</el-link>
        </el-form-item>
        <el-form-item label=""  v-if="form.userType==1">
          <div>
            <el-button
              size="medium"
              icon="el-icon-circle-plus-outline"
              plain
              @click="handleListUser(form.type,form.sendType, true)">请选择使用员工
            </el-button>
          </div>
          <div>
            <el-tag
              style="margin-left: 5px"
              size="medium"
              :key="user.id"
              v-for="user in userSelectList"
              closable
              :disable-transitions="false"
              @close="handleCloseGroupUser(user)">
              {{ user.qwUserName }}
            </el-tag>
          </div>

        </el-form-item>
        <el-form-item label="员工添加上限"v-if="form.userType==1" prop="isUserLimit">
          <el-switch
            v-model="form.isUserLimit"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="" v-if="form.isUserLimit==1&&form.userType==1">
                <el-table  :data="userLimitJson" style="border: 1px solid #e6e6e6;width: 50%;">
                  <el-table-column label="名称" align="center" prop="userId" >
                   <template slot-scope="scope">
                     <div v-for="(companyUser, index) in companyUserList" :key="index">
                        <span v-if="companyUser.qwUserId==scope.row.userId">{{companyUser.qwUserName}}</span>
                     </div>
                   </template>
                  </el-table-column>
                  <el-table-column label="数量" align="center" prop="limitCount" >
                     <template slot-scope="scope">
                       <div>
                           <el-input-number v-model="scope.row.limitCount"    size="mini" :min="0"   ></el-input-number>
                       </div>
                     </template>
                  </el-table-column>
                </el-table>
        </el-form-item>
        <el-form-item label="备用员工" prop="spareUserIds" >
         <el-select v-model="spareUserIds" remote multiple placeholder="员工" filterable  style="width: 800px;">
           <el-option
             v-for="dict in companyUserList"
             :key="dict.qwUserId"
             :label="dict.qwUserName"
             :value="dict.qwUserId">
           </el-option>
         </el-select>
        </el-form-item>


          <el-form-item label="分组" prop="groupId">
            <el-select v-model="form.groupId" placeholder="分组">
              <el-option
                v-for="dict in groupList"
                :label="dict.groupName"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
		  <el-form-item label="信息流" prop="informationId">
		    <el-select v-model="form.informationId" placeholder="分组">
		      <el-option
		        v-for="dict in informationList"
		        :label="dict.dictLabel"
		        :value="parseInt(dict.dictValue)"
		      ></el-option>
		    </el-select>
		  </el-form-item>


          <el-form-item label="免验证" prop="skipVerify">
              <el-switch
                v-model="form.skipVerify"
                :active-value="1"
                :inactive-value="0"
                >
              </el-switch>
          </el-form-item>
          <el-form-item label="备注" prop="isRemark">
            <el-radio-group v-model="form.isRemark">
              <el-switch
                v-model="form.isRemark"
                :active-value="1"
                :inactive-value="0"
                >
              </el-switch>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="form.isRemark==1" prop="remarkStatus">
            <el-radio-group v-model="form.remarkStatus" >
              <el-radio :label="1">昵称后</el-radio>
              <el-radio :label="2">昵称前</el-radio>
            </el-radio-group>
          </el-form-item>
        <el-form-item label="" prop="remark" v-if="form.isRemark==1">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="添加描述"  prop="isDescription">
          <el-switch
            v-model="form.isDescription"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="" prop="description" v-if="form.isDescription==1">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="开启欢迎语屏蔽"   prop="isCloseWelcome">
          <el-switch
            v-model="form.isCloseWelcome"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="欢迎语屏蔽" prop="closeWelcomeWord" v-if="form.isCloseWelcome==1">
          <el-tag
            v-for="tag in closeWelcomeWord"
            closable
            :disable-transitions="false"
            @close="handleCloseWord(tag)">
            {{tag}}
          </el-tag>
          <el-input
            style="width:110px"
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" style="width: 110px" @click="showInput">新增屏蔽关键词</el-button>
        </el-form-item>

        <el-form-item label="添加标签"  prop="isTag">
          <el-switch
            v-model="form.isTag"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="" v-if="form.isTag==1">
          <div>
            <div>
              <el-button  size="medium"   icon="el-icon-circle-plus-outline"   plain  @click="handleTags()">请选择标签</el-button>
            </div>
            <div>
              <div v-for="i in tagListForm" :key="i" style="display: inline;">
              <el-tag type="success" closable :disable-transitions="false" @close="handleCloseTag(i)" v-for="ii in tagList" :key="ii.id" style="margin: 3px;" v-if="ii.tagId==i">{{ii.name}}</el-tag>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="发送欢迎语" prop="isWelcome">
          <el-switch
            v-model="form.isWelcome"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="消息文本内容" prop="textContent" v-if="form.isWelcome==1">
          <el-input type="textarea" cols="1000" v-model="form.textContent"  placeholder="请输入消息文本内容" />
        </el-form-item>
        <el-form-item label="图片的链接" prop="imagePicUrl"  v-if="form.isWelcome==1">
          <ImageUpload v-model="form.imagePicUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="分时段欢迎语"  prop="isSpanWelcome">
          <el-switch
            v-model="form.isSpanWelcome"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
        <div  v-if="form.isSpanWelcome == '1'"  v-for="(item, index) in welcomeJson"    :key="index" >
          <el-form-item :label="`时段 ${index + 1}：`">
              <el-row>
                <el-col :span="22">
                  <div style="background-color: #fbfbfb;padding: 10px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                    <el-form ref="friendWelcomeItemForm"  :rules="itemRules" :model="item">
                      <div style="display: flex; ">
                        <el-form-item label="时间:" prop="week" style="flex: 6;">
                          <el-select v-model="item.week" remote multiple placeholder="请选择" filterable style="width: 580px;">
                            <el-option
                              v-for="dict in weekOptions"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="startTime" style="flex: 1;">
                          <el-time-picker
                            v-model="item.startTime"
                            value-format="HH:mm"
                            format="HH:mm"
                            :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                            placeholder="开始"
                            style="width: 100px">
                          </el-time-picker>

                        </el-form-item>
                        <el-form-item prop="endTime" style="flex: 1;">
                          <el-time-picker
                            v-model="item.endTime"
                            value-format="HH:mm"
                            format="HH:mm"
                            :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                            placeholder="结束"
                            style="width: 100px">
                          </el-time-picker>
                        </el-form-item>
                      </div>

                      <el-form-item style="margin-top: 20px" prop="text">
                        <el-input v-model="item.text.content" type="textarea" :rows="12" maxlength="1300" show-word-limit placeholder="请输入消息内容"/>
                        <!-- 附件和链接列表 -->
                        <el-row>
                          <el-col>
                            <div v-for="(attachment, attachIndex) in item.attachments" :key="attachIndex" style="background-color: #f5f7fa;padding: 5px;border: 1px solid  #d9d9d9;">
                              <div slot="header" style="  display: flex;justify-content: space-between;align-items: center; ">
                                <div style="flex: 1;">
                                  <span v-if="attachment.msgtype === 'image'">【图片】: {{ attachment.image.pic_url }}</span>
                                  <span v-if="attachment.msgtype === 'link'">【链接】: {{ attachment.link.title }}-{{attachment.link.desc}}</span>
                                </div>
                                <div style="  display: flex;gap: 10px;">
                                  <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-edit"
                                    style="float: left;"
                                    @click="editFileItem(attachment,attachIndex,index)"
                                  >修改</el-button>
                                  <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    style="float: right;"
                                    @click="removeFileItem(attachment,attachIndex,index)"
                                  >删除</el-button>
                                </div>
                              </div>
                            </div>
                          </el-col>
                        </el-row>

                        <el-dropdown @command="(command) => handleCommand(command, index)" trigger="click" placement="top-start">
                          <el-dropdown-menu slot="dropdown" style="width: 100px;">
                            <el-dropdown-item command="image">
                              <i class="el-icon-picture" style="margin-right: 10px;"></i>图片
                            </el-dropdown-item>
                            <el-dropdown-item command="link">
                              <i class="el-icon-link" style="margin-right: 10px;"></i>链接
                            </el-dropdown-item>
                          </el-dropdown-menu>

                          <span class="el-dropdown-link">
                          <el-link icon="el-icon-paperclip" type="text" style="color: rgb(24, 144, 255)">
                            添加附件(最多9个)
                          </el-link>
                          </span>
                        </el-dropdown>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-col>
                <el-col :span="1" :offset="1">

                  <el-link v-if="welcomeJson.length>1" icon="el-icon-delete-solid" @click="delItemList(index)" type="text" style="margin-top: 400px" ></el-link>
                </el-col>
              </el-row>
          </el-form-item>
        </div>
        <div  v-if="form.isSpanWelcome == '1'" style="margin-left: 10%">
          <el-link type="primary" class="el-icon-plus" :underline="false" @click='addItemList()'>添加其他分时段欢迎语</el-link>
        </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>
    <el-dialog :title="welcomeItem.title" :visible.sync="welcomeItem.open" style="width: 1300px;height: 100%" append-to-body>
      <el-form ref="fileFrom" :model="fileFrom" :rules="fuleRules" label-width="100px">
        <div v-if="welcomeItem.type==='image'">
          <el-form-item label="图片：" prop="imagePicUrl">
            <ImageUpload v-model="fileFrom.imagePicUrl"  type="image" :num="10" :width="150" :height="150"  disabled/>
          </el-form-item>
        </div>
        <div v-if="welcomeItem.type==='link'">

          <el-form-item label="选择课程">
            <el-select  v-model="fileFrom.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChange(fileFrom,welcomeItem.index,welcomeItem.itemIndex)">
              <el-option
                v-for="dict in courseList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
            <el-select  v-model="fileFrom.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange(fileFrom, welcomeItem.index, welcomeItem.itemIndex)" >
              <el-option
                v-for="dict in videoList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图文标题：" prop="linkTitle">
            <el-input v-model="fileFrom.linkTitle" :rows="2" maxlength="42"  show-word-limit placeholder="请输入图文消息标题，最长为42字" />
          </el-form-item>
          <el-form-item label="图文封面：" prop="linkPicUrl">
            <ImageUpload v-model="fileFrom.linkPicUrl"  type="image" :num="10" :width="150" :height="150" />
          </el-form-item>
          <el-form-item label="图文的描述：" prop="linkDesc">
            <el-input v-model="fileFrom.linkDesc" :rows="4" maxlength="170" show-word-limit type="textarea" placeholder="请输入内容,，最长为170字" />
          </el-form-item>
          <div v-if="fileFrom.videoId==null" style="margin-top: 1%">
            <el-form-item label="图文链接:"  label-width="100px" >
              <el-input v-model="fileFrom.linkUrl" placeholder="请输入链接地址" style="width: 90%;"/>
            </el-form-item>
          </div>
          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="图文链接:"  label-width="100px" >
              <el-tag type="warning">选择的课程小节 即为卡片链接地址</el-tag>
            </el-form-item>
          </div>
          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="课节过期时间" style="margin-top: 1%" required label-width="110px">
              <el-row>
                <el-input-number  v-model="fileFrom.expiresDays"  :min="1" :max="9999" ></el-input-number>
                （天）
              </el-row>
              <el-row>
                <span class="tip">默认为30天</span>
              </el-row>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="confirmUpload">确定</el-button>
        <el-button type="primary" @click="cancelUpload">取消</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>
      <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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTagSubmitForm()">确 定</el-button>
        <el-button @click="addTagCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="listUser.title" :visible.sync="listUser.open" width="700px" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    </div>
        <el-drawer
        :with-header="false"
        size="75%"
        :title="show.title" :visible.sync="show.open">
       <statisDetails  ref="Details" />
     </el-drawer>
   </div>
</template>

<script>
import { informationList,sync,listContactWay, getContactWay, delContactWay, addContactWay, updateContactWay, exportContactWay } from "@/api/qw/contactWay";
import {getQwAllUserList } from "@/api/company/companyUser";
import contactWayGroup from '@/views/qw/contactWay/group';
import {listTag, getTag, searchTags,} from "@/api/qw/tag";
import { allListTagGroup} from "@/api/qw/tagGroup";
import ImageUpload from '@/views/qw/material/ImageUpload.vue'
import statisDetails from '@/views/qw/contactWay/statisDetails';
import { getMyQwUserList,getMyQwCompanyList } from "@/api/qw/user";
import {courseList, videoList} from "@/api/qw/sop";
import qwUserList from "@/views/qw/user/qwUserList.vue";
export default {
  name: "ContactWay",
   components: {qwUserList, contactWayGroup,ImageUpload,statisDetails},
  data() {
    return {
      // 遮罩层
      loading: true,
	  informationList:[],
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      userTimeJson:[{userIds:null,userList:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}],
      currentEditingTimeSlotIndex: -1, // 当前正在编辑的时间段索引
      userIds:[],
      show:{
           title:"医院详情",
           open:false,
       },
      userLimitJson:[],
      welcomeJson:[{text:{content:null},attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}],
      closeWelcomeWord: [],
      inputVisible: false,
      inputValue: '',
      myQwCompanyList:[],
      tagOpen:false,
      spareUserIds:[],
      welcomeItem:{
        open: false,
        title: '',
        type: '',
        index: -1,
        itemIndex: -1
      },
      courseList:[],
      videoList:[],
      //标签弹窗选择
      tagChange:{
        open:false,
        index:null,
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      groupList:[],
      // 企微活码表格数据
      contactWayList: [],
      // 弹出层标题
      title: "",
      itemRules: {
        week: [
          { required: true, message: '请选择发起时间的星期', trigger: 'submit' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'submit' },
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'submit' },

        ],
        text: [
          { required: true, message: '消息内容不能为空噢', trigger: 'submit' }
        ],

      },
      fuleRules:{
        imagePicUrl:[ { required: true, message: "图片不能为空", trigger: "submit" }],
        linkTitle:[ { required: true, message: "图文标题不能为空", trigger: "submit" }],
        linkUrl:[ { required: true, message: "图文链接不能为空", trigger: "submit" }],
      },
      // 是否显示弹出层
      open: false,
      // 联系方式类型,1-单人, 2-多人字典
      typeOptions: [],
      weekOptions: [{
          value: 1,
          label: '星期一'
        }, {
          value: 2,
          label: '星期二'
        }, {
          value: 3,
          label: '星期三'
        }, {
          value: 4,
          label: '星期四'
        }, {
          value: 5,
          label: '星期五'
        }
        , {
          value: 6,
          label: '星期六'
        }
        , {
          value: 7,
          label: '星期天'
        }],
      // 外部客户添加时是否无需验证字典
      isOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        skipVerify: null,
        state: null,
        userIds: null,
        addNum: null,
        deleteNum: null,
        num: null,
        qrCode: null,
        configId: null,
        isDel: 0,
        companyId: null,
        groupId: null,
      },
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 表单参数
      form: {

      },
      fileFrom:{
        imagePicUrl:null,
        linkTitle:null,
        linkPicUrl:null,
        linkDesc:null,
        linkUrl:null,
        videoId:null,
        courseId:null,
        expiresDays:30,
      },
      // 是否发送欢迎语字典
      companyUserList:[],
      // 表单校验
      rules: {
        name:[{required:true,message:"名称不能为空",trigger:"blur"}],
        userIds:[{required:true,message:"用户不能为空",trigger:"blur"}],
        skipVerify:[{required:true,message:"是否跳过验证不能为空",trigger:"change"}],
        isWelcome:[{required:true,message:"是否发送欢迎语不能为空",trigger:"change"}],
        textContent:[{required:true,message:"不能为空",trigger:"change"}],
        isUserLimit:[{required:true,message:"不能为空",trigger:"change"}],
        isSpanWelcome:[{required:true,message:"不能为空",trigger:"change"}],
        isCloseWelcome:[{required:true,message:"不能为空",trigger:"change"}],
        isTag:[{required:true,message:"不能为空",trigger:"change"}],
        tags:[{required:true,message:"不能为空",trigger:"change"}],
        isRemark:[{required:true,message:"不能为空",trigger:"change"}],
        remarkStatus:[{required:true,message:"不能为空",trigger:"change"}],
        description:[{required:true,message:"不能为空",trigger:"change"}],
        isDescription:[{required:true,message:"不能为空",trigger:"change"}],
        groupId:[{required:true,message:"不能为空",trigger:"change"}],
        userType:[{required:true,message:"不能为空",trigger:"change"}],
      },
      tagGroupList:[],
      tagList:[],
      tagListForm:[],
      // 选择使用员工相关参数
      userSelectList: [],
      //企业微信员工
      listUser: {
        title: "",
        open: false
      },
    };
  },
  created() {
	  informationList().then(response => {
	      this.informationList = response.data;
	  });
    courseList().then(response => {
      this.courseList = response.list;
    });
	  this.getDicts("sys_qw_contact_way_type").then(response => {
	    this.typeOptions = response.data;
	  });
	  this.getDicts("sys_company_or").then(response => {
	    this.isOptions = response.data;
	  });
    getMyQwCompanyList().then(response => {
        this.myQwCompanyList = response.data;
        if(this.myQwCompanyList!=null && this.myQwCompanyList.length>0){
          this.queryParams.corpId=this.myQwCompanyList[0].dictValue;
          setTimeout(() => {
            this.$refs.contactWayGroup.getDetails(this.queryParams.corpId);
          }, 100);
          getQwAllUserList(this.queryParams.corpId).then(response => {
              this.companyUserList = response.data;
          });
          listTag({corpId:this.queryParams.corpId}).then(response => {
            this.tagList = response.rows;
          });
          allListTagGroup({corpId:this.queryParams.corpId}).then(response => {
              this.tagGroupList = response.rows;
          });
          this.getList();
        }
    });





  },
  methods: {
    updateCorpId(){
      setTimeout(() => {
        this.$refs.contactWayGroup.getDetails(this.queryParams.corpId);
      }, 1);
      getQwAllUserList(this.queryParams.corpId).then(response => {
          this.companyUserList = response.data;
      });
      listTag({corpId:this.queryParams.corpId}).then(response => {
        this.tagList = response.rows;
      });
      allListTagGroup({corpId:this.queryParams.corpId}).then(response => {
          this.tagGroupList = response.rows;
      });
       this.getList();
    },
    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.tagTotal = response.total;
      });
      // searchTags({name:name,corpId:this.queryParams.corpId}).then(response => {
      //   this.tagGroupList = response.rows;
      // });

    },
    cancelSearchTags(){
      this.afreshData(this.queryParams.corpId)
    },

    /**
     * 重新获取 部分数据
     */
    afreshData(value){
      //所有的标签组
      allListTagGroup({corpId:value}).then(response => {
        this.tagGroupList = response.rows;
      });

      //所有的标签
      listTag({corpId:value}).then(response => {
        this.tagList = response.rows;
      });
    },
    /** 查询企微活码列表 */
    getList() {
      this.loading = true;
      listContactWay(this.queryParams).then(response => {
        this.contactWayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handledetails(row){
       this.show.open=true;
       setTimeout(() => {
            this.$refs.Details.getDetails(row.id);
       }, 1);
    },
    courseChange(fileFrom,index,itemIndex){

      // 清空 videoId 选择
      this.$set(fileFrom, 'videoId', null);
      // 清空 videoList
      this.videoList = [];

      if (fileFrom.courseId != null) {
        // 查找选中的课程对应的 label 和 dictImgUrl
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === fileFrom.courseId);

        if (selectedCourse) {
          // 设置 linkTitle 和 linkImageUrl
          this.$set(fileFrom, 'linkTitle', selectedCourse.dictLabel);
          this.$set(fileFrom, 'linkPicUrl', selectedCourse.dictImgUrl);
        }

        // 获取新的 videoList
        videoList(fileFrom.courseId).then(response => {
          this.videoList = response.list;
        });
      }
      //
      // // 更新对应的数据层级
      // if (itemIndex === -1) {
      //   // 更新 form.attachments
      //   this.$set(this.form.attachments, index, {
      //     ...this.form.attachments[index],
      //     courseId: fileFrom.courseId,
      //     videoId: null, // 因为已清空
      //     title: fileFrom.linkTitle,
      //     picurl: fileFrom.linkPicUrl
      //   });
      // } else {
      //
      //   this.$set(this.form.daypartingItemlist[itemIndex].attachments, index, {
      //     ...this.form.daypartingItemlist[itemIndex].attachments[index],
      //     courseId: fileFrom.courseId,
      //     videoId: null, // 因为已清空
      //     title: fileFrom.linkTitle,
      //     picurl: fileFrom.linkPicUrl
      //   });
      // }
    },
    videoIdChange(fileFrom,index, itemIndex){
      //选择了课程小节则 默认绑上
      if (fileFrom.videoId != null) {
        // 根据 videoId 获取相关信息（假设有相关的 API 调用）
        let  selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === fileFrom.videoId);
        if (selectedVideo) {
          this.$set(fileFrom, 'linkDesc', selectedVideo.dictLabel);
          this.$set(fileFrom, 'expiresDays', 30);
        }
      }

      // // 更新对应的数据层级
      // if (itemIndex === -1) {
      //   // 更新 form.attachments
      //   this.$set(this.form.attachments, index, {
      //     ...this.form.attachments[index],
      //     videoId: fileFrom.videoId,
      //     desc: fileFrom.linkDesc,
      //   });
      // } else {
      //   // 更新 form.daypartingItemlist[itemIndex].attachments
      //   this.$set(this.form.daypartingItemlist[itemIndex].attachments, index, {
      //     ...this.form.daypartingItemlist[itemIndex].attachments[index],
      //     videoId: fileFrom.videoId,
      //     desc: fileFrom.linkDesc,
      //   });
      //
      // }

    },
    //附件选择
    handleCommand(command,itemIndex){
      if (this.welcomeJson[itemIndex].attachments.length>=9){
        return this.$message.error('附件数量已达上限，无法添加更多附件');
      }
      this.welcomeItem = {
        open: true,
        title: command === 'image' ? '添加图片' : '添加链接',
        type: command,
        index: itemIndex === -1 ? this.form.attachments.length : this.welcomeJson[itemIndex].attachments.length,
        itemIndex
      };
    },
    //重置附件表单
    resetFileFrom() {
      this.fileFrom = {
        imagePicUrl: null,
        linkTitle: null,
        linkPicUrl: null,
        linkDesc: null,
        linkUrl: null,
        videoId:null,
        courseId:null,
      };

      this.welcomeItem={
        open: false,
        title: '',
        type: '',
        index: -1,
        itemIndex: -1
      } // 重置编辑索引
    },

    //修改附件
    editFileItem(item, index, itemIndex){

      this.welcomeItem = {
        open: true,
        title: item.msgtype === 'image' ? '编辑图片' : '编辑链接',
        type: item.msgtype,
        index,
        itemIndex
      };
      if (item.msgtype === 'image') {
        this.fileFrom.imagePicUrl = item.image.pic_url;
      } else if (item.msgtype === 'link') {
        this.fileFrom.linkTitle = item.link.title;
        this.fileFrom.linkPicUrl = item.link.picurl;
        this.fileFrom.linkDesc = item.link.desc;
        this.fileFrom.linkUrl = item.link.url;
        this.fileFrom.videoId = item.link.videoId;
        this.fileFrom.courseId = item.link.courseId;
        this.fileFrom.expiresDays = item.link.expiresDays;
      }

      videoList(item.link.courseId).then(response => {
        this.videoList = response.list;
      });

    },

    //删除附件
    removeFileItem(data,index, itemIndex) {

      if (itemIndex === -1) {
        this.form.attachments.splice(index, 1);
      } else {
        this.welcomeJson[itemIndex].attachments.splice(index, 1);
      }
    },

    //添加分时段欢迎语
    addItemList(){
      this.welcomeJson.push({text:{content:null},attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null})
    },


    //删除某一个分时段欢迎语
    delItemList(index){
      this.welcomeJson.splice(index,1)
    },

    //提交附件
    confirmUpload() {

      const { type, index, itemIndex } = this.welcomeItem;

      let attachment = {};
      if (type === 'image') {
        attachment = {
          msgtype: 'image',
          image: {
            pic_url: this.fileFrom.imagePicUrl
          }
        };
      } else if (type === 'link') {
        attachment = {
          msgtype: 'link',
          link: {
            title: this.fileFrom.linkTitle,
            picurl: this.fileFrom.linkPicUrl,
            desc: this.fileFrom.linkDesc,
            url: this.fileFrom.linkUrl,
            courseId:this.fileFrom.courseId,
            videoId:this.fileFrom.videoId,
            expiresDays:this.fileFrom.expiresDays,
          }
        };
      }

      if (itemIndex === -1) {
        // 默认欢迎语附件处理
        if (index < this.form.attachments.length) {
          // 存在附件则更新
          this.form.attachments.splice(index, 1, attachment);
        } else {
          // 不存在附件则插入
          this.form.attachments.push(attachment);
        }
      } else {
        // 分时段欢迎语附件处理
        if (index < this.welcomeJson[itemIndex].attachments.length) {
          // 存在附件则更新
          this.welcomeJson[itemIndex].attachments.splice(index, 1, attachment);
        } else {
          // 不存在附件则插入
          this.welcomeJson[itemIndex].attachments.push(attachment);
        }
      }

      this.resetFileFrom();
    },

    //取消附件
    cancelUpload() {
      this.resetFileFrom();
      this.welcomeItem.open = false;
    },



    userChange(){

      for (let i = 0; i < this.userIds.length; i++) {
             if(!this.userLimitJson.find(item => item.userId == this.userIds[i])){
               this.userLimitJson.push({userId:this.userIds[i],limitCount:100})
               console.log(this.userLimitJson)
             }
          }
      for (let i = 0; i < this.userLimitJson.length; i++) {
            if(!this.userIds.find(item => item== this.userLimitJson[i].userId)){
                this.userLimitJson.splice(i,1)
         }
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    addUserTime(){
      this.userTimeJson.push({userIds:null,userList:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null})
    },
    delUserTime(index){
      this.userTimeJson.splice(index,1)
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.closeWelcomeWord.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleCloseTag(row) {
      console.log(row)
        this.tagListForm.splice(this.tagListForm.indexOf(row), 1);
    },
    handleTags(){
      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.tagOpen = true;
    },

    addTagSubmitForm(){
      this.tagListForm=[];
      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.tagListForm.push(this.tagGroupList[i].tag[x].tagId)
          }
        }
      }
      if(this.tagListForm==[]||this.tagListForm==null||this.tagListForm==""){
        return  this.$message('请选择标签');
      }

      this.tagOpen = false;
    },
    addTagCancel() {
      this.tagOpen = false;
      this.tagListForm=null;
    },
    tagSelection(row){
      row.isSelected= !row.isSelected;
      this.$forceUpdate();
    },
    selectGroupScreen(row){
      this.queryParams.groupId=row
      this.getList();
    },
    getGroupList(row){
      this.groupList=row;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
              id: null,
              type: null,
              name: null,
              remark: null,
              skipVerify: null,
              state: null,
              userIds: null,
              addNum: null,
              deleteNum: null,
              num: null,
              qrCode: null,
              configId: null,
              isDel: null,
              createTime: null,
              companyId: null,
              isWelcome: 0,
              textContent: null,
              imagePicUrl: null,
              isUserLimit: 0,
              isSpanWelcome: 1,
              isCloseWelcome: 1,
              closeWelcomeWord: null,
              isTag: 0,
              tags: null,
              isRemark: 0,
              remarkStatus: 1,
              description: null,
              isDescription: 0,
              spareUserIds: null,
              groupId: null,
              userLimitJson: null,
              userTimeJson: null,
              userType: 2
            };
              this.userTimeJson=[{userIds:null,userList:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}];
              this.currentEditingTimeSlotIndex = -1;
              this.userLimitJson=[];
              this.userIds=[];
              this.userSelectList=[];
              this.spareUserIds=[];
              this.tagListForm=[];
              this.closeWelcomeWord=[];
              this.welcomeJson=[{text:{content:null},attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    sync(){
      sync(this.queryParams.corpId).then(response => {
      this.msgSuccess("同步");
      this.getList();
    });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.groupId=null
      this.handleQuery();
    },
    // 多选框选中数据
    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 = "添加企微活码";
      this.form.groupId=this.queryParams.groupId
    },



    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContactWay(id).then(response => {
        this.form = response.data;
        this.open = true;

        // 根据 userType 区分处理
        if(this.form.userType === 2) {
          // 自动上下线模式 - 只回显 userTimeJson
          if(this.form.userTimeJson!=null){
            this.userTimeJson=JSON.parse(this.form.userTimeJson)
            // 根据 userIds回显userList
            this.userTimeJson.forEach(timeSlot => {
              if (!timeSlot.userList) {
                timeSlot.userList = [];
              }
              if (timeSlot.userIds && Array.isArray(timeSlot.userIds)) {
                timeSlot.userList = timeSlot.userIds.map(qwUserId => {
                  return this.companyUserList.find(u => u.qwUserId === qwUserId);
                }).filter(u => u); // 过滤掉 undefined
              }
            });
          }else{
            this.userTimeJson=[{userIds:null,userList:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}]
          }
        } else if(this.form.userType === 1) {
          // 全天在线模式 - 只回显 userSelectList
          if(this.form.userIds!=null){
            this.userIds=JSON.parse(this.form.userIds)
            this.userSelectList = this.userIds.map(qwUserId => {
              return this.companyUserList.find(u => u.qwUserId === qwUserId);
            }).filter(u => u); // 过滤掉 undefined
          }else{
            this.userIds=[]
            this.userSelectList=[]
          }
        }

        if(this.form.userLimitJson!=null){
          this.userLimitJson=JSON.parse(this.form.userLimitJson)
        }else{ this.userLimitJson=[]}
        if(this.form.spareUserIds!=null){
          this.spareUserIds=JSON.parse(this.form.spareUserIds)
        }else{ this.spareUserIds=[]}
        if(this.form.tags!=null){
          this.tagListForm=JSON.parse(this.form.tags)
        }else{ this.tagListForm=[]}
        if(this.form.closeWelcomeWord!=null){
          this.closeWelcomeWord=JSON.parse(this.form.closeWelcomeWord)
        }else{ this.closeWelcomeWord=[]}
        if(this.form.welcomeJson!=null){
          this.welcomeJson=JSON.parse(this.form.welcomeJson)
        }else{ this.welcomeJson=[{text:{content:null},attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}] }
        this.title = "修改企微活码";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.corpId=this.queryParams.corpId
          if(this.form.userType === 1){
            if(Object.keys(this.userIds).length === 0){
              return this.$message({
                message: '请选择客服类型-使用员工',
                type: 'warning'
              });
            }
          }
          if(this.form.userType==2){
            var jsonUserIds=[];
            for (let i = 0; i < this.userTimeJson.length; i++) {
                // 确保 userIds 与 userList 同步
                if(this.userTimeJson[i].userList && this.userTimeJson[i].userList.length > 0){
                  this.userTimeJson[i].userIds = this.userTimeJson[i].userList.map(u => u.qwUserId);
                }

                if(this.userTimeJson[i].userIds==null||this.userTimeJson[i].userIds=="" || this.userTimeJson[i].userIds.length==0){
                  return this.$message('人员不能为空');
                }
                if(this.userTimeJson[i].week==null||this.userTimeJson[i].week==""){
                  return this.$message('日期不能为空');
                }
                if(this.userTimeJson[i].startTime==null||this.userTimeJson[i].startTime==""){
                  return this.$message('时间不能为空');
                }
                if(this.userTimeJson[i].endTime==null||this.userTimeJson[i].endTime==""){
                  return this.$message('时间不能为空');
                }

                for (let j = 0; j < this.userTimeJson[i].userIds.length; j++) {
                  if(!jsonUserIds.find(item=>item==this.userTimeJson[i].userIds[j])){
                    jsonUserIds.push(this.userTimeJson[i].userIds[j]);
                  }
                }
            }

            this.userIds=jsonUserIds;

          }
          this.form.closeWelcomeWord=JSON.stringify(this.closeWelcomeWord)
          this.form.userIds=JSON.stringify(this.userIds)
          // 提交前移除 userList 字段（因为后端只需要 userIds）
          const userTimeJsonForSubmit = this.userTimeJson.map(item => {
            const {userList, ...rest} = item;
            return rest;
          });
          this.form.userTimeJson=JSON.stringify(userTimeJsonForSubmit)
          this.form.userLimitJson=JSON.stringify(this.userLimitJson)
          this.form.spareUserIds=JSON.stringify(this.spareUserIds)
          this.form.tags=JSON.stringify(this.tagListForm)
          this.form.welcomeJson=JSON.stringify(this.welcomeJson)
          if (this.form.id != null) {
            updateContactWay(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContactWay(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 delContactWay(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企微活码数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportContactWay(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //选择企微员工时
    handleListUser(type, sendType, selectOne) {
      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.form.corpId, type, sendType, selectOne);
      }, 1);

      this.listUser.title = "选择企微员工"
      this.listUser.open = true;

    },
    //企业微信员工信息子组件返回
    selectUserList(list) {
      this.listUser.open = false;
      console.log("选择的员工",list)

      // 判断是全天在线还是自动上下线
      if (this.currentEditingTimeSlotIndex === -1) {
        // 全天在线模式
        list.forEach(obj => {
          if (!this.userSelectList.some(item => item.id === obj.id)) {
            this.userSelectList.push(obj);  // 存储完整对象
            this.userIds.push(obj.qwUserId);
          }
        });
      } else {
        // 自动上下线模式 - 为特定时间段添加员工
        const timeSlot = this.userTimeJson[this.currentEditingTimeSlotIndex];
        if (!timeSlot.userList) {
          this.$set(timeSlot, 'userList', []);
        }
        if (!timeSlot.userIds) {
          this.$set(timeSlot, 'userIds', []);
        }

        list.forEach(obj => {
          if (!timeSlot.userList.some(item => item.id === obj.id)) {
            timeSlot.userList.push(obj);
            timeSlot.userIds.push(obj.qwUserId);
          }
        });

        // 重置索引
        this.currentEditingTimeSlotIndex = -1;
      }
    },
    // 全天在线模式 - 删除员工标签
    handleCloseGroupUser(user) {
      const index = this.userSelectList.findIndex(t => t.id === user.id);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
        this.userIds.splice(index, 1);
      }
    },
    // 自动上下线模式 - 打开员工选择弹窗
    handleListUserForTimeSlot(timeSlotIndex) {
      this.currentEditingTimeSlotIndex = timeSlotIndex;
      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.form.corpId, this.form.type, this.form.sendType, true);
      }, 1);
      this.listUser.title = "选择企微员工"
      this.listUser.open = true;
    },
    // 自动上下线模式 - 删除时间段员工标签
    handleCloseTimeSlotUser(timeSlotIndex, user) {
      const timeSlot = this.userTimeJson[timeSlotIndex];
      const userListIndex = timeSlot.userList.findIndex(t => t.id === user.id);
      if (userListIndex !== -1) {
        // 使用 splice 删除并强制更新
        timeSlot.userList.splice(userListIndex, 1);
        timeSlot.userIds.splice(userListIndex, 1);
        // 强制更新整个 userTimeJson 数组以触发响应式更新
        this.$set(this.userTimeJson, timeSlotIndex, {...timeSlot});
      }
    },
  }
};
</script>
<style scoped>
</style>
<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;
}
/* 新增的滚动容器样式（不影响原有样式） */
.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>
