<template>
  <div class="app-container">
    <el-dialog :title="sendMsgOpen.title" :visible.sync="sendMsgOpen.open"  width="1000px" append-to-body>
        <el-alert
          type="error"
          :closable="false"
          show-icon>
          <template #title>
                <span style="font-size: 25px; line-height: 1.5;">
                    此功能用于给 选中的 营期 内【所有的】客户发送 消息
                </span>
          </template>
        </el-alert>
        <el-form ref="msgForm" :model="msgForm" :rules="msgRules" label-width="100px">
          <el-form-item label="策略" prop="draftStrategy">
            <el-radio-group v-model="msgForm.draftStrategy">
              <el-radio :label="1">正常群发</el-radio>
              <el-radio :label="2">清除草稿</el-radio>
              <el-radio :label="3">发送草稿</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="选择科普" v-if="msgForm.draftStrategy==1" >
            <el-select  v-model="msgForm.courseId" placeholder="请选择科普" style=" margin-right: 10px;" size="mini"  @change="courseChange()">
              <el-option
                v-for="dict in courseList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
            <el-select  v-model="msgForm.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange()"  >
              <el-option
                v-for="dict in videoList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
                :disabled="dict.isPause == 1"
              >
                <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>
            <el-select  v-model="msgForm.courseType" placeholder="请选择消息类型" size="mini" style=" margin-right: 10px;">
              <el-option
                v-for="dict in sysFsSopWatchStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规则" prop="setting" v-if="msgForm.draftStrategy==1"  >
            <div v-for="(item, index) in setting" :key="index" style="background-color: #fdfdfd; border: 1px solid #e6e6e6; margin-bottom: 20px;">
              <el-row>
                <el-col :span="22">
                  <el-form :model="item" label-width="70px">
                    <el-form-item label="内容类别" style="margin: 2%">
                      <el-radio-group  v-model="item.contentType">
                        <el-radio   :label="items.dictValue" v-for="items in sysQwSopAiContentType" v-if="items.dictValue !== '19' || (items.dictValue === '19' && item.openClass=== 1)"   @change="handleContentTypeChange()">{{items.dictLabel}}</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="内容" style="margin-bottom: 2%" >
                      <el-input
                        v-if="item.contentType == 1 || item.contentType == 11|| item.contentType == 13"
                        v-model="item.value"
                        type="textarea"
                        :rows="3"
                        placeholder="内容"
                        style="width: 90%; margin-top: 10px;"
                        @keydown.native="handleKeydown($event, index)"
                        :ref="`textarea-${index}`"
                      >
                      </el-input>
                      <el-link
                        v-if="item.contentType == 1 || item.contentType == 11 || item.contentType == 13"
                        type="primary"
                        @click="toggleSalesCall(index)"
                        style="margin-top: 10px;"
                      >
                        {{ item.isSalesCallAdded ? '移除#客服称呼#' : '添加#客服称呼#' }}
                      </el-link>
                      <el-link
                        v-if="item.contentType == 1 || item.contentType == 11|| item.contentType == 13"
                        type="primary"
                        @click="toggleSalesCallCustomer(index)"
                        style="margin-top: 10px;margin-left: 2%"
                      >
                        {{ item.isSalesCallCustomerAdded ? '移除#客户称呼#' : '添加#客户称呼#' }}
                      </el-link>


                      <ImageUpload v-if="item.contentType == 2 " v-model="item.imgUrl" type="image" :num="1"  :width="150" :height="150" />

                      <div v-if="item.contentType == 3 || item.contentType ==9 ">
                        <el-card class="box-card">
                          <el-form-item label="链接标题:"  label-width="100px">
                            <el-input v-model="item.linkTitle" placeholder="请输入链接标题" style="width: 90%;"/>
                          </el-form-item>
                          <el-form-item label="链接描述:"   label-width="100px" >
                            <el-input type="textarea" :rows="3" v-model="item.linkDescribe" placeholder="请输入链接描述" style="width: 90%;margin-top: 1%;"/>
                          </el-form-item>
                          <el-form-item label="链接封面:"   label-width="100px">
                            <ImageUpload v-model="item.linkImageUrl" type="image" :num="1" :file-size="2" :width="150" :height="150" style="margin-top: 1%;" />
                          </el-form-item>
                          <el-form-item label="链接地址:"  label-width="100px" >
                            <el-tag type="warning" v-model="item.isBindUrl" value = "1">选择的科普小节 即为卡片链接地址</el-tag>
                          </el-form-item>
                        </el-card>
                      </div>
                      <div v-if="item.contentType == 4 || item.contentType == 15|| item.contentType == 19">
                        <el-card class="box-card">
                          <el-form-item label="标题" prop="miniprogramTitle">
                            <el-input v-model="item.miniprogramTitle" placeholder="请输入小程序消息标题，最长为64字"  />
                          </el-form-item>
                          <el-form-item label="封面" prop="miniprogramPicUrl">
                            <ImageUpload v-model="item.miniprogramPicUrl"  type="image" :num="10" :width="150" :height="150" />
                          </el-form-item>
                          <el-form-item label="appid" prop="miniprogramAppid" v-show="false" >
                            <el-input v-model="item.miniprogramAppid" value = 'wx73f85f8d62769119' disabled />
                          </el-form-item>
                          <el-form-item label="page路径" prop="miniprogramPage" v-show="false" label-width="100px" style="margin-left: -30px" >
                            <el-input v-model="item.miniprogramPage" placeholder="小程序消息打开后的路径"  disabled />
                          </el-form-item>
                        </el-card>
                      </div>
                      <div v-if="item.contentType == 5 ">

                        <el-form-item label="上传文件:" prop="fileUrl" label-width="100px">
                          <el-upload
                            v-model="item.fileUrl"
                            class="avatar-uploader"
                            :action="uploadUrl"
                            :show-file-list="false"
                            :on-success="(res, file) => handleAvatarSuccessFile(res, file, item)"
                            :before-upload="beforeAvatarUploadFile">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                          <el-link v-if="item.fileUrl" type="primary" :href="downloadUrl(item.fileUrl)" download>
                            {{item.fileUrl}}
                          </el-link>
                        </el-form-item>

                      </div>

                      <div v-if="item.contentType == 6 ">
                        <el-form-item label="上传视频：" prop="videoUrl" label-width="100px">
                          <el-upload
                            v-model="item.videoUrl"
                            class="avatar-uploader"
                            :action="uploadUrl"
                            :show-file-list="false"
                            :on-success="(res, file) => handleAvatarSuccessVideo(res, file, item)"
                            :before-upload="beforeAvatarUploadVideo">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                          <video v-if="item.videoUrl"
                                 :src="item.videoUrl"
                                 controls style="width: 200px;height: 100px">
                          </video>
                        </el-form-item>
                      </div>
                      <div v-if="item.contentType == 7 || item.contentType == 12">
                        <el-input
                          v-model="item.value"
                          type="textarea" :rows="3" maxlength="66" show-word-limit
                          placeholder="输入要转为语音的内容" style="width: 90%;margin-top: 10px;"
                          @input="handleInputVideoText(item.value,item)"/>
                      </div>
                      <div v-if="item.contentType == 8">
                          <el-button type="primary"
                                     style="margin-bottom: 1%"
                                     @click="hanldeSelectVideoNum(setting,index)">
                            选择视频号
                          </el-button>
                          <el-card class="box-card" v-if="item.coverUrl">
                            <el-form-item label="封面标题:" label-width="100px">
                              <el-input v-model="item.nickname"
                                        style="width: 90%;margin-bottom: 1%" disabled/>
                            </el-form-item>
                            <el-form-item label="头像:" label-width="100px">
                              <el-image
                                v-if="item.avatar != null"
                                :src="item.avatar"
                                :preview-src-list="[item.avatar]"
                                :style="{ width: '50px', height: '50px' }"
                              ></el-image>
                            </el-form-item>
                            <el-form-item label="封面:" label-width="100px">
                              <el-image
                                v-if="item.coverUrl != null"
                                :src="item.coverUrl"
                                :preview-src-list="[item.coverUrl]"
                                :style="{ width: '200px', height: '200px' }"
                              ></el-image>

                            </el-form-item>
                            <el-form-item label="简介:" label-width="100px">
                              <el-input type="textarea" :rows="3"
                                        v-model="item.desc"
                                        style="width: 90%;margin-top: 1%;" disabled/>
                            </el-form-item>
                            <el-form-item label="视频地址:" label-width="100px"
                                          style="margin-top: 1%">
                              <el-input v-model="item.url"
                                        style="width: 90%;" disabled/>
                            </el-form-item>
                          </el-card>
                      </div>

                      <div v-if="item.contentType == 14">
                        <el-card class="box-card">
                          <el-form-item label="福袋名称" >
                            <el-select  v-model="item.luckyBagId"
                                        placeholder="请选择福袋" size="mini"
                                        @change="getLuckyBagStatus(item)" >
                              <el-option
                                v-for="dict in luckyBagList"
                                :key="dict.id"
                                :label="dict.name"
                                :value="dict.id"
                              />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="福袋状态" >
                            <el-tag :type="item.luckyBagDataStatus == 1 ? 'success' : 'danger'">
                              {{ item.luckyBagDataStatus == 1 ? '启用' : '禁用' }}
                            </el-tag>
                          </el-form-item>
                        </el-card>
                      </div>

                      <div v-if="item.contentType == 17">
                        <el-card class="box-card">
                          <el-form-item label="短信模板" >
                            <el-select v-model="item.smsTemplateId"
                                       placeholder="请选择短信模板" size="mini"
                                       @change="getSmsTemplateInfo(item)" >
                              <el-option
                                v-for="template in smsTemplateList"
                                :key="template.tempId"
                                :label="template.title"
                                :value="template.tempId"
                              />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="内容预览" v-if="item.smsTemplateContent">
                            <div style="color: #666; font-size: 12px; padding: 8px; border: 1px solid #eee; border-radius: 4px; background-color: #f9f9f9; max-height: 100px; overflow-y: auto;">
                              {{ item.smsTemplateContent }}
                            </div>
                          </el-form-item>
                        </el-card>
                      </div>

                    </el-form-item>
                    <div v-if="item.contentType == 20">
                      <!--                                           <div >-->
                      <el-card class="box-card">
                        <el-form-item label="直播分组" required>
                          <el-select
                            v-model="item.liveGroupTypeId"
                            placeholder="请选择直播分组"
                            size="mini"
                            filterable
                            clearable
                            @change="liveGroupTypeChange(item)"
                          >
                            <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="item.liveId"
                            placeholder="请先选择直播分组"
                            size="mini"
                            filterable
                            :disabled="!item.liveGroupTypeId"
                            @change="liveChange(item)"
                          >
                            <el-option
                              v-for="dict in (item.meta && item.meta.liveList ? item.meta.liveList : [])"
                              :key="dict.liveId"
                              :label="dict.liveName"
                              :value="dict.liveId"
                            />
                          </el-select>
                        </el-form-item>

                        <el-form-item label="标题" prop="miniprogramTitle">
                          <el-input v-model="item.miniprogramTitle" placeholder="请输入小程序消息标题，最长为64字节" :rows="2" maxlength="64"
                                    type="textarea"   @input="checkLiveMiniprogramTitle(item)"/>
                        </el-form-item>
                        <el-form-item label="封面" prop="miniprogramPicUrl">
                          <ImageUpload v-model="item.miniprogramPicUrl" type="image" :num="10" :width="150" :height="150" />
                        </el-form-item>
                        <el-form-item label="appid" prop="miniprogramAppid" v-show="false">
                          <el-input v-model="item.miniprogramAppid" value = 'wx776d6bd6848eec49' disabled />
                        </el-form-item>
                        <el-form-item label="page路径" prop="miniprogramPage"  v-show="false" label-width="100px" style="margin-left: -30px">
                          <el-input v-model="item.miniprogramPage" placeholder="小程序消息打开后的路径"  disabled />
                        </el-form-item>
                      </el-card>
                    </div>

                    <el-form-item label="添加短链" v-if="item.contentType == 1 || item.contentType == 11"  >
                      <el-tooltip content="请先根据科普选定科普小节之后再添加" effect="dark" :disabled="!!msgForm.videoId">
                        <el-switch
                          v-model="item.isBindUrl"
                          :disabled="!msgForm.videoId"
                          active-color="#13ce66"
                          inactive-color="#DCDFE6"
                          active-value="1"
                          inactive-value="2">
                        </el-switch>
                      </el-tooltip>

                      <span v-if="item.isBindUrl == '1'" style="margin-left: 10px; color: #13ce66">添加URL</span>
                      <span v-if="item.isBindUrl == '2'" style="margin-left: 10px; color: #b1b4ba">不加URL</span>
                    </el-form-item>

                    <el-form-item label="程序类型" v-if="item.contentType == 4"  >
                      <el-tooltip content="请先根据科普选定科普小节之后再添加" effect="dark" :disabled="!!msgForm.videoId">
                        <el-radio-group v-model="item.isSortUrl" :disabled="!msgForm.videoId">
                          <el-radio :label="1">发小程序卡片</el-radio>
                          <el-radio :label="2">发微信的短链</el-radio>
                        </el-radio-group>
                      </el-tooltip>

                    </el-form-item>
                    <span v-if="item.contentType == 4" >不选默认【发小程序卡片】</span>

                    <el-form-item label="课节过期时间" v-if="item.isBindUrl == '1'
                                                          && item.contentType != 2
                                                          && item.contentType != 5
                                                          && item.contentType != 6
                                                          && item.contentType != 8"
                                  style="margin-top: 1%" label-width="100px">
                      <el-row>
                        <el-input-number  v-model="item.expiresDays"  :min="1" :max="100" ></el-input-number>
                        （天）
                      </el-row>
                      <el-row>
                        <span class="tip">填写0或不填时，默认为系统配置的默认时间</span>
                      </el-row>
                    </el-form-item>
                  </el-form>
                </el-col>
                <el-col :span="1" :offset="1">
                  <i class="el-icon-delete" @click="delSetList(index)" style="margin-top: 20px;" v-if="setting.length>1"></i>
                </el-col>
              </el-row>
            </div>
            <el-link type="primary" class="el-icon-plus" :underline="false" @click='addSetList()'  >添加内容</el-link>

          </el-form-item>

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

          <el-form-item label="发送时间" prop="sendTime" v-if="msgForm.draftStrategy==1" >
            <el-time-picker
              class="custom-input"
              v-model="msgForm.sendTime"
              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">
          <el-button type="primary" @click="submitMsgForm">确 定</el-button>
          <el-button @click="cancelMsgForm">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 添加或修改sopUserLogsInfo对话框 -->
    <el-dialog title="批量修改客户营期" :visible.sync="updateMsgOpen.updateOpen" width="500px" append-to-body>
      <el-form ref="updateLogsInfoFrom" :model="updateLogsInfoFrom" :rules="batchRules" label-width="120px">
        <el-form-item label="选择营期时间" prop="paramTime">
          <el-date-picker clearable size="small"
                          v-model="updateLogsInfoFrom.paramTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择营期时间">
          </el-date-picker>
        </el-form-item>
      </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="videoNumOptions.title" :visible.sync="videoNumOptions.open" width="1500px" append-to-body>
      <userVideo ref="QwUserVideo" @videoResult="qwUserVideoResult"></userVideo>
    </el-dialog> -->
  </div>
</template>

<script>
import { sendMsgSopType,} from "@/api/app/userLogsInfo";
import ImageUpload from "@/views/qw/sop/ImageUpload.vue";
import {courseList, videoList} from "@/api/qw/sop";
import {updateTimeSopUserLogs} from "@/api/qw/sopUserLogs";
import { getLiveOptions as fetchLiveOptionsApi, getLiveGroupTypeList as fetchLiveGroupTypeListApi } from "@/api/app/live";


export default {
  name: "sendMsgOpenTool",
  components: { ImageUpload},
  data() {
    return {
      //上传语音的遮罩层
      voiceLoading :false,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS2",
      uploadUrlByVoice:process.env.VUE_APP_BASE_API+"/common/uploadOSSByHOOKVoice",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // sopUserLogsInfo表格数据
      sopUserLogsInfoList: [],
      sysFsSopWatchStatus: [],
      isSalesCallAdded:false,
      videoNumOptions: {
        title: '选择视频号',
        open: false,
        content: null,
        contentIndex: null,
      },
      isSalesCallCustomerAdded:false,
      tagList:[],
      selectTags:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      updateOpen:false,

      //修改营期
      updateLogsInfoFrom:{},
      queryParams1: {
        pageNum: 1,
        pageSize: 100,
        dataStatus: '1',
        name: null,
        type: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagIds:null,
        remark:null,
        sopId: null,
        userLogsId: null,
        userIdParam:null,
        startTimeParam:null,
        externalContactId: null,
        qwUserId: null,
        corpId: null,
        externalId: null,
        fsUserId: null,
        externalUserName: null,
        createTime: null,
      },

      courseList:[],
      videoList:[],
      liveGroupTypeList: [],//直播分组
      liveList: [],//直播间下拉
      //插件版
      sysQwSopAiContentType:[],

      sendMsgOpen:{
        title:'一键批量群发',
        open:false,
        ids:null,
      },
      updateMsgOpen:{
        title:'批量修改客户营期',
        updateOpen:false,
        ids:null,
      },

      smsTemplateList: [],
      // 表单参数
      form: {},
      setting:[{contentType:'1', value: '',}],
      msgForm:{
        videoId:null,
        courseId:null,
        courseType:null,
        userIdParam:null,
        setting:null,
        ids:null,
        type:null,
        corpId:null,
        sopId: null,
        startTime: null,
        sendTime: null,
        qwUserId: null,
        draftStrategy:1,
        sendTimeType: 1, // 添加字段：1-当天发送，2-次日发送
      },
      // 表单校验
      rules: {},
      batchRules:{
        paramTime: [
          { required: true, message: '选择的时间不能为空', trigger: 'blur' }
        ],
      },
      msgRules:{},
    };
  },

  created() {
    // 本页内容类别字典：sys_qwSopAi_contentType（直播对应 dictValue=20）
    // 注意：与群发页 app_sop_plugin_settingType（直播=21）不是同一套字典
    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });
    this.getDicts("sys_fs_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });

    courseList().then(response => {
      this.courseList = response.list;
    });

    fetchLiveGroupTypeListApi({ pageNum: 1, pageSize: 999 }).then(response => {
      this.liveGroupTypeList = response.rows || response.data || [];
    });

    this.loadSmsTemplates();
  },
  methods: {
    getLuckyBagStatus(content) {
      const selectedLuckyBag = this.luckyBagList.find(item => item.id === content.luckyBagId);
      if (selectedLuckyBag) {
        content.luckyBagDataStatus = selectedLuckyBag.dataStatus; // 自动填充标题
      } else {
        // 若未找到对应直播间，清空标题和封面（可选）
        content.luckyBagDataStatus = null;
      }
    },
    checkLiveMiniprogramTitle(item) {
      this.$forceUpdate();
    },
    /**
     * 直播分组切换
     */
    async liveGroupTypeChange(content) {
      this.$set(content, 'liveId', null);
      this.$set(content, 'miniprogramTitle', '');
      this.$set(content, 'miniprogramPicUrl', '');
      if (!content.liveGroupTypeId) {
        this.$set(content, 'meta', Object.assign({}, content.meta || {}, {
          liveLoading: false,
          liveList: [],
        }));
        return;
      }
      this.$set(content, 'meta', Object.assign({}, content.meta || {}, {
        liveLoading: true,
        liveList: [],
      }));
      const liveRes = await fetchLiveOptionsApi({ liveGroupType: content.liveGroupTypeId });
      this.$set(content, 'meta', Object.assign({}, content.meta || {}, {
        liveLoading: false,
        liveList: liveRes.data || liveRes.rows || [],
      }));
    },
    liveChange(content) {
      // content.liveId 是选中的直播间 ID（liveId）
      const list = (content.meta && content.meta.liveList) ? content.meta.liveList : [];
      const selectedLive = list.find(live => parseInt(live.liveId) === parseInt(content.liveId));
      if (selectedLive) {
        // 从选中的直播间对象中提取标题和封面，赋值给当前内容的对应字段
        content.miniprogramTitle = selectedLive.liveName || ''; // 自动填充标题
        content.miniprogramPicUrl = selectedLive.liveImgUrl || ''; // 自动填充封面
      } else {
        // 若未找到对应直播间，清空标题和封面（可选）
        content.miniprogramTitle = '';
        content.miniprogramPicUrl = '';
      }
    },
    oneClickGroupSending(val,type,corpId){

      this.sendMsgOpen.open= true;
      this.msgForm.ids = val;
      this.msgForm.type = type;
      this.msgForm.corpId = corpId;

    },
    updateTimeUserLogs(val,type,corpId,sopId){

      this.updateMsgOpen.updateOpen= true;
      this.msgForm.ids = val;
      this.msgForm.type = type;
      this.msgForm.corpId = corpId;
      this.msgForm.sopId = sopId;

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["updateLogsInfoFrom"].validate(valid => {
        if (valid) {

          this.updateLogsInfoFrom.ids=this.msgForm.ids;
          this.updateLogsInfoFrom.sopId= this.msgForm.sopId
          this.updateLogsInfoFrom.corpId= this.msgForm.corpId

          let loadingRock = this.$loading({
            lock: true,
            text: '正在执行中请稍后~~请不要刷新页面！！',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          updateTimeSopUserLogs(this.updateLogsInfoFrom).then(response => {
            this.msgSuccess("修改成功");
            this.open = false;
            this.updateMsgOpen.updateOpen=false;

            this.$emit('flashNotify')
            loadingRock.close();
          }).finally(res=>{
            loadingRock.close();
          })

        }
      });
    },
    // 取消按钮
    cancel() {
      this.updateMsgOpen.updateOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sopId: null,
        userLogsId: null,
        externalContactId: null,
        qwUserId: null,
        corpId: null,
        externalId: null,
        fsUserId: null,
        externalUserName: null,
        createTime: null,
        crtTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    courseChange() {
      if (this.msgForm.courseId != null ) {
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === this.msgForm.courseId);
        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的标题/封面上值
          if (selectedCourse && this.msgForm.courseId != null) {
            if ( this.setting[i].contentType == 3 || this.setting[i].contentType == 9 ){
              this.$set(this.setting[i], 'linkTitle', selectedCourse.dictLabel);
              this.$set(this.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
            }

            if ( this.setting[i].contentType == 4 || this.setting[i].contentType == 15|| this.setting[i].contentType == 19){
              this.$set(this.setting[i], 'miniprogramPicUrl', selectedCourse.dictImgUrl);
            }
          }

        }

      }
      videoList(this.msgForm.courseId).then(response => {
        this.videoList=response.list;
      });
    },

    videoIdChange() {
      if (this.msgForm.videoId != null ) {
        // 查找选中的课节对应的 label
        const selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === this.msgForm.videoId);
        if (selectedVideo) {

          // 重新获取内容类型字典数据
          this.getDicts("sys_qwSopAi_contentType").then(response => {
            let contentTypeList = response.data;

            if (!selectedVideo || selectedVideo.openClass != 1) {
              contentTypeList = contentTypeList.filter(item => item.dictValue !== '19');
            }

            // 使用 Vue.set 确保响应式
            this.$set(this, 'sysQwSopAiContentType', contentTypeList);

            // 强制更新每个 setting 项
            this.setting.forEach((item, index) => {
              if (item.contentType === '19' && (!selectedVideo || selectedVideo.openClass != 1)) {
                // 将 contentType 重置为默认值（比如1）
                this.$set(item, 'contentType', '1');
              }
              this.$set(this.setting[index], 'openClass', selectedVideo.openClass);
            });

            // 强制整个组件更新
            this.$forceUpdate();
          });
        }
        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的描述上值
          if (selectedVideo && this.msgForm.videoId != null) {
            if (this.setting[i].contentType == 3 || this.setting[i].contentType == 9 ){
              this.$set(this.setting[i], 'linkDescribe', selectedVideo.dictLabel);
            }

            if (this.setting[i].contentType == 4 || this.setting[i].contentType == 15|| this.setting[i].contentType == 19){
              this.$set(this.setting[i], 'miniprogramTitle', selectedVideo.dictLabel);
            }


          }
        }
      }
    },
    handleAvatarSuccessFile(res, file, item) {
      if (res.code === 200) {
        // 使用 $set 确保响应式更新
        this.$set(item, 'fileUrl', res.url);
      } else {
        this.msgError(res.msg);
      }
    },
    beforeAvatarUploadFile(file){
      const isLt1M = file.size / 1024 / 1024 < 10;
      if (!isLt1M) {
        this.$message.error('上传大小不能超过 10MB!');
      }
      return isLt1M;
    },
    //下载文件
    downloadUrl(materialUrl) {
      // 直接返回文件 URL
      return materialUrl;
    },

    handleAvatarSuccessVideo(res, file, item) {
      if(res.code==200){
        // 使用 $set 确保响应式更新
        this.$set(item, 'videoUrl', res.url);
      }
      else{
        this.msgError(res.msg);
      }
    },

    beforeAvatarUploadVideo(file){
      const isLt30M = file.size / 1024 / 1024 < 10;
      const isMP4 = file.type === 'video/mp4';

      if (!isMP4) {
        this.$message.error('仅支持上传 MP4 格式的视频文件!');
        return false;
      }

      if (!isLt30M) {
        this.$message.error('上传大小不能超过 10MB!');
        return false;
      }

      return true;
    },

    handleInputVideoText(value,content){
      // 允许的字符：中文、英文（大小写）、数字和指定标点符号（，。！？）
      const regex = /^[\u4e00-\u9fa5，。！？,!?]+$/;

      // 删除不符合条件的字符
      const filteredValue = value.split('').filter(char => regex.test(char)).join('');

      this.$set(content, 'value', filteredValue);

    },

    delSetList(index){
      this.setting.splice(index,1)
    },
    addSetList(){
      const newSetting = {
        contentType:'1',
        value: '',
        sendTimeType: 1, // 为每个规则项添加发送时间类型
      };
      // 将新设置项添加到 content.setting 数组中
      this.setting.push(newSetting);

    },


    handleKeydown(event, index) {
      const item = this.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; // 找到匹配的标签后退出循环
            }
          }
        }
      }
    },

    // 切换添加客服称呼按钮点击事件
    toggleSalesCall(index) {
      const item = this.setting[index];
      const salesCall = '#客服称呼#';
      const textarea = this.$refs[`textarea-${index}`][0].$refs.textarea;

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

      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);
      });
    },
    toggleSalesCallCustomer(index) {
      const item = this.setting[index];
      const salesCall = '#客户称呼#';
      const textarea = this.$refs[`textarea-${index}`][0].$refs.textarea;

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

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

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

      // 保持光标位置
      this.$nextTick(() => {
        textarea.setSelectionRange(cursorPosition, cursorPosition);
      });
    },

    handleContentTypeChange() {

      //如果是链接的才上
      if (this.msgForm.courseId != null ) {
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === this.msgForm.courseId);
        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的标题/封面上值
          if (selectedCourse  && this.msgForm.courseId != null) {

            if (this.setting[i].contentType == 3 || this.setting[i].contentType == 9){
              this.$set(this.setting[i], 'linkTitle', selectedCourse.dictLabel);
              this.$set(this.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
            }
            if (this.setting[i].contentType == 4 || this.setting[i].contentType == 15|| this.setting[i].contentType == 19){
              this.$set(this.setting[i], 'miniprogramPicUrl', selectedCourse.dictImgUrl);
            }


          }

        }

      }
      if (this.msgForm.videoId != null ) {
        // 查找选中的课节对应的 label
        const selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === this.msgForm.videoId);

        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的描述上值
          if (selectedVideo  && this.msgForm.videoId != null) {

            if (this.setting[i].contentType == 3 || this.setting[i].contentType == 9){
              this.$set(this.setting[i], 'linkDescribe', selectedVideo.dictLabel);
            }
            if (this.setting[i].contentType == 4 || this.setting[i].contentType == 15|| this.setting[i].contentType == 19){
              this.$set(this.setting[i], 'miniprogramTitle', selectedVideo.dictLabel);
            }

          }
        }
      }


    },

    resetSendMsgSop() {
      this.msgForm = {
        videoId:null,
        courseId:null,
        courseType:null,
        corpId:null,
        setting:null,
        sendTime:null,
        draftStrategy:1,
        sendTimeType: 1, // 添加默认值
      };
      this.resetForm("msgForm");
    },

    // 获取短信模板信息（类似福袋的处理方式）
    getSmsTemplateInfo(content) {
      // 如果短信模板列表为空，先加载数据
      if (this.smsTemplateList.length === 0) {
        getSmsTempList().then(response => {
          this.smsTemplateList = response.rows || response.data || [];
          // 加载完成后再次调用自身来处理选中项
          this.processSelectedSmsTemplate(content);
        }).catch(error => {
          console.error('加载短信模板失败:', error);
          this.$message.error('加载短信模板失败');
        });
      } else {
        // 直接处理选中项
        this.processSelectedSmsTemplate(content);
      }
    },

    // 处理选中的短信模板
    processSelectedSmsTemplate(content) {
      const selectedTemplate = this.smsTemplateList.find(item => item.tempId === content.smsTemplateId);
      if (selectedTemplate) {
        // 自动填充模板内容预览
        this.$set(content, 'smsTemplateContent', selectedTemplate.content || selectedTemplate.templateContent || '');
      } else {
        // 清空相关内容
        this.$set(content, 'smsTemplateContent', '');
      }
    },

    // 加载短信模板列表
    loadSmsTemplates() {
      if (this.smsTemplateList.length > 0) {
        return; // 如果已经有数据，不再重复加载
      }

      getSmsTempList().then(response => {
        this.smsTemplateList = response.rows || response.data || [];
        if (this.smsTemplateList.length === 0) {
          this.$message.info('暂无可用的短信模板');
        }
      }).catch(error => {
        console.error('加载短信模板失败:', error);
        this.$message.error('加载短信模板失败');
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

// 修改后的方法：在原有的基础上增加一条消息
    processContentType13(settings) {
      const result = [];

      settings.forEach(item => {
        // 如果 contentType 是 13 且 value 不为空，则额外添加一条 contentType 为 1 的消息
        if (item.contentType == 13 && item.value && item.value.trim() !== '') {
          // 按换行符分割内容，取第一部分
          const contentParts = item.value.split('\n')
            .map(part => part.trim())
            .filter(part => part !== '');

          if (contentParts.length > 0) {
            // 创建一条额外的消息，使用第一部分内容
            const additionalMessage = {
              ...item,
              contentType: 1, // 改为文本类型
              value: contentParts[0]
            };
            result.push(additionalMessage);
          }
        }
        if (item.contentType == 20) {
          item.miniprogramAppid = 'wx776d6bd6848eec49'
        }
        result.push(item);
      });

      return result;
    },
    submitMsgForm() {
      // 表单验证
      this.$refs["msgForm"].validate(valid => {
        if (valid) {
          // 确保发送时间类型被传递
          this.msgForm.sendTimeType = this.msgForm.sendTimeType;
          if (this.msgForm.draftStrategy == 1) {
            // 处理 contentType 13 的拆分逻辑
            const processedSetting = this.processContentType13(this.setting);
            this.msgForm.setting = JSON.stringify(processedSetting);

            // 基础验证
            if (processedSetting.length <= 0) {
              return this.$message.error("请添加规则")
            }
            if (this.msgForm.courseId === null || this.msgForm.courseId === '') {
              return this.$message.error("科普不能为空")
            }
            if (this.msgForm.videoId === null || this.msgForm.videoId === '') {
              return this.$message.error("课节不能为空")
            }
            if (this.msgForm.courseType === null || this.msgForm.courseType === '') {
              return this.$message.error("消息类型不能为空")
            }

            // 内容类型验证
            for (let i = 0; i < processedSetting.length; i++) {
              const item = processedSetting[i];

              // 文本内容验证
              if (item.contentType == 1 && (item.value == null || item.value == "")) {
                return this.$message.error("内容不能为空")
              }
              // 图片内容验证
              if (item.contentType == 2 && (item.imgUrl == null || item.imgUrl == "")) {
                return this.$message.error("图片不能为空")
              }
              // 链接内容验证
              if ((item.contentType == 3 || item.contentType == 9) && (item.linkTitle == null || item.linkTitle == "")) {
                return this.$message.error("链接标题不能为空")
              }
              if ((item.contentType == 3 || item.contentType == 9) && (item.linkDescribe == null || item.linkDescribe == "")) {
                return this.$message.error("链接描述不能为空")
              }
              if ((item.contentType == 3 || item.contentType == 9) && (item.linkImageUrl == null || item.linkImageUrl == "")) {
                return this.$message.error("链接图片不能为空")
              }
              if ((item.contentType == 3 || item.contentType == 9) && item.type == 1 && (item.linkUrl == null || item.linkUrl == "")) {
                return this.$message.error("链接地址不能为空")
              }
              // 小程序内容验证
              if ((item.contentType == 4 || item.contentType == 15  || item.contentType == 19) && (item.miniprogramTitle == null || item.miniprogramTitle == "")) {
                return this.$message.error("小程序消息标题不能为空")
              }
              if ((item.contentType == 4 || item.contentType == 15 || item.contentType == 19) && (item.miniprogramPicUrl == null || item.miniprogramPicUrl == "")) {
                return this.$message.error("小程序封面地址不能为空")
              }
              // 文件内容验证
              if (item.contentType == 5 && (item.fileUrl == null || item.fileUrl == "")) {
                return this.$message.error("文件不能为空")
              }
              // 视频内容验证
              if (item.contentType == 6 && (item.videoUrl == null || item.videoUrl == "")) {
                return this.$message.error("视频不能为空")
              }
              // 语音内容验证
              if (item.contentType == 7 && (item.value == null || item.value == "")) {
                return this.$message.error("语音不能为空")
              }
              // 直播间内容验证
              if (item.contentType == 20 && (item.liveGroupTypeId == null || item.liveGroupTypeId === "")) {
                this.$message.error("直播分组不能为空")
                return false;
              }
              if (item.contentType == 20 && (item.liveId == null || item.liveId == "")) {
                this.$message.error("直播间不能为空")
                return false;
              }
              if (item.contentType == 20 && (item.miniprogramTitle == null || item.miniprogramTitle == "")) {
                this.$message.error("标题不能为空")
                return false;
              }
              if (item.contentType == 20 && (item.miniprogramPicUrl == null || item.miniprogramPicUrl == "")) {
                this.$message.error("封面不能为空")
                return false;
              }
              // 福袋内容验证
              if (item.contentType == 14 && (item.luckyBagId == null || item.luckyBagId === "")) {
                return this.$message.error("福袋不能为空")
              }
              // 短信模板验证
              if (item.contentType == 17 && (item.smsTemplateId == null || item.smsTemplateId === "")) {
                return this.$message.error("短信模板不能为空")
              }
            }

            // 短信模板数据映射
            for (let j = 0; j < processedSetting.length; j++) {
              const item = processedSetting[j];
              if (item.contentType == 17 && item.smsTemplateId) {
                // 根据选中的短信模板ID查找对应的模板信息
                const selectedTemplate = this.smsTemplateList.find(template => template.tempId === item.smsTemplateId);
                if (selectedTemplate) {
                  // 设置短信模板的相关字段
                  this.$set(item, 'smsTemplateCode', selectedTemplate.tempCode || '');
                  this.$set(item, 'smsTemplateTitle', selectedTemplate.title || '');
                }
              }
            }

            // 重新序列化处理后的数据
            this.msgForm.setting = JSON.stringify(processedSetting);

            // 关闭弹窗
            this.sendMsgOpen.open = false;

            // 显示加载状态
            const loading = this.$loading({
              lock: true,
              text: '正在执行中请稍后~~请不要刷新页面！！',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });

            // 发送消息
            sendMsgSopType(this.msgForm).then(response => {
              this.msgSuccess("一键群发成功");
              loading.close();
              this.setting = [{ contentType: '1', value: '' }];
              this.resetSendMsgSop();
            }).catch(error => {
              loading.close();
              this.msgError("发送失败：" + (error.message || '未知错误'));
            });
            // 测试用 - 查看处理后的数据
          /*  console.log('原始setting:', this.setting);
            loading.close();*/
          }
        }
      });
    },
    cancelMsgForm(){
      this.sendMsgOpen.open = false;
      this.resetSendMsgSop();
    },

    //选择视频号
    hanldeSelectVideoNum(content, index) {
      this.videoNumOptions.content = content;
      this.videoNumOptions.contentIndex = index;
      this.videoNumOptions.open = true;
    },

    qwUserVideoResult(val) {

      // 根据选中的内容，将返回的数据更新到相应的表单项
      const content = this.videoNumOptions.content;
      const setList = content[this.videoNumOptions.contentIndex];
      setList.nickname = val.nickname;
      setList.avatar = val.avatar;
      setList.coverUrl = val.coverUrl;
      setList.thumbUrl = val.thumbUrl;
      setList.desc = val.desc;
      setList.url = val.url;
      setList.extras = val.extras;
      setList.videoId = val.id;

      this.videoNumOptions.open = false;

    },
  }
};
</script>
