<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="80px">
        <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="时间" >
                                  <el-time-picker
                                    class="custom-input"
                                    v-model="content.time"
                                    value-format="HH:mm"
                                    format="HH:mm"
                                    :picker-options="{ selectableRange: '00:00: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-group>
                                </el-form-item>

                                <el-form-item label="课程"  v-if="content.type == 2 " required>
                                  <el-select v-model="content.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChangeUpdate(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;">
                                    <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="内容类别"  >
                                  <div v-if="form.sendType == 1 ">
                                    <el-radio-group v-model="content.contentType">
                                      <el-radio :label="item.dictValue" v-for="item in sysQwSopContentType">{{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="content.contentType" @change="handleContentTypeChange(content,index,contentIndex)">
                                        <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="content.contentType" @change="handleContentTypeChange(content,index,contentIndex)">
                                        <el-radio   :label="item.dictValue" v-for="item in sysQwSopAiContentType">{{item.dictLabel}}</el-radio>
                                      </el-radio-group>
                                    </div>
                                  </div>
                                  <!--                                   <el-radio-group v-model="content.contentType">-->
                                  <!--                                       <el-radio-->
                                  <!--                                         :label="1"-->
                                  <!--                                       >文字</el-radio>-->
                                  <!--                                       <el-radio-->
                                  <!--                                         :label="2"-->
                                  <!--                                       >图片</el-radio>-->
                                  <!--                                   </el-radio-group>-->
                                </el-form-item>

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

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

                                  </div>

                                  <div v-if="content.contentType == 6 ">
                                    <el-form-item label="上传视频：" prop="videoUrl" label-width="100px">
                                      <el-upload
                                        v-model="content.videoUrl"
                                        class="avatar-uploader"
                                        :action="uploadUrl"
                                        :show-file-list="false"
                                        :on-success="(res, file) => handleAvatarSuccessVideo(res, file, content)"
                                        :before-upload="beforeAvatarUploadVideo">
                                        <i class="el-icon-plus avatar-uploader-icon"></i>
                                      </el-upload>
                                      <video v-if="content.videoUrl"
                                             :src="content.videoUrl"
                                             controls style="width: 200px;height: 100px">
                                      </video>
                                    </el-form-item>
                                  </div>
                                  <div v-if="content.contentType == 7 ">
                                    <el-form-item label="上传语音：" prop="videoUrl" label-width="100px">
                                      <el-upload
                                        v-model="content.voiceUrl"
                                        class="avatar-uploader"
                                        :action="uploadUrl"
                                        :show-file-list="false"
                                        :on-success="(res, file) => handleAvatarSuccessVoice(res, file, content)"
                                        :before-upload="beforeAvatarUploadVoice">
                                        <i class="el-icon-plus avatar-uploader-icon"></i>
                                      </el-upload>
                                      <audio  v-if="content.voiceUrl"
                                              :src="content.voiceUrl"
                                              controls style="width: 300px;height: 50px">
                                      </audio >
                                    </el-form-item>
                                  </div>
                                </el-form-item>
                                <el-form-item label="添加短链" v-if="content.type == 2 && content.contentType == 1  "  >
                                  <el-tooltip content="请先根据课程选定课程小节之后再添加" effect="dark" :disabled="!!content.videoId">
                                    <el-switch
                                      v-model="content.isBindUrl"
                                      :disabled="!content.videoId"
                                      active-color="#13ce66"
                                      inactive-color="#DCDFE6"
                                      active-value="1"
                                      inactive-value="2">
                                    </el-switch>
                                  </el-tooltip>

                                  <span v-if="content.isBindUrl == '1'" style="margin-left: 10px; color: #13ce66">添加URL</span>
                                  <span v-if="content.isBindUrl == '2'" style="margin-left: 10px; color: #b1b4ba">不加URL</span>
                                </el-form-item>
                                <el-form-item label="课节过期时间" v-if="content.type == 2 && content.isBindUrl == '1' && content.contentType != 2  && content.contentType != 5  && content.contentType != 6 ">
                                  <el-row>
                                    <el-input-number  v-model="content.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="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="display: flex;justify-content: flex-end;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { listSopTemp, getSopTemp, delSopTemp, addSopTemp, updateSopTemp, exportSopTemp } from "@/api/qw/sopTemp";
import { courseList,videoList } from "@/api/qw/sop";
import ImageUpload from "@/views/qw/sop/ImageUpload";
export default {
  name: "SopTemp",
  components: { ImageUpload},
  data() {
    return {
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      sysFsSopWatchStatus: [],
      //消息内容类型 企微版
      sysQwSopContentType:[],
      //插件版
      sysQwSopAiContentType:[],

      //类别
      sysQwSopSettingType:[],

      courseList:[],
      videoList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // sop模板表格数据
      setting: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      form: {
        name: null,
        setting: null,
        status: "1",
        sort: 1,
        companyId: null,
        gap:1,
      },
      // 表单校验
      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' }
        ],
      }
    };
  },
  created() {
    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });
    this.getDicts("sys_fs_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });

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

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

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

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

    const id = this.$route.params && this.$route.params.id;
    this.handleUpdate(id);



  },
  methods: {
    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})
        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,type:1,content:[],day:"0",hour:"0",minute:"0",time:""})
      this.videoList.push([])

    },
    delSetting(index){
      this.setting.splice(index,1)
      this.videoList.splice(index,1)
    },
    handleClosegroupUser(list){
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
    },

    //首次刷新
    courseChange(content,index,countIndex){

      this.courseUpdate(content,index,countIndex);
    },

    //修改
    courseChangeUpdate(content,index,countIndex){
      this.$set(content, 'videoId', null);
      this.$set(content, 'linkTitle', null);
      this.$set(content, 'linkDescribe', null);
      this.$set(content, 'linkImageUrl', null);
      //如果是链接的才上
      if (content.contentType==3 && content.type==2 && content.courseId!=null){

        // 查找选中的课程对应的 label
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === content.courseId);

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

      this.courseUpdate(content,index,countIndex);
    },

    courseUpdate(content,index,countIndex){
      videoList(content.courseId).then(response => {

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

      });
    },
    handleContentTypeChange(content,index,countIndex){

      //如果是链接的才上
      if (content.contentType==3 && content.type==2 ) {

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

          //响应式直接给链接的标题/封面上值
          if (selectedCourse) {
            this.$set(content, 'linkTitle', selectedCourse.dictLabel);
            this.$set(content, 'linkImageUrl', selectedCourse.dictImgUrl);
          }
        }
        if (content.videoId!=null){
          // 查找选中的课程对应的 label
          const selectedVideo = this.videoList[index][countIndex].find(course => parseInt(course.dictValue) === content.videoId);

          //响应式直接给链接的描述上值
          if (selectedVideo) {
            this.$set(content, 'linkDescribe', selectedVideo.dictLabel);
          }
        }

      }
    },
    videoIdChange(content,index,countIndex){

      //选择了课程小节则 默认绑上
      this.$set(content,'isBindUrl','1');

      //如果是链接的才上
      if (content.contentType==3 && content.type==2 && content.videoId!=null) {

        // 查找选中的课程对应的 label
        const selectedVideo = this.videoList[index][countIndex].find(course => parseInt(course.dictValue) === content.videoId);

        //响应式直接给链接的描述上值
        if (selectedVideo) {
          this.$set(content, 'linkDescribe', selectedVideo.dictLabel);
        }
      }

    },
    //上传文件
    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 < 30;
      if (!isLt1M) {
        this.$message.error('上传大小不能超过 30MB!');
      }
      return isLt1M;
    },

    //下载文件
    downloadUrl(materialUrl) {
      // 直接返回文件 URL
      return materialUrl;
    },

    handleAvatarSuccessVideo(res, file, content) {
      if(res.code==200){
        // 使用 $set 确保响应式更新
        this.$set(content, 'videoUrl', res.url);
      }
      else{
        this.msgError(res.msg);
      }
    },
    beforeAvatarUploadVideo(file){
      const isLt30M = file.size / 1024 / 1024 < 50;
      const isMP4 = file.type === 'video/mp4';

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

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

      return true;
    },

    handleAvatarSuccessVoice(res, file, content){
      if(res.code==200){
        // 使用 $set 确保响应式更新
        this.$set(content, 'voiceUrl', res.url);
      }
      else{
        this.msgError(res.msg);
      }
    },
    beforeAvatarUploadVoice(file){
      const isLt10M = file.size / 1024 / 1024 < 10; //语音文件大小限制为10MB
      const isVoiceType = ['audio/mp3'].includes(file.type); // 支持的语音文件类型

      if (!isVoiceType) {
        this.$message.error('仅支持上传 MP3 格式的语音文件!');
        return false;
      }

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

      return true;
    },
    /** 查询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");
    },



    /** 修改按钮操作 */
    handleUpdate(id) {

      getSopTemp(id).then(response => {
        this.videoList=[]
        this.form=response.data;
        this.setting = JSON.parse(response.data.setting);
        for (let i = 0; i < this.setting.length; i++) {
          this.videoList.push([])
          for (let j = 0; j < this.setting[i].content.length; j++) {
            this.videoList[i].push([])
            if(this.setting[i].content[j].type==2){
              if(this.setting[i].content[j].hasOwnProperty('courseId')){
                this.courseChange(this.setting[i].content[j],i,j);
              }
            }
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.setting=JSON.stringify(this.setting)
        if (valid) {
          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();

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    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>
