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

    <div style="margin: 30px;" v-if="this.form.sendType == 1 "> sop规则【企微接口】模板</div>
    <div style="margin: 30px;" v-if="this.form.sendType == 2 "> sop规则【AI插件】模板</div>

    <div style="margin-top: 10px;margin-left: 50px;margin-right: 100px;margin-bottom: 60px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板标题" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="间隔天数" prop="gap">
          <el-input-number v-model="form.gap"  :min="1" label="间隔天数"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort"  :min="0" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="规则" prop="setting">
          <el-timeline >
            <el-timeline-item :timestamp="'第'+(1+(form.gap*index))+'天'" :color="'#0bbd87'" placement="top" v-for="(item, index) in setting"  style="margin-top: 10px;">
              <el-row>
                <el-col :span="22">
                  <div style="background-color: #fbfbfb;padding: 15px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                    <el-form :model="item"  label-width="80px">

                      <el-form-item label="内容名称"  style="height: 50px;">
                        <el-input v-model="item.name" placeholder="内容名称,仅内部可见" />
                      </el-form-item>

                      <el-form-item label="规则"  >
                        <div v-for="(content, contentIndex) in item.content" style="background-color: #fdfdfd;padding: 15px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">

                          <el-row>

                            <el-col el-col :span="22" >
                              <el-form :model="content" label-width="70px">
                                <el-form-item label="时间"  prop="time"  >
                                  <el-time-picker
                                    class="custom-input"
                                    v-model="content.time"
                                    value-format="HH:mm"
                                    format="HH:mm"
                                    :picker-options="{ selectableRange: '00:21:00 - 23:59:59' }"
                                    placeholder="时间"
                                    style="width: 100px;height: 20px;" >
                                  </el-time-picker>
                                </el-form-item>
                                <el-form-item label="消息类别"  >
                                  <el-radio-group v-model="content.type" @change="() => content.contentType = '1'" >
                                    <el-radio
                                      :label="1"

                                    >普通</el-radio>
                                    <el-radio
                                      :label="2"

                                    >课程</el-radio>
                                    <el-radio
                                      :label="3"

                                    >订单</el-radio>
                                    <el-radio
                                      :label="4"

                                    >AI触达</el-radio>
                                  </el-radio-group>
                                </el-form-item>

                                <el-form-item label="课程"  v-if="content.type == 2 ">
                                  <el-select  v-model="content.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChange(content,index,contentIndex)">
                                    <el-option
                                      v-for="dict in courseList"
                                      :key="dict.dictValue"
                                      :label="dict.dictLabel"
                                      :value="parseInt(dict.dictValue)"
                                    />
                                  </el-select>
                                  <el-select  v-model="content.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange(content,index,contentIndex)" >
                                    <el-option
                                      v-for="dict in videoList[index][contentIndex]"
                                      :key="dict.dictValue"
                                      :label="dict.dictLabel"
                                      :value="parseInt(dict.dictValue)"
                                    />
                                  </el-select>
                                  <el-select  v-model="content.courseType" placeholder="请选择消息类型" size="mini" style=" margin-right: 10px;" v-if="content.type != 4 ">
                                    <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="Ai触达"  v-if="content.type == 4 ">
                                  <el-select  v-model="content.aiTouch" placeholder="请选择Ai触达类型" size="mini" style=" margin-right: 10px;" v-if="content.type == 4 ">
                                    <el-option label="非首次交流" value="非首次交流"></el-option>
                                    <el-option label="首次交流1" value="首次交流1"></el-option>
                                    <el-option label="首次交流2" value="首次交流2"></el-option>
                                    <el-option label="交流状态1" value="交流状态1"></el-option>
                                    <el-option label="交流状态2" value="交流状态2"></el-option>
                                    <el-option label="交流状态3" value="交流状态3"></el-option>
                                  </el-select>
                                </el-form-item>



                                <!--                                <el-form-item label="内容类型"  >-->
                                <div v-for="(setList, setIndex) in content.setting" :key="setIndex" style="background-color: #fdfdfd; border: 1px solid #e6e6e6; margin-bottom: 20px;" v-if="content.type != 4 ">
                                  <el-row>
                                    <el-col :span="22">
                                      <el-form :model="setList" label-width="70px">
                                        <el-form-item label="内容类别" style="margin: 2%">
                                          <div v-if="form.sendType == 1 ">
                                            <el-radio-group  v-model="setList.contentType" >
                                              <el-radio
                                                v-for="item in sysQwSopContentType"
                                                :label="item.dictValue"
                                                :disabled="item.dictValue === '1' && content.setting.some(s => s.contentType == '1')">
                                                {{ item.dictLabel }}
                                              </el-radio>
                                            </el-radio-group>
                                          </div>
                                          <div v-if="form.sendType == 2 ">
                                            <!--                                              <div v-if="content.type == 2 ">-->
                                            <!--                                                <el-radio-group  v-model="setList.contentType" @change="handleContentTypeChange(setList,index,setIndex)">-->
                                            <!--                                                  <el-radio  :label="item.dictValue" v-for="item in sysQwSopSettingType">{{item.dictLabel}}</el-radio>-->
                                            <!--                                                </el-radio-group>-->
                                            <!--                                              </div>-->
                                            <!--                                              <div v-else>-->
                                            <el-radio-group  v-model="setList.contentType" @change="handleContentTypeChange(content,index,contentIndex,setIndex)">
                                              <el-radio   :label="item.dictValue" v-for="item in sysQwSopAiContentType">{{item.dictLabel}}</el-radio>
                                            </el-radio-group>
                                            <!--                                              </div>-->

                                          </div>
                                        </el-form-item>
                                        <el-form-item label="内容"  >
                                          <el-input v-if="setList.contentType == 1 " v-model="setList.value" type="textarea" :rows="3" placeholder="内容" style="width: 90%;margin-top: 10px;"/>

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

                                          <div v-if="setList.contentType == 3 ">
                                            <el-card class="box-card">
                                              <el-form-item label="链接标题:"  label-width="100px">
                                                <el-input v-model="setList.linkTitle" placeholder="请输入链接标题" style="width: 90%;"/>
                                              </el-form-item>
                                              <el-form-item label="链接描述:"   label-width="100px" >
                                                <el-input type="textarea" :rows="3" v-model="setList.linkDescribe" placeholder="请输入链接描述" style="width: 90%;margin-top: 1%;"/>
                                              </el-form-item>
                                              <el-form-item label="链接封面:"   label-width="100px">
                                                <ImageUpload v-model="setList.linkImageUrl" type="image" :num="1" :file-size="2" :width="150" :height="150" style="margin-top: 1%;" />
                                              </el-form-item>
                                              <div v-if="content.type!=2" style="margin-top: 1%">
                                                <el-form-item label="链接地址:"  label-width="100px" >
                                                  <el-input v-model="setList.linkUrl" placeholder="请输入链接地址" style="width: 90%;"/>
                                                </el-form-item>
                                              </div>
                                              <div v-if="content.type==2">
                                                <el-form-item label="链接地址:"  label-width="100px" >
                                                  <el-tag type="warning" v-model="setList.isBindUrl=1">选择的课程小节 即为卡片链接地址</el-tag>
                                                </el-form-item>
                                              </div>
                                            </el-card>
                                          </div>

                                          <div v-if="setList.contentType == 4">
                                            <el-card class="box-card">
                                              <el-form-item label="标题" prop="miniprogramTitle">
                                                <el-input v-model="setList.miniprogramTitle" placeholder="请输入小程序消息标题，最长为64字"  />
                                              </el-form-item>
                                              <el-form-item label="封面" prop="miniprogramPicUrl">
                                                <ImageUpload v-model="setList.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="setList.miniprogramAppid='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="setList.miniprogramPage" placeholder="小程序消息打开后的路径" disabled />
                                              </el-form-item>
                                            </el-card>
                                          </div>

                                          <div v-if="setList.contentType == 5 ">

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

                                          </div>

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

                                            </el-card>
                                          </div>

                                        </el-form-item>

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

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

                                        <el-form-item label="课节过期时间" v-if="content.type == 2 && setList.isBindUrl == '1' && setList.contentType != 2  && setList.contentType != 5  && setList.contentType != 6 && setList.contentType != 8 " style="margin-top: 1%">
                                          <el-row>
                                            <el-input-number  v-model="setList.expiresDays"  :min="0" :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,contentIndex,setIndex)" style="margin-top: 20px;" v-if="content.setting.length>1"></i>
                                    </el-col>
                                  </el-row>

                                </div>
                                <el-link type="primary" class="el-icon-plus" :underline="false" @click='addSetList(contentIndex,item.content)' v-if="content.type != 4 ">添加内容</el-link>
                                <!--                                </el-form-item>-->

                              </el-form>

                            </el-col>
                            <el-col :span="1" :offset="1">
                              <i class="el-icon-delete" @click="delContent(index,contentIndex)" style="margin-top: 20px;" v-if="item.content.length>1"></i>
                            </el-col>
                          </el-row>
                        </div>
                        <el-link type="primary" class="el-icon-plus" :underline="false" @click='addContent(index)'>添加规则</el-link>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-col>
                <el-col :span="1" :offset="1">
                  <i class="el-icon-delete-solid" @click="delSetting(index)"  v-if="setting.length>1"></i>
                </el-col>
              </el-row>
            </el-timeline-item>


          </el-timeline>
          <el-link type="primary" class="el-icon-plus" :underline="false" @click='addSetting()'>添加天数</el-link>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="float: right;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>


    <el-dialog :title="videoNumOptions.title" :visible.sync="videoNumOptions.open" style="width: 1500px;height: 100%" append-to-body>
      <userVideo ref="QwUserVideo" @videoResult="qwUserVideoResult" ></userVideo>
    </el-dialog>

  </div>
</template>

<script>
import {addSopTemp, delSopTemp, exportSopTemp, getSopTemp, listSopTemp, updateSopTemp} from "@/api/qw/sopTemp";
import {courseList, videoList} from "@/api/qw/sop";
import ImageUpload from "@/views/qw/sop/ImageUpload";
import FriendMaterial from "@/views/qw/friendMaterial/index.vue";
import userVideo from "@/views/qw/userVideo/userVideo.vue";

export default {
  name: "addSopTemp",
  components: { ImageUpload,FriendMaterial,userVideo},
  data() {
    return {

      //图片放大
      dialogVisible: false,
      dialogImageUrl:null,

      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS2",
      uploadUrlByVoice:process.env.VUE_APP_BASE_API+"/common/uploadOSSByHOOKVoice",
      //上传语音的遮罩层
      voiceLoading :false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      sysFsSopWatchStatus: [],
      //消息内容类型 企微版
      sysQwSopContentType:[],
      //插件版
      sysQwSopAiContentType:[],
      //链接版类别
      sysQwSopSettingType:[],

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // sop模板表格数据
      setting: [],
      courseList:[],
      videoList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      form: {
        name: null,
        setting: null,
        status: "1",
        sort: 1,
        companyId: null,
        gap:1,
      },
      videoNumOptions:{
        title:'选择视频号',
        open:false,
        content:null,
        contentIndex:null,
        setIndex:null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        gap: [
          { required: true, message: '间隔天数不能为空', trigger: 'blur' }
        ],
      },
      contentRules:{
        time:[{ required: true, message: '时间不能为空', trigger: 'blur' }],
      }
    };
  },
  created() {

    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    courseList().then(response => {
      this.courseList = response.list;
    });
    this.getDicts("sys_fs_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });

    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });

    this.getDicts("sys_qwSop_contentType").then(response => {
      this.sysQwSopContentType = response.data;
    });
    this.getDicts("sys_qwSop_settingType").then(response => {
      this.sysQwSopSettingType = response.data;
    });


    this.form.sendType = this.$route.params && this.$route.params.command;

    setTimeout(() => {
      this.getList();
    }, 200);

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

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

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

    },
    addSetList(contentIndex, content) {

      if (this.form.sendType == 1) {
        for (let i = 0; i < content.length; i++) {

          if (content[i].setting.length > 9) {
            return this.$message.error("因为企微接口限制，企微模板一条消息只能设置最多~9个内容！！")
          } else {

            // 动态生成新的设置项
            const newSetting = content[i].setting.some(item => item.contentType === '1')
              ? {contentType: '2', imgUrl: ''}  // 如果存在 contentType = '1'，添加 contentType = '2'
              : {contentType: '1', value: ''};  // 如果不存在 contentType = '1'，添加 contentType = '1'

            // 将新设置项添加到 content[i].setting 数组中
            content[i].setting.push(newSetting);
          }

        }
      } else {

        const newSetting = {
          contentType: '1',
          value: '',
        };

        // 将新设置项添加到 content.setting 数组中
        content[contentIndex].setting.push(newSetting);

      }

    },
    delSetList(index, contentIndex, setIndex) {
      this.setting[index].content[contentIndex].setting.splice(setIndex, 1)
    },

    addContent(index) {

      if (this.setting[index].content.length > 0 && this.form.sendType == 1) {
        return this.$message.error("因为企微接口限制，企微模板一天只能设置一条消息~")
      } else {
        this.setting[index].content.push({type: 1, contentType: '1', setting: [{contentType: '1', value: "",}]})
        this.videoList[index].push([])
      }

    },

    delContent(index, contentIndex) {
      this.setting[index].content.splice(contentIndex, 1)
      this.videoList[index].splice(contentIndex, 1)
    },
    addSetting() {

      this.setting.push({name: null, content: [{type: 1, contentType: '1', setting: [{contentType: '1', value: "",}]}]})
      this.videoList.push([])

    },
    delSetting(index) {
      this.setting.splice(index, 1)
      this.videoList.splice(index, 1)
    },
    //上传文件
    handleAvatarSuccessFile(res, file, content) {
      if (res.code === 200) {
        // 使用 $set 确保响应式更新
        this.$set(content, '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;
    },

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

    qwUserVideoResult(val){

      // 根据选中的内容，将返回的数据更新到相应的表单项
      const content = this.videoNumOptions.content;
      const setList = content.setting[this.videoNumOptions.setIndex];

      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;

      this.videoNumOptions.open=false;
    },

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

        // 创建 Audio 对象加载音频
        const audio = new Audio(res.mp3Url);
        audio.addEventListener('loadedmetadata', () => {
          // 获取音频时长
          this.$set(content, 'voiceDuration', Math.ceil(audio.duration));
        });
        // 使用 $set 确保响应式更新
        this.$set(content, 'voiceUrl', res.silkUrl);
        this.$set(content, 'mp3Url', res.mp3Url);
      } else {
        this.msgError(res.msg);
      }
      this.voiceLoading = false;
    },
    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;
    },
    beforeAvatarUploadVoice(file) {
      return new Promise((resolve, reject) => {
        const isLt10M = file.size / 1024 / 1024 < 10; // 假设语音文件大小限制为10MB
        const isVoiceType = ['audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/x-wav'].includes(file.type);

        if (!isVoiceType) {
          this.$message.error('仅支持上传 MP3, WAV, X-WAV 格式的语音文件!');
          return reject(false); // 不允许继续上传
        }

        if (!isLt10M) {
          this.$message.error('上传大小不能超过 10MB!');
          return reject(false); // 不允许继续上传
        }

        // 使用 FileReader 读取文件
        const reader = new FileReader();
        reader.onload = (event) => {
          const audio = new Audio(event.target.result);
          audio.addEventListener('loadedmetadata', () => {
            // 获取时长并保存
            if (Math.ceil(audio.duration) > 30) {
              this.$message.error('音频时长不能超过30秒！');
              this.voiceLoading = false;
              return reject(false); // 不允许继续上传
            }
            resolve(true); // 允许上传
          });
        };

        reader.onerror = () => {
          this.$message.error('无法读取音频文件！请上传正确的音频文件');
          reject(false); // 不允许继续上传
        };
        this.voiceLoading = true;
        reader.readAsDataURL(file); // 开始读取文件
      });
    },

    handleClosegroupUser(list) {
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
    },
    courseChange(content, index, countIndex) {
      this.$set(content, 'videoId', null);
      let selectedCourse;
      if (content.courseId != null) {
        // 查找选中的课程对应的 label
        selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === content.courseId);
      }

      for (let i = 0; i < content.setting.length; i++) {
        //如果是链接的才上
        if (selectedCourse && content.type == 2 && content.courseId != null) {

          if (content.setting[i].contentType == 3){
            //响应式直接给链接的标题/封面上值
              this.$set(content.setting[i], 'linkTitle', selectedCourse.dictLabel);
              this.$set(content.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
          }

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


        }
      }
      videoList(content.courseId).then(response => {

        this.videoList[index].splice(countIndex, 1, response.list);

      });
    },

    handleContentTypeChange(content, index, countIndex, setIndex) {

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

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

          }

        }

      }
      if (content.videoId != null && content.type == 2) {
        // 查找选中的课节对应的 label
        const selectedVideo = this.videoList[index][countIndex].find(course => parseInt(course.dictValue) === content.videoId);

        for (let i = 0; i < content.setting.length; i++) {
          //响应式直接给链接的描述上值
          if (selectedVideo  && content.type == 2 && content.videoId != null) {
            if (content.setting[i].contentType == 3){
              this.$set(content.setting[i], 'linkDescribe', selectedVideo.dictLabel);
            }
            if (this.setting[i].contentType == 4){
              this.$set(content.setting[i], 'miniprogramTitle', selectedVideo.dictLabel);
            }
          }
        }
      }


    },
    videoIdChange(content, index, countIndex) {
      //选择了课程小节则 默认绑上

      let selectedVideo;
      // 查找选中的课程对应的 label
      if (content.videoId != null) {
        selectedVideo = this.videoList[index][countIndex].find(course => parseInt(course.dictValue) === content.videoId);
      }
      for (let i = 0; i < content.setting.length; i++) {
        //课程消息-文本内容
        if (content.setting[i].contentType == 1 && content.type == 2) {
          this.$set(content.setting[i], 'isBindUrl', '1');
        }
        //如果是链接的才上
        if (selectedVideo && content.type == 2 && content.videoId != null) {
          //响应式直接给链接的描述上值
          if (content.setting[i].contentType == 3 ){

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

        }
      }

    },
    /** 查询sop模板列表 */
    getList() {
      this.loading = true;
      listSopTemp(this.queryParams).then(response => {
        this.sopTempList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace('/qw/conversion/sopTemp')
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        setting: null,
        status: "0",
        sort: null,
        createTime: null,
        createBy: null,
        companyId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加sop模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSopTemp(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改sop模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {

        if (valid) {
          this.form.setting = JSON.stringify(this.setting)

          if (this.setting.length <= 0) {
            return this.$message("请添加规则")
          }

          for (let i = 0; i < this.setting.length; i++) {


            for (let j = 0; j < this.setting[i].content.length; j++) {

              if (this.setting[i].name == null || this.setting[i].name == "") {
                return this.$message.error("内容名称不能为空")
              }
              if (this.setting[i].content[j].time == null || this.setting[i].content[j].time == "") {
                return this.$message.error("时间不能为空")
              }
              if (this.setting[i].content[j].type != 4) {
                for (let k = 0; k < this.setting[i].content[j].setting.length; k++) {
                  if (this.setting[i].content[j].setting[k].contentType == 1 && (this.setting[i].content[j].setting[k].value == null || this.setting[i].content[j].setting[k].value == "")) {
                    return this.$message.error("内容不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 2 && (this.setting[i].content[j].setting[k].imgUrl == null || this.setting[i].content[j].setting[k].imgUrl == "")) {
                    return this.$message.error("图片不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 3 && (this.setting[i].content[j].setting[k].linkTitle == null || this.setting[i].content[j].setting[k].linkTitle == "")) {
                    return this.$message.error("链接标题不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 3 && (this.setting[i].content[j].setting[k].linkDescribe == null || this.setting[i].content[j].setting[k].linkDescribe == "")) {
                    return this.$message.error("链接描述不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 3 && (this.setting[i].content[j].setting[k].linkImageUrl == null || this.setting[i].content[j].setting[k].linkImageUrl == "")) {
                    return this.$message.error("链接图片不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 3 && this.setting[i].content[j].setting[k].type == 1 && (this.setting[i].content[j].setting[k].linkUrl == null || this.setting[i].content[j].setting[k].linkUrl == "")) {
                    return this.$message.error("链接地址不能为空")
                  }

                  if (this.setting[i].content[j].setting[k].contentType == 4 && (this.setting[i].content[j].setting[k].miniprogramTitle == null || this.setting[i].content[j].setting[k].miniprogramTitle == "")) {
                    return this.$message.error("小程序消息标题不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 4 && (this.setting[i].content[j].setting[k].miniprogramPicUrl == null || this.setting[i].content[j].setting[k].miniprogramPicUrl == "")) {
                    return this.$message.error("小程序封面地址不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 5 && (this.setting[i].content[j].setting[k].fileUrl == null || this.setting[i].content[j].setting[k].fileUrl == "")) {
                    return this.$message.error("文件不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 6 && (this.setting[i].content[j].setting[k].videoUrl == null || this.setting[i].content[j].setting[k].videoUrl == "")) {
                    return this.$message.error("视频不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 7 && (this.setting[i].content[j].setting[k].value == null || this.setting[i].content[j].setting[k].value == "")) {
                    return this.$message.error("语音文本不能为空")
                  }
                  if (this.setting[i].content[j].setting[k].contentType == 8 && (this.setting[i].content[j].setting[k].url == null || this.setting[i].content[j].setting[k].url == "")) {
                    return this.$message.error("视频号信息不能为空")
                  }
                }
              } else {
                if (this.setting[i].content[j].aiTouch == null || this.setting[i].content[j].aiTouch == '') {
                  return this.$message.error("AI触达不能为空")
                }
              }
            }


          }

          if (this.form.id != null) {
            updateSopTemp(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sopTemp')
              window.location.replace('/qw/conversion/sopTemp')
              this.reset();

            });
          } else {

            addSopTemp(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sopTemp')
              window.location.replace('/qw/conversion/sopTemp')
              this.reset();

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除sop模板编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSopTemp(ids);
      }).then(() => {
        this.getList();


        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有sop模板数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSopTemp(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>

<style scoped>
.custom-input /deep/ .el-input__inner {
  height: 20px;
  text-align: center;
}

.custom-input /deep/ .el-input__icon {
  line-height: 10px;
}
</style>
