<template>
  <div class="app-container">

    <el-alert type="warning" :closable="false" show-icon>
      <template #title>
        <span style="font-size: 25px; line-height: 1.5;">
          {{ sourceType === 2
            ? '此功能用于给选中的SOP规则内【所有的】客户发送消息'
            : '此功能用于给选中的营期内【所有的】客户发送消息' }}
        </span>
      </template>
    </el-alert>

    <el-form
      ref="groupSendMessageForm"
      :model="groupSendMessageForm"
      :rules="groupSendRules"
      label-width="100px"
      style="margin-top: 8px;"
      :loading="loading"
    >
      <el-form-item label="科普"
        style="margin-bottom: 15px;"
        prop="videoId"
      >
        <!-- 禁用条件：操作类型为查看 -->
        <el-select
          v-model="groupSendMessageForm.courseId"
          placeholder="默认50条，可输入关键字检索"
          style=" margin-right: 10px;"
          size="mini"
          filterable
          clearable
          :loading="courseLoading"
          remote
          :remote-method="(keyword) => handleCourseRemoteSearch(keyword)"
          @change="courseChangeUpdate()"
        >
          <el-option
            v-for="dict in courseList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>

        <el-select
          v-model="groupSendMessageForm.videoId"
          placeholder="请选择小节"
          size="mini"
          style=" margin-right: 10px;"
          filterable
          clearable
          @change="videoIdChange()"
        >
          <el-option
            v-for="dict in videoList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          >
            <div :style="{ color: dict.isPause == 1 ? '#f56c6c' : 'inherit', display: 'flex', alignItems: 'center' }">
              <span>{{ dict.dictLabel }}</span>
              <span v-if="dict.isPause == 1" style="font-size: 12px; margin-left: 8px; color: #f56c6c;">
                  (该科普已被关闭，无法正常发送)
              </span>
            </div>
          </el-option>
        </el-select>

        <!-- 禁用条件：操作类型为查看 -->
        <!-- 渲染条件：消息类型不为AI触达 -->
        <el-select
          v-model="groupSendMessageForm.courseType"
          placeholder="请选择消息类型"
          size="mini"
          style=" margin-right: 10px;"
        >
          <el-option
            v-for="dict in sysFsSopWatchStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="Number(dict.dictValue)"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="规则" style="height: 500px; overflow: auto;">
        <!-- 遍历规则 所有内容【存在多个】 -->
        <div
          v-for="(content, contentIndex) in groupSendMessageForm.setting"
          :key="contentIndex"
          style="
            background-color: #fdfdfd;
            border: 1px solid #e6e6e6;
            margin-bottom: 20px;
          "
        >
          <el-row style="padding-bottom: 20px">
            <el-col :span="22">
              <el-form
                :model="content"
                label-width="100px"
              >
                <el-form-item label="内容类别"
                  style="margin: 2%"
                >
                  <div>
                    <el-radio-group
                      v-model="content.contentType"
                      @change="handleContentTypeChange()"
                    >
                      <el-radio
                        :key="item.dictValue"
                        :label="item.dictValue"
                        v-for="item in sysQwSopAiContentType"
                      >{{ item.dictLabel }}
                      </el-radio>
                    </el-radio-group>
                  </div>

                </el-form-item>

                <!-- 科普 -->
                <el-form-item label="内容" v-if="9 == content.contentType">

                  <div>
                    <el-card class="box-card">
                      <el-form-item label="链接标题:"
                        label-width="100px"
                        required
                      >
                        <el-input
                          v-model="content.linkTitle"
                          placeholder="请输入链接标题"
                          style="width: 90%;"
                        />
                      </el-form-item>
                      <el-form-item label="链接描述:"
                        label-width="100px"
                        required
                      >
                        <el-input
                          type="textarea"
                          :rows="3"
                          v-model="content.linkDescribe"
                          placeholder="请输入链接描述"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item label="链接封面:"
                        label-width="100px"
                        required
                      >
                        <ImageUpload
                          v-model="content.linkImageUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item label="链接地址:"
                        label-width="100px"
                      >
                        <el-tag
                          type="warning"
                          v-model="content.isBindUrl"
                        >选择的科普小节
                          即为卡片链接地址
                        </el-tag>
                      </el-form-item>
                      <el-form-item label="课节过期时间">
                        <el-row>
                          <el-input
                            type="number"
                            v-model="content.expiresDays"
                            style="width: 200px"
                          >
                            <template slot="append">天</template>
                          </el-input>
                        </el-row>
                        <el-row>
                          <span class="tip">填写0或不填时，默认为系统配置的默认时间</span>
                        </el-row>
                      </el-form-item>
                    </el-card>
                  </div>

                </el-form-item>

                <!-- 文本 -->
                 <el-form-item label="内容" v-else-if="11 == content.contentType">
                  <div
                    style="
                      color: #999;
                      font-size: 14px;
                      display: flex;
                      align-items: center;
                    "
                  >
                    <i class="el-icon-info"></i>
                    多语句分割符：|&| 例如：'语句1|&|语句2'
                  </div>
                  <el-input
                    v-model="content.value"
                    type="textarea"
                    :rows="3"
                    placeholder="内容"
                    style="width: 90%; margin-top: 10px;"
                    @keydown.native="handleKeydown($event, contentIndex)"
                    :ref="`textarea-${contentIndex}`"
                  />

                  <!-- 修改按钮部分 -->
                  <el-link
                    type="primary"
                    @click="toggleSalesCall(contentIndex)"
                    style="margin-top: 10px;"
                    >
                      {{ content.isSalesCallAdded ? '移除#客服称呼#' : '添加#客服称呼#' }}
                  </el-link>

                  <el-link
                    type="primary"
                    style="margin-top: 10px;margin-left:10px"
                    @click="showOpenContent(contentIndex)"
                  >
                    查看分割内容
                  </el-link>

                  <el-link
                    type="primary"
                    style="margin-top: 10px;margin-left:10px"
                    @click="copySpliter()"
                  >
                    复制分隔符
                  </el-link>

                </el-form-item>

                <!-- 语音 -->
                <el-form-item label="内容" v-else-if="12 == content.contentType">

                  <div>
                    <el-input
                      v-model="content.value"
                      type="textarea"
                      :rows="3"
                      maxlength="66"
                      show-word-limit
                      placeholder="输入要转为语音的内容"
                      style="width: 90%;margin-top: 10px;"
                      @input="handleInputVoiceText(content.value, content)"
                    />
                  </div>

                </el-form-item>

                <!-- 图片 -->
                <el-form-item label="内容" v-else-if="2 == content.contentType">

                  <ImageUpload
                    v-model="content.imgUrl"
                    type="image"
                    :num="1"
                    :width="150"
                    :height="150"
                  />

                </el-form-item>

                <!-- 视频 -->
                <el-form-item label="内容" v-else-if="6 == content.contentType">

                  <div>
                    <el-form-item
                      label="上传视频："
                      prop="videoUrl"
                      label-width="100px"
                    >
                      <el-upload
                        v-model="content.videoUrl"
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="(res, file) => handleSuccessVideo(res, file, content)"
                        :before-upload="beforeUploadVideo"
                      >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                      <video
                        v-if="content.videoUrl"
                        :src="content.videoUrl"
                        controls
                        style="width: 200px;height: 100px"
                      >
                      </video>
                    </el-form-item>
                  </div>

                </el-form-item>

                <!-- 疗法 -->
                <el-form-item label="内容" v-else-if="20 == content.contentType">

                  <el-card class="box-card">
                    <el-form-item
                      label="选择疗法:"
                      label-width="100px"
                      required
                    >
                      <el-select
                        v-model="content.packageId"
                        placeholder="默认50条，可输入关键字检索"
                        style=" margin-right: 10px; width: 230px;"
                        size="mini"
                        filterable
                        clearable
                        :loading="content.meta.pkgLoading"
                        remote
                        :remote-method="(keyword) => handlePkgRemoteSearch(keyword, content)"
                        @change="pkgChangeUpdate(content)"
                      >
                        <el-option
                          v-for="dict in (content.meta && content.meta.pkgList ? content.meta.pkgList : [])"
                          :key="dict.packageId"
                          :label="`${dict.packageName}(${dict.packageId})`"
                          :value="parseInt(dict.packageId)"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      label="疗法名称:"
                      label-width="100px"
                    >
                      <el-input
                        disabled
                        :rows="3"
                        v-model="content.packageName"
                        style="width: 90%;margin-top: 1%;"
                      />
                    </el-form-item>
                    <el-form-item
                      label="疗法封面:"
                      label-width="100px"
                    >
                      <ImageUpload
                        :disabled="true"
                        v-model="content.packageImgUrl"
                        type="image"
                        :num="1"
                        :file-size="1"
                        :width="150"
                        :height="150"
                        style="margin-top: 1%;"
                      />
                    </el-form-item>
                  </el-card>

                </el-form-item>

                <!-- 直播 -->
                <el-form-item label="内容" v-else-if="21 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item label="直播分组"
                        required
                      >
                        <el-select
                          v-model="content.liveGroupTypeId"
                          placeholder="请选择直播分组"
                          size="mini"
                          filterable
                          clearable
                          @change="liveGroupTypeChange(content)"
                        >
                          <el-option
                            v-for="dict in liveGroupTypeList"
                            :key="dict.id"
                            :label="dict.liveGroupType"
                            :value="dict.id"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="直播间"
                        required
                      >
                        <el-select
                          v-model="content.liveId"
                          placeholder="请先选择直播分组"
                          size="mini"
                          filterable
                          :disabled="!content.liveGroupTypeId"
                          @change="liveChange(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.liveList ? content.meta.liveList : [])"
                            :key="dict.liveId"
                            :label="dict.liveName"
                            :value="parseInt(dict.liveId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="标题"
                        prop="liveTitle"
                        style="margin-bottom: 5px;"
                      >
                        <el-input
                          v-model="content.liveTitle"
                          placeholder="请输入消息标题，最长为64字节"
                          :rows="2"
                          maxlength="64"
                          type="textarea"
                          disabled
                          @input="checkByteLength(content.contentType, 'liveTitle')"
                        />
                      </el-form-item>
                      <el-form-item label="封面"
                        prop="liveImgUrl"
                      >
                        <ImageUpload
                          v-model="content.liveImgUrl"
                          type="image"
                          :num="10"
                          :width="150"
                          :height="150"
                          disabled
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 民品 -->
                <el-form-item label="内容" v-else-if="22 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item
                        label="选择民品:"
                        label-width="100px"
                        required
                      >
                        <el-select
                          v-model="content.productId"
                          placeholder="默认50条，可输入关键字检索"
                          style=" margin-right: 10px; width: 230px;"
                          size="mini"
                          filterable
                          clearable
                          :loading="content.meta.productLoading"
                          remote
                          :remote-method="(keyword) => handleProductRemoteSearch(keyword, content)"
                          @change="productChangeUpdate(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.productList ? content.meta.productList : [])"
                            :key="dict.productId"
                            :label="`${dict.productName}(${dict.productId})`"
                            :value="parseInt(dict.productId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="民品名称:"
                        label-width="100px"
                      >
                        <el-input
                          disabled
                          :rows="3"
                          v-model="content.productName"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item
                        label="民品封面:"
                        label-width="100px"
                      >
                        <ImageUpload
                          :disabled="true"
                          v-model="content.productImgUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 药品 -->
                <el-form-item label="内容" v-else-if="23 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item
                        label="选择药品:"
                        label-width="100px"
                        required
                      >
                        <el-select
                          v-model="content.medicinesId"
                          placeholder="默认50条，可输入关键字检索"
                          style=" margin-right: 10px; width: 230px;"
                          size="mini"
                          filterable
                          clearable
                          :loading="content.meta.medicinesLoading"
                          remote
                          :remote-method="(keyword) => handleMedicinesRemoteSearch(keyword, content)"
                          @change="medicinesChangeUpdate(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.medicinesList ? content.meta.medicinesList : [])"
                            :key="dict.productId"
                            :label="`${dict.productName}(${dict.productId})`"
                            :value="parseInt(dict.productId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="药品名称:"
                        label-width="100px"
                      >
                        <el-input
                          disabled
                          :rows="3"
                          v-model="content.medicinesName"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item
                        label="药品封面:"
                        label-width="100px"
                      >
                        <ImageUpload
                          :disabled="true"
                          v-model="content.medicinesImgUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 短视频 -->
                <el-form-item label="内容" v-else-if="24 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item
                        label="选择短视频:"
                        label-width="100px"
                        required
                      >
                        <el-select
                          v-model="content.shortVideoId"
                          placeholder="默认50条，可输入关键字检索"
                          style=" margin-right: 10px; width: 230px;"
                          size="mini"
                          filterable
                          clearable
                          :loading="content.meta.shortVideoLoading"
                          remote
                          :remote-method="(keyword) => handleShortVideoRemoteSearch(keyword, content)"
                          @change="shortVideoChangeUpdate(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.shortVideoList ? content.meta.shortVideoList : [])"
                            :key="dict.videoId"
                            :label="`${dict.title}(${dict.videoId})`"
                            :value="parseInt(dict.videoId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="短视频名称:"
                        label-width="100px"
                      >
                        <el-input
                          disabled
                          :rows="3"
                          v-model="content.shortVideoName"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item
                        label="短视频封面:"
                        label-width="100px"
                      >
                        <ImageUpload
                          :disabled="true"
                          v-model="content.shortVideoImgUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 文章 -->
                <el-form-item label="内容" v-else-if="25 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item
                        label="选择文章:"
                        label-width="100px"
                        required
                      >
                        <el-select
                          v-model="content.articleId"
                          placeholder="默认50条，可输入关键字检索"
                          style=" margin-right: 10px; width: 230px;"
                          size="mini"
                          filterable
                          clearable
                          :loading="content.meta.articleLoading"
                          remote
                          :remote-method="(keyword) => handleArticleRemoteSearch(keyword, content)"
                          @change="articleChangeUpdate(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.articleList ? content.meta.articleList : [])"
                            :key="dict.articleId"
                            :label="`${dict.title}(${dict.articleId})`"
                            :value="parseInt(dict.articleId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="文章名称:"
                        label-width="100px"
                      >
                        <el-input
                          disabled
                          :rows="3"
                          v-model="content.articleName"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item
                        label="文章封面:"
                        label-width="100px"
                      >
                        <ImageUpload
                          :disabled="true"
                          v-model="content.articleImgUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 公开课 -->
                <el-form-item label="内容" v-else-if="26 == content.contentType">
                  <div>
                    <el-card class="box-card">
                      <el-form-item
                        label="选择公开课:"
                        label-width="100px"
                        required
                      >
                        <el-select
                          v-model="content.openClassVideoId"
                          placeholder="默认50条，可输入关键字检索"
                          style=" margin-right: 10px; width: 230px;"
                          size="mini"
                          filterable
                          clearable
                          :loading="content.meta.openClassVideoLoading"
                          remote
                          :remote-method="(keyword) => handleOpenClassVideoRemoteSearch(keyword, content)"
                          @change="openClassVideoChangeUpdate(content)"
                        >
                          <el-option
                            v-for="dict in (content.meta && content.meta.openClassVideoList ? content.meta.openClassVideoList : [])"
                            :key="dict.videoId"
                            :label="`${dict.title}(${dict.videoId})`"
                            :value="parseInt(dict.videoId)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="公开课名称:"
                        label-width="100px"
                      >
                        <el-input
                          disabled
                          :rows="3"
                          v-model="content.openClassVideoName"
                          style="width: 90%;margin-top: 1%;"
                        />
                      </el-form-item>
                      <el-form-item
                        label="公开课封面:"
                        label-width="100px"
                      >
                        <ImageUpload
                          :disabled="true"
                          v-model="content.openClassVideoImgUrl"
                          type="image"
                          :num="1"
                          :file-size="1"
                          :width="150"
                          :height="150"
                          style="margin-top: 1%;"
                        />
                      </el-form-item>
                    </el-card>
                  </div>
                </el-form-item>

                <!-- 舌诊：无实际内容 -->
                <!-- <el-form-item label="内容" v-else-if="27 == content.contentType">
                  <div>
                    <el-card class="box-card">

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

                <!-- 健康周报：无实际内容 -->
                <!-- <el-form-item label="内容" v-else-if="28 == content.contentType">
                  <div>
                    <el-card class="box-card">

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

              </el-form>
            </el-col>

            <el-col
              :span="1"
              :offset="1"
            >
              <!-- 删除内容节点 -->
              <i
                class="el-icon-delete"
                @click="delContentNode(contentIndex)"
                style="margin-top: 20px;"
                v-if="groupSendMessageForm.setting.length > 1"
              ></i>
            </el-col>
          </el-row>

        </div>
        <el-link type="primary" class="el-icon-plus" :underline="false" @click='addContent()'>添加内容</el-link>
      </el-form-item>

      <el-form-item label="发送时间类型" prop="sendTimeType">
        <el-radio-group v-model="groupSendMessageForm.sendTimeType">
          <el-radio :label="1">当天发送</el-radio>
          <el-radio :label="2">次日发送</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="发送时间" prop="time">
        <el-time-picker class="custom-input" v-model="groupSendMessageForm.time" value-format="HH:mm" format="HH:mm"
          placeholder="时间" style="width: 100px;height: 20px;">
        </el-time-picker>
        <span class="tip" style="margin-left: 2%"> 不填时，默认为系统当前时间(立即发送)</span>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button type="primary" @click="submitGroupSendMessage" :disabled="loading">确 定</el-button>
      <el-button @click="cancelGroupSendMessage">取 消</el-button>
    </div>

    <el-dialog
      title="查看分割后内容"
      :visible.sync="openShowContent"
      width="800px"
      append-to-body
    >
      <el-table
        stripe
        :data="contentListData"
        style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
          />

          <el-table-column
            prop="content"
            label="内容"
            width="700"
          >
            <template #default="{ row }">
              <div v-html="row.content.replace(/\n/g, '<br>')"></div>
            </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button
          type="primary"
          @click="comfirmContent"
        >确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ImageUpload from "@/views/qw/sop/ImageUpload.vue";
import {courseList, videoList} from "@/api/app/course";
import { getPackageOptions,} from "@/api/app/pkg";
import { groupSendMessage, } from '@/api/app/userLogs'
import { getLiveOptions as fetchLiveOptionsApi, getLiveGroupTypeList as fetchLiveGroupTypeListApi } from "@/api/app/live";
// import { getMedicinesOptions, } from "@/api/app/medicines";
// import { getProductOptions, } from "@/api/app/product";
// import { getShortVideoOptions, } from "@/api/app/shortVideo";
import { getArticleOptions } from "@/api/app/article";
import { getOpenClassVideoOptions, } from "@/api/app/openClassVideo";
import { getToken } from "@/utils/auth";

export default {
  name: "sendMsgOpenTool",
  components: { ImageUpload },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/app/common/uploadOSS2",
      uploadUrlByVoice: process.env.VUE_APP_BASE_API + "/app/common/uploadOSSByHOOKVoice",
      uploadHeaders: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: false,
      courseLoading: false,
      sysFsSopWatchStatus: [],
      isSalesCallAdded:false,
      isSalesCallCustomerAdded:false,
      courseList:[],
      videoList:[],
      pkgList: [],//默认疗法列表
      liveGroupTypeList: [],//直播分组
      liveList: [],//默认直播列表
      productList: [],//默认民品列表
      medicinesList: [],//默认药品列表
      shortVideoList: [],//默认短视频列表
      articleList: [],//默认文章列表
      openClassVideoList: [],//默认公开课列表
      sysQwSopAiContentType:[],
      groupSendMessageForm: {
        courseId: null,
        videoId: null,
        courseType: null,
        sendTimeType: 1,
        time: null,
        setting: [],
      },
      groupSendRules: {
        courseId: [
          { required: true, message: '科普/课节不能为空', trigger: 'blur' }
        ],
        videoId: [
          { required: true, message: '科普/课节不能为空', trigger: 'blur' }
        ],
        courseType: [
          { required: true, message: '消息类型', trigger: 'blur' }
        ]
      },
      openShowContent: false,
      contentList: [],
      contentListData: [],
    };
  },
  props: {
    visible: {
      default: false,
      type: Boolean,
    },
    ids: {
      default: () => [],
      type: Array,
    },
    sourceType: {
      default: 0,//0-营期的一键群发，1-营期详情的一键群发，2-SOP的一键群发
      type: Number,
    },
  },
  async created() {
    // 仅屏蔽民品/药品/短视频，直播(21)需要展示
    const disabledContentTypes = ['22', '23', '24'];
    this.getDicts("app_sop_plugin_settingType").then(response => {
      this.sysQwSopAiContentType = response.data.filter(
        item => !disabledContentTypes.includes(String(item.dictValue))
      );
    });
    this.getDicts("app_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });
    const [
      courseInfo,
      defaultPkg,
      defaultLiveGroup,
      defaultArticle,
      defaultOpenClassVideo,
    ] = await Promise.all([
      courseList(),
      this.getPkgList(null, null),
      this.fetchLiveGroupTypeList(),
      this.getArticleList(null, null),
      this.getOpenClassVideoList(null, null),
    ]);
    this.courseList = courseInfo.list;
    this.pkgList = defaultPkg.data;
    this.liveGroupTypeList = defaultLiveGroup.rows || defaultLiveGroup.data || [];
    this.articleList = defaultArticle.data;
    this.openClassVideoList = defaultOpenClassVideo.data;
    // const [
    //   courseInfo,
    //   defaultPkg,
    //   defaultLive,
    //   defaultProduct,
    //   defaultMedicines,
    //   defaultShortVideo,
    //   defaultArticle,
    //   defaultOpenClassVideo,
    // ] = await Promise.all([
    //   courseList(),
    //   this.getPkgList(null, null),
    //   this.fetchLiveOptionsByGroup(),
    //   this.getProductList(null, null),
    //   this.getMedicinesList(null, null),
    //   this.getShortVideoList(null, null),
    //   this.getArticleList(null, null),
    //   this.getOpenClassVideoList(null, null),
    // ]);
    // this.courseList = courseInfo.list;
    // this.pkgList = defaultPkg.data;
    // this.liveList = defaultLive.data;
    // this.productList = defaultProduct.data;
    // this.medicinesList = defaultMedicines.data;
    // this.shortVideoList = defaultShortVideo.data;
    // this.articleList = defaultArticle.data;
    // this.openClassVideoList = defaultOpenClassVideo.data;
  },
  watch: {
    visible: {
      handler(n, o) {
        //打开新建
        if (n) {
          this.addContent();
        }
        //关闭销毁
        else {
          this.resetForm();
        }
      },
      immediate: true,
    },
  },
  methods: {
    /**
     * 获取科普信息
     */
    async getCourseList(keyword, selectedId) {
      let data = {
        keyword: keyword,
        selectedId: selectedId,
        pageNum: 1,
        pageSize: 50,
      };
      return await courseList(data);
    },
    /**
     * 根据科普获取视频小节
     * @param courseId
     * @param title
     */
    async getVideoList(courseId, title) {
      return await videoList({
        courseId: courseId,
        title: title
      });
    },
    /**
     * 获取疗法信息
     */
    async getPkgList(keyword, selectedId) {
      let data = {
        keyword: keyword,
        metaId: selectedId,
        limit: 50
      };
      return await getPackageOptions(data);
    },
    /**
     * 获取直播分组下拉
     */
    async fetchLiveGroupTypeList() {
      return await fetchLiveGroupTypeListApi({ pageNum: 1, pageSize: 999 });
    },
    /**
     * 获取直播间信息
     * @param liveGroupType 直播分组id
     */
    async fetchLiveOptionsByGroup(liveGroupType) {
      if (!liveGroupType) {
        return { data: [] };
      }
      return await fetchLiveOptionsApi({ liveGroupType });
    },
    // /**
    //  * 获取民品列表
    //  * @param keyword
    //  * @param selectedId
    //  */
    // async getProductList(keyword, selectedId) {
    //   let data = {
    //     keyword: keyword,
    //     metaId: selectedId,
    //     limit: 50
    //   };
    //   return await getProductOptions(data);
    // },
    // /**
    //  * 获取药品列表
    //  * @param keyword
    //  * @param selectedId
    //  */
    // async getMedicinesList(keyword, selectedId) {
    //   let data = {
    //     keyword: keyword,
    //     metaId: selectedId,
    //     limit: 50
    //   };
    //   return await getMedicinesOptions(data);
    // },
    // /**
    //  * 获取短视频列表
    //  * @param keyword
    //  * @param selectedId
    //  */
    // async getShortVideoList(keyword, selectedId) {
    //   let data = {
    //     keyword: keyword,
    //     metaId: selectedId,
    //     limit: 50
    //   };
    //   return await getShortVideoOptions(data);
    // },
    /**
     * 获取文章列表
     * @param keyword
     * @param selectedId
     */
    async getArticleList(keyword, selectedId) {
      let data = {
        keyword: keyword,
        metaId: selectedId,
        limit: 50
      };
      return await getArticleOptions(data);
    },
    /**
     * 获取公开课列表
     * @param keyword
     * @param selectedId
     */
    async getOpenClassVideoList(keyword, selectedId) {
      let data = {
        keyword: keyword,
        metaId: selectedId,
        limit: 50
      };
      return await getOpenClassVideoOptions(data);
    },
    /**
     * 科普变动处理
     * @param ruleItem
     * @param dayIndex
     * @param ruleIndex
     */
    async courseChangeUpdate() {
      //将当前规则已选中的视频小节清空
      this.groupSendMessageForm.videoId = null;
      this.videoList = [];
      // 查找选中的科普的信息
      const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) == this.groupSendMessageForm.courseId);
      for (let i = 0; i < this.groupSendMessageForm.setting.length; i++) {
        let contentItem = this.groupSendMessageForm.setting[i];
        this.$set(contentItem, 'linkTitle', null);
        this.$set(contentItem, 'linkDescribe', null);
        this.$set(contentItem, 'linkImageUrl', null);

        //如果是科普才上
        if (selectedCourse && this.groupSendMessageForm.courseId) {
          //响应式直接给链接的标题/封面上值
          if (contentItem.contentType == 9) {
            this.$set(contentItem, 'linkTitle', selectedCourse.dictLabel);
            this.$set(contentItem, 'linkImageUrl', selectedCourse.dictImgUrl);
          }
        }
      }
      if (this.groupSendMessageForm.courseId) {
        let vl = await this.getVideoList(this.groupSendMessageForm.courseId, null);
        this.videoList = vl.list;
      } else {
        let cl = await this.getCourseList(null, null);
        this.courseList = cl.list;
      }
    },
    /**
     * 课程远程搜索
     */
    async handleCourseRemoteSearch(keyword) {
      this.courseLoading = true;
      // 模拟远程接口请求（替换为你的真实接口）
      let cl = await this.getCourseList(this.isEmpty(keyword) ? null : keyword, null);
      this.courseLoading = false;
      this.courseList = cl.list;
    },
    /**
     * 疗法下拉搜索
     * @param keyword
     * @param content
     */
    async handlePkgRemoteSearch(keyword, content) {
      content.meta.pkgLoading = true;
      let cl = await this.getPkgList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.pkgLoading = false;
      content.meta.pkgList = cl.data;
    },
    /**
     * 疗法变动处理
     * @param content
     */
    async pkgChangeUpdate(content) {
      //将当前规则已选中的视频小节清空
      this.$set(content, 'packageName', null);
      this.$set(content, 'packageImgUrl', null);
      if (content.packageId) {
        // 查找选中疗法的信息
        const selectedPkg = content.meta.pkgList.find(pkg => parseInt(pkg.packageId) === content.packageId);
        this.$set(content, 'packageName', selectedPkg.packageName);
        this.$set(content, 'packageImgUrl', selectedPkg.imgUrl);
      }
    },
    /**
     * 民品下拉搜索
     * @param keyword
     * @param content
     */
    async handleProductRemoteSearch(keyword, content) {
      content.meta.productLoading = true;
      let cl = await this.getProductList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.productLoading = false;
      content.meta.productList = cl.data;
    },
    /**
     * 民品变动处理
     * @param content
     */
    async productChangeUpdate(content) {
      this.$set(content, 'productName', null);
      this.$set(content, 'productImgUrl', null);
      if (content.productId) {
        // 查找选中民品的信息
        const selected = content.meta.productList.find(pro => parseInt(pro.productId) === content.productId);
        this.$set(content, 'productName', selected.productName);
        this.$set(content, 'productImgUrl', selected.image);
      }
    },
    /**
     * 药品下拉搜索
     * @param keyword
     * @param content
     */
    async handleMedicinesRemoteSearch(keyword, content) {
      content.meta.medicinesLoading = true;
      let cl = await this.getMedicinesList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.medicinesLoading = false;
      content.meta.medicinesList = cl.data;
    },
    /**
     * 药品变动处理
     * @param content
     */
    async medicinesChangeUpdate(content) {
      this.$set(content, 'medicinesName', null);
      this.$set(content, 'medicinesImgUrl', null);
      if (content.medicinesId) {
        // 查找选中药品的信息
        const selected = content.meta.medicinesList.find(pro => parseInt(pro.productId) === content.medicinesId);
        this.$set(content, 'medicinesName', selected.productName);
        this.$set(content, 'medicinesImgUrl', selected.image);
      }
    },
    /**
     * 短视频下拉搜索
     * @param keyword
     * @param content
     */
    async handleShortVideoRemoteSearch(keyword, content) {
      content.meta.shortVideoLoading = true;
      let cl = await this.getShortVideoList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.shortVideoLoading = false;
      content.meta.shortVideoList = cl.data;
    },
    /**
     * 短视频变动处理
     * @param content
     */
    async shortVideoChangeUpdate(content) {
      this.$set(content, 'shortVideoName', null);
      this.$set(content, 'shortVideoImgUrl', null);
      if (content.shortVideoId) {
        // 查找选中短视频的信息
        const selected = content.meta.shortVideoList.find(pro => parseInt(pro.videoId) === content.shortVideoId);
        this.$set(content, 'shortVideoName', selected.title);
        this.$set(content, 'shortVideoImgUrl', selected.thumbnail);
      }
    },
    /**
     * 文章下拉搜索
     * @param keyword
     * @param content
     */
    async handleArticleRemoteSearch(keyword, content) {
      content.meta.articleLoading = true;
      let cl = await this.getArticleList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.articleLoading = false;
      content.meta.articleList = cl.data;
    },
    /**
     * 文章变动处理
     * @param content
     */
    async articleChangeUpdate(content) {
      this.$set(content, 'articleName', null);
      this.$set(content, 'articleImgUrl', null);
      if (content.articleId) {
        // 查找选中文章的信息
        const selected = content.meta.articleList.find(pro => parseInt(pro.articleId) === content.articleId);
        this.$set(content, 'articleName', selected.title);
        this.$set(content, 'articleImgUrl', selected.imageUrl);
      }
    },
    /**
     * 公开课下拉搜索
     * @param keyword
     * @param content
     */
    async handleOpenClassVideoRemoteSearch(keyword, content) {
      content.meta.openClassVideoLoading = true;
      let cl = await this.getOpenClassVideoList(this.isEmpty(keyword) ? null : keyword, null);
      content.meta.openClassVideoLoading = false;
      content.meta.openClassVideoList = cl.data;
    },
    /**
     * 公开课变动处理
     * @param content
     */
    async openClassVideoChangeUpdate(content) {
      this.$set(content, 'openClassVideoName', null);
      this.$set(content, 'openClassVideoImgUrl', null);
      if (content.openClassVideoId) {
        // 查找选中文章的信息
        const selected = content.meta.openClassVideoList.find(pro => parseInt(pro.videoId) === content.openClassVideoId);
        this.$set(content, 'openClassVideoName', selected.title);
        this.$set(content, 'openClassVideoImgUrl', selected.thumbnail);
      }
    },
    /**
     * 直播分组切换
     * @param content
     */
    async liveGroupTypeChange(content) {
      this.$set(content, 'liveId', null);
      this.$set(content, 'liveTitle', null);
      this.$set(content, 'liveImgUrl', null);
      if (!content.liveGroupTypeId) {
        this.$set(content, 'meta', {
          ...(content.meta || {}),
          liveLoading: false,
          liveList: [],
        });
        return;
      }
      this.$set(content, 'meta', {
        ...(content.meta || {}),
        liveLoading: true,
        liveList: [],
      });
      const liveRes = await this.fetchLiveOptionsByGroup(content.liveGroupTypeId);
      this.$set(content, 'meta', {
        ...(content.meta || {}),
        liveLoading: false,
        liveList: liveRes.data || liveRes.rows || [],
      });
    },
    /**
     * 直播间切换
     * @param content
     */
    liveChange(content) {
      content.liveTitle = null;
      content.liveImgUrl = null;
      const list = (content.meta && content.meta.liveList) ? content.meta.liveList : [];
      const selectedLive = list.find(live => parseInt(live.liveId) === parseInt(content.liveId));
      if (selectedLive) {
        content.liveTitle = selectedLive.liveName; // 自动填充标题
        content.liveImgUrl = selectedLive.liveImgUrl; // 自动填充封面
      }
    },
    /**
     * 科普小节变化
     * @param ruleItem
     * @param dayIndex
     * @param ruleIndex
     */
    videoIdChange() {
      //选择了科普小节则 默认绑上
      let selectedVideo;
      // 查找选中的科普对应的 label
      if (this.groupSendMessageForm.videoId) {
        selectedVideo = this.videoList.find(course => parseInt(course.dictValue) == this.groupSendMessageForm.videoId);
      }
      for (let i = 0; i < this.groupSendMessageForm.setting.length; i++) {
        let contentItem = this.groupSendMessageForm.setting[i];
        //科普消息-文本内容
        if (contentItem == 11) {
          this.$set(contentItem, 'isBindUrl', '2');
        }
        //如果是科普的才上
        if (selectedVideo && this.groupSendMessageForm.videoId != null) {

          if (contentItem.contentType == 9) {
            this.$set(contentItem, 'linkDescribe', selectedVideo.dictLabel);
          }
        }
      }
    },
    /**
     * 上传视频成功处理
     * @param res
     * @param file
     * @param item
     */
    handleSuccessVideo(res, file, item) {
      if(res.code == 200) {
        // 使用 $set 确保响应式更新
        this.$set(item, 'videoUrl', res.url);
      }
      else{
        this.msgError(res.msg);
      }
    },
    /**
     * 上传视频前置处理
     * @param file
     */
    beforeUploadVideo(file){
      const isLt30M = file.size / 1024 / 1024 < 10;
      const fileName = (file.name || '').toLowerCase();
      const isMP4 = file.type === 'video/mp4' || fileName.endsWith('.mp4');
      if (!isMP4) {
        this.$message.error('仅支持上传 MP4 格式的视频文件!');
        return false;
      }
      if (!isLt30M) {
        this.$message.error('上传大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    /**
     * 语音文本录入
     * @param value
     * @param content
     */
    handleInputVoiceText(value,content){
      // 允许的字符：中文、英文（大小写）、数字和指定标点符号（，。！？）
      const regex = /^[\u4e00-\u9fa5a-zA-Z0-9，。！？,!?]+$/;
      // 删除不符合条件的字符
      const filteredValue = value.split('').filter(char => regex.test(char)).join('');
      this.$set(content, 'value', filteredValue);
    },
    /**
     * 删除内容节点
     * @param index
     */
    delContentNode(index){
      this.groupSendMessageForm.setting.splice(index, 1)
    },
    /**
     * 添加规则内容
     */
    addContent() {
      let content = {
        contentType: '9',//默认科普类型
        value: '',
      };
      this.groupSendMessageForm.setting.push(content);
      this.handleContentTypeChange();
    },
    /**
     *
     * @param event
     * @param index
     */
    handleKeydown(event, index) {
      const item = this.groupSendMessageForm.setting[index];
      const textarea = this.$refs[`textarea-${index}`][0].$refs.textarea;
      const cursorPosition = textarea.selectionStart;
      // 检查是否按下了 Backspace 或 Delete 键
      if (event.key === 'Backspace' || event.key === 'Delete') {
        const tags = ['#客服称呼#', '#客户称呼#']; // 需要检查的标签
        const value = item.value;
        // 遍历标签，检查是否需要删除
        for (const tag of tags) {
          let start, end;
          if (event.key === 'Backspace') {
            // 检查光标前是否是当前标签的一部分
            start = cursorPosition - tag.length;
            if (start >= 0 && value.slice(start, cursorPosition) === tag) {
              // 删除整个标签
              item.value = value.slice(0, start) + value.slice(cursorPosition);
              // 更新光标位置
              this.$nextTick(() => {
                textarea.setSelectionRange(start, start);
              });
              // 更新状态
              if (tag === '#客服称呼#') {
                item.isSalesCallAdded = false;
              }
              if (tag === '#客户称呼#') {
                item.isSalesCallCustomerAdded = false;
              }
              event.preventDefault(); // 阻止默认删除行为
              break; // 找到匹配的标签后退出循环
            }
          } else if (event.key === 'Delete') {
            // 检查光标后是否是当前标签的一部分
            end = cursorPosition + tag.length;
            if (end <= value.length && value.slice(cursorPosition, end) === tag) {
              // 删除整个标签
              item.value = value.slice(0, cursorPosition) + value.slice(end);
              // 更新状态
              if (tag === '#客服称呼#') {
                item.isSalesCallAdded = false;
              }
              if (tag === '#客户称呼#') {
                item.isSalesCallCustomerAdded = false;
              }
              event.preventDefault(); // 阻止默认删除行为
              break; // 找到匹配的标签后退出循环
            }
          }
          // 检查光标是否位于标签的中间
          for (let i = 0; i <= tag.length; i++) {
            const tagStart = cursorPosition - i;
            const tagEnd = tagStart + tag.length;
            if (
              tagStart >= 0 &&
              tagEnd <= value.length &&
              value.slice(tagStart, tagEnd) === tag
            ) {
              // 删除整个标签
              item.value = value.slice(0, tagStart) + value.slice(tagEnd);
              // 更新光标位置
              this.$nextTick(() => {
                textarea.setSelectionRange(tagStart, tagStart);
              });
              // 更新状态
              if (tag === '#客服称呼#') {
                item.isSalesCallAdded = false;
              }
              if (tag === '#客户称呼#') {
                item.isSalesCallCustomerAdded = false;
              }
              event.preventDefault(); // 阻止默认删除行为
              break; // 找到匹配的标签后退出循环
            }
          }
        }
      }
    },
    /**
     * 切换添加客服称呼按钮点击事件
     * @param index
     */
    toggleSalesCall(index) {
      const item = this.groupSendMessageForm.setting[index];
      const salesCall = '#客服称呼#';
      const textarea = this.$refs[`textarea-${index}`][0].$refs.textarea;

      // 获取当前光标位置
      const cursorPosition = textarea.selectionStart;

      if (item && !Object.hasOwn(item, 'isSalesCallAdded')) {
        this.$set(item, 'isSalesCallAdded', false);
      }

      if (item.isSalesCallAdded) {
        // 移除所有的 #客服称呼#
        item.value = item.value.replace(new RegExp(salesCall, 'g'), '');
      } else {
        // 添加 #客服称呼#
        item.value = item.value.slice(0, cursorPosition) + salesCall + item.value.slice(cursorPosition);
      }

      // 切换状态
      item.isSalesCallAdded = !item.isSalesCallAdded;

      // 保持光标位置
      this.$nextTick(() => {
        textarea.setSelectionRange(cursorPosition, cursorPosition);
      });
    },
    /**
     * 修改内容类别，避免万一，把所有的content刷一遍
     */
    handleContentTypeChange() {
      const form = this.groupSendMessageForm;
      //科普
      const course = this.courseList.find(c => parseInt(c.dictValue) == form.courseId);
      //课节
      const video = this.videoList.find(v => parseInt(v.dictValue) == form.videoId);
      form.setting.forEach(async item => {
        //科普
        if (item.contentType == 9) {
          course && this.$set(item, 'linkTitle', course.dictLabel);
          course && this.$set(item, 'linkImageUrl', course.dictImgUrl);
          video && this.$set(item, 'linkDescribe', video.dictLabel);
        }
        //疗法
        else if(item.contentType == 20) {
          if (!item.packageId) {
            this.$set(item, 'meta', {
              pkgLoading: false,
              pkgList: this.pkgList,
            });
          } else {
            let pkgList = await this.getPkgList(null, item.packageId);
            this.$set(item, 'meta', {
              pkgLoading: false,
              pkgList: pkgList.data,
            });
          }
        }
        //直播
        else if(item.contentType == 21) {
          if (item.liveGroupTypeId) {
            let liveRes = await this.fetchLiveOptionsByGroup(item.liveGroupTypeId);
            this.$set(item, 'meta', {
              liveLoading: false,
              liveList: liveRes.data || liveRes.rows || [],
            });
          } else {
            this.$set(item, 'meta', {
              liveLoading: false,
              liveList: [],
            });
          }
        }
        // //民品
        // else if(item.contentType == 22) {
        //   if (!item.productId) {
        //     this.$set(item, 'meta', {
        //       productLoading: false,
        //       productList: this.productList,
        //     });
        //   } else {
        //     let productList = await this.getProductList(null, item.productId);
        //     this.$set(item, 'meta', {
        //       productLoading: false,
        //       productList: productList.data,
        //     });
        //   }
        // }
        // //药品
        // else if(item.contentType == 23) {
        //   if (!item.medicinesId) {
        //     this.$set(item, 'meta', {
        //       medicinesLoading: false,
        //       medicinesList: this.medicinesList,
        //     });
        //   } else {
        //     let medicinesList = await this.getMedicinesList(null, item.medicinesId);
        //     this.$set(item, 'meta', {
        //       medicinesLoading: false,
        //       medicinesList: medicinesList.data,
        //     });
        //   }
        // }
        // //短视频
        // else if(item.contentType == 24) {
        //   if (!item.shortVideoId) {
        //     this.$set(item, 'meta', {
        //       shortVideoLoading: false,
        //       shortVideoList: this.shortVideoList,
        //     });
        //   } else {
        //     let shortVideoList = await this.getShortVideoList(null, item.shortVideoId);
        //     this.$set(item, 'meta', {
        //       shortVideoLoading: false,
        //       shortVideoList: shortVideoList.data,
        //     });
        //   }
        // }
        //文章
        else if(item.contentType == 25) {
          if (!item.articleId) {
            this.$set(item, 'meta', {
              articleLoading: false,
              articleList: this.articleList,
            });
          } else {
            let articleList = await this.getArticleList(null, item.articleId);
            this.$set(item, 'meta', {
              articleLoading: false,
              articleList: articleList.data,
            });
          }
        }
        //公开课
        else if(item.contentType == 26) {
          if (!item.openClassVideoId) {
            this.$set(item, 'meta', {
              openClassVideoLoading: false,
              openClassVideoList: this.openClassVideoList,
            });
          } else {
            let openClassVideoList = await this.getOpenClassVideoList(null, item.openClassVideoId);
            this.$set(item, 'meta', {
              openClassVideoLoading: false,
              openClassVideoList: openClassVideoList.data,
            });
          }
        }
        //舌诊
        else if(item.contentType == 27) {

        }
        //健康周报
        else if(item.contentType == 28) {

        }
      })
    },
    /**
     * 检查数据
     */
    checkData() {
      if (this.isEmpty(this.groupSendMessageForm.courseId)) {
        return this.$message.error("科普不能为空")
      }
      if (this.isEmpty(this.groupSendMessageForm.videoId)) {
        return this.$message.error("课节不能为空")
      }
      if (this.isEmpty(this.groupSendMessageForm.courseType)) {
        return this.$message.error("消息类型不能为空")
      }
      let contentList = this.groupSendMessageForm.setting;
      if (contentList.length === 0) {
        return this.$message.error("请添加规则")
      }
      for (let k = 0; k < contentList.length; k++) {
        let dcs = contentList[k];
        if (dcs.contentType == 11 && this.isEmpty(dcs.value)) {
          return this.$message.error("内容不能为空");
        }
        if (dcs.contentType == 12 && this.isEmpty(dcs.value)) {
          return this.$message.error("语音文本不能为空");
        }
        if (dcs.contentType == 2 && this.isEmpty(dcs.imgUrl)) {
          return this.$message.error("图片不能为空");
        }
        if ([9].includes(Number(dcs.contentType)) && this.isEmpty(dcs.linkTitle)) {
          return this.$message.error("链接标题不能为空");
        }
        if ([9].includes(Number(dcs.contentType)) && this.isEmpty(dcs.linkDescribe)) {
          return this.$message.error("链接描述不能为空");
        }
        if ([9].includes(Number(dcs.contentType)) && this.isEmpty(dcs.linkImageUrl)) {
          return this.$message.error("链接图片不能为空");
        }
        if ([20].includes(Number(dcs.contentType)) && this.isEmpty(dcs.packageId)) {
          return this.$message.error("疗法不能为空");
        }
        if ([21].includes(Number(dcs.contentType)) && this.isEmpty(dcs.liveGroupTypeId)) {
          return this.$message.error("直播分组不能为空");
        }
        if ([21].includes(Number(dcs.contentType)) && this.isEmpty(dcs.liveId)) {
          return this.$message.error("直播间不能为空");
        }
        // if ([22].includes(Number(dcs.contentType)) && this.isEmpty(dcs.productId)) {
        //   return this.$message.error("民品不能为空");
        // }
        // if ([23].includes(Number(dcs.contentType)) && this.isEmpty(dcs.medicinesId)) {
        //   return this.$message.error("药品不能为空");
        // }
        // if ([24].includes(Number(dcs.contentType)) && this.isEmpty(dcs.shortVideoId)) {
        //   return this.$message.error("短视频不能为空");
        // }
        if ([25].includes(Number(dcs.contentType)) && this.isEmpty(dcs.articleId)) {
          return this.$message.error("文章不能为空");
        }
        if ([26].includes(Number(dcs.contentType)) && this.isEmpty(dcs.openClassVideoId)) {
          return this.$message.error("公开课不能为空");
        }
      }
      if (this.groupSendMessageForm.sendTimeType == 2 && this.isEmpty(this.groupSendMessageForm.time)) {
        return this.$message.error("请指定次日发送时间")
      }
      return 1;
    },
    /**
     * 空校验
     * @param obj
     */
    isEmpty(obj) {
      return obj === null || obj === undefined || obj.length === 0;
    },
    /**
     * 确认一键群发
     */
    submitGroupSendMessage() {
      // 表单验证
      this.loading = true;
      this.$refs["groupSendMessageForm"].validate(async valid => {
        if (valid) {
          if (this.checkData() !== 1) {
            this.loading = false;
            return;
          }
          let params = {...this.groupSendMessageForm, ids: this.ids};
          params['sourceType'] = this.sourceType;
          let res = await groupSendMessage(params);
          this.msgSuccess("一键群发成功");
          this.$emit('changeGroupSendMessageVisible', false);
        }
        this.loading = false;
      });
    },
    /**
     * 取消一键群发
     */
    cancelGroupSendMessage() {
      this.$emit('changeGroupSendMessageVisible', false);
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.groupSendMessageForm = {
        courseId: null,
        videoId: null,
        courseType: null,
        sendTimeType: 1,
        time: null,
        setting: [],
      };
    },
    /**
     * 确认分割后的内容
     */
    comfirmContent() {
      this.openShowContent = false;
    },
    /**
     * 显示分割后的内容
     * @param contentIndex
     */
    showOpenContent(contentIndex) {
      let setItem = this.groupSendMessageForm.setting[contentIndex];
      let refKey = `textarea-${contentIndex}`;
      let textarea = this.$refs[refKey][0]?.$refs?.textarea;
      if (!textarea) return;
      this.openShowContent = true;
      this.contentList = [];
      this.contentListData = [];
      let str = setItem.value;
      this.contentList = str.split("|&|");
      let idx = 1;
      this.contentList.forEach(a => {
        this.contentListData.push({ index: idx++, content: a });
      })
    },
    /**
     * 复制分隔符
     */
    copySpliter() {
      navigator.clipboard.writeText("|&|").then(() => {
        this.$message({
          message: '复制成功',
          type: 'success'
        });
      }).catch(err => {
        this.$message({
          message: '复制失败',
          type: 'warning'
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 8px;

  .el-alert {
    padding: 5px 16px;
  }
}
</style>
