<template>
   <div class="app-container">
        <!-- 过滤条件 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

            <el-form-item label="规则编号" prop="id">
                <el-input v-model="queryParams.id" placeholder="请输入规则名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="规则状态 " prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择规则状态" clearable size="small"
                    @change="updateCorpId()">
                    <el-option v-for="dict in sysSopStatus" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>

            <el-form-item label="发送方式 " prop="sendType">
                <el-select v-model="queryParams.sendType" placeholder="请选择发送方式状态" clearable size="small"
                    @change="updateCorpId()">
                    <el-option v-for="dict in appSopType" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>

            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入规则名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="创建时间" prop="createTime">
                <el-date-picker clearable size="small" v-model="queryParams.createTime" type="date"
                    value-format="yyyy-MM-dd" placeholder="选择创建时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="标签" prop="tagIds">
                <div @click="hangleChangeTags()"
                    style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 250px">
                    <div style="min-height: 35px; max-height: 200px; overflow-y: auto;">
                        <el-tag type="success" closable :disable-transitions="false" v-for="list in this.selectTags"
                            :key="list.id" @close="handleCloseTags(list)" style="margin: 3px;">{{ list.name }}
                        </el-tag>
                    </div>
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 工具栏 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['app:sop:add']"
                >
                    新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['app:sop:delete']"
                >
                    删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    :loading="exportLoading"
                    @click="handleExport"
                    v-hasPermi="['app:sop:export']"
                >
                    导出
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    size="mini"
                    plain
                    type="warning"
                    icon="el-icon-edit"
                    :disabled="multiple"
                    @click="handleExecute"
                    v-hasPermi="['app:sop:exec']"
                >
                    批量执行自动化
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 数据表格 -->
        <el-table v-loading="loading" border :data="sopList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="规则编号" align="center" prop="id" min-width="160" />
            <el-table-column label="规则名称" align="center" prop="name" min-width="150" />
            <el-table-column label="规则状态" align="center" prop="status" min-width="150">
                <template slot-scope="scope">
                    <dict-tag :options="sysSopStatus" :value="scope.row.status"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column label="发送方式" align="center" prop="sendType">
                <template slot-scope="scope">
                    <dict-tag :options="appSopType" :value="scope.row.sendType" />
                </template>
            </el-table-column>

            <el-table-column label="模板" align="center" prop="tempId">
                <template slot-scope="scope">
                    <div v-for="id in tempList" v-if="id.id == scope.row.tempId">{{ id.name }}</div>
                </template>
            </el-table-column>

            <el-table-column label="新客户自动创建自动化" align="center" prop="isAutoSop" min-width="180">
                <template slot-scope="scope">
                    <el-switch v-if="scope.row.sendType == 2 || scope.row.sendType != 4" v-model="scope.row.isAutoSop"
                        active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2"
                        @change="switchAutoSopChange(scope.row, scope.row.isAutoSop)">
                    </el-switch>
                    <span v-if="scope.row.sendType != 1 && scope.row.sendType != 4 && scope.row.isAutoSop == '1'"
                        style="margin-left: 10px;color: #13ce66">已开启</span>
                    <span v-if="scope.row.sendType != 1 && scope.row.sendType != 4 && scope.row.isAutoSop == '2'"
                        style="margin-left: 10px;color: #ff4949">已关闭</span>
                </template>
            </el-table-column>
            <el-table-column label="过期时间" align="center" prop="expiryTime">
                <template slot-scope="scope">
                    {{ scope.row.expiryTime }} 小时
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
            <el-table-column label="修改规则状态时间" align="center" prop="stopTime" min-width="180" />
            <el-table-column label="查看操作" align="center" class-name="small-padding fixed-width" min-width="200"
                fixed="right">
                <!-- 任务状态为 非待执行 则有以下操作-->
                <template slot-scope="scope">
                    <el-button
                        v-if="[0, 2, 3, 4].includes(Number(scope.row.status)) && scope.row.sendType != 4"
                        size="mini" type="text" @click="selectSchedule(scope.row)">营期
                    </el-button>
                    <el-button
                        v-if="[0, 2, 3, 4].includes(Number(scope.row.status)) || scope.row.sendType == 4"
                        size="mini" type="text" style="color: green;" @click="handleScheduleDetail(scope.row)">执行详情
                    </el-button>
                    <el-button
                        v-if="[0, 2, 3, 4].includes(Number(scope.row.status))"
                        size="mini" type="text" @click="handleUpdate(scope.row, 2)">查看规则
                    </el-button>
                    <el-button
                        v-if="[0, 2, 3, 4].includes(Number(scope.row.status))"
                        size="mini" type="text" style="color: green;" @click="handleQueryDetails(scope.row)">查看模板
                    </el-button>

                </template>
            </el-table-column>
            <el-table-column label="修改操作" align="center" class-name="small-padding fixed-width" min-width="100"
                fixed="right">
                <template slot-scope="scope">
                    <el-button
                        v-if="scope.row.sendType != 4"
                        size="mini"
                        type="text"
                        @click="handleUpdateOutTime(scope.row)"
                        v-hasPermi="['app:sop:edit']"
                    >
                        修改规则
                    </el-button>
                    <el-button
                        v-if="scope.row.status == 1"
                        size="mini"
                        type="text"
                        @click="handleUpdate(scope.row, 1)"
                        v-hasPermi="['app:sop:edit']"
                    >
                        修改任务
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        style="color: red;"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['app:sop:delete']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改sop对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <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="parseInt(dict.dictValue)">{{ dict.dictLabel }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker clearable size="small" v-model="form.startTime" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="模板" prop="tempId">
                    <el-select v-model="form.tempId" @focus="selectListSopTemp(form.sendType)" placeholder="请选择模板"
                        v-loading="tempListLoading">
                        <el-option v-for="dict in tempList" :label="dict.name" :value="dict.id">
                        </el-option>
                        <div v-if="tempListLoading" slot="prefix" class="select-prefix">正在查询相应模板...</div>
                    </el-select>
                </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="changeTagDialog.title" :visible.sync="changeTagDialog.open" width="1000px" append-to-body>
            <div>搜索标签：
                <el-input v-model="queryTagParams.name" placeholder="请输入标签名称" clearable size="small"
                    style="width: 200px;margin-right: 10px" />
                <el-button type="primary" icon="el-icon-search" size="mini"
                    @click="handleSearchTags(queryTagParams.name)">
                    搜索
                </el-button>
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="cancelSearchTags">重置</el-button>
            </div>
            <div v-for="item in tagGroupList" :key="item.id">
                <div style="font-size: 20px;margin-top: 20px;margin-bottom: 20px;">
                    <span class="name-background">{{ item.name }}</span>
                </div>
                <div class="tag-container">
                    <a v-for="tagItem in item.tags" class="tag-box" @click="tagSelection(tagItem)"
                        :class="{ 'tag-selected': tagItem.isSelected || (selectTags && selectTags.some(tg => tg.id == tagItem.id)) }">
                        {{ tagItem.name }}
                    </a>
                </div>
            </div>
            <pagination v-show="tagTotal > 0" :total="tagTotal" :page.sync="queryTagParams.pageNum"
                :limit.sync="queryTagParams.pageSize" @pagination="getPageListTagGroup" />
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="tagSubmitForm()">确 定</el-button>
                <el-button @click="tagCancel()">取消</el-button>
            </div>
        </el-dialog>

        <!-- 单独的修改时间 -->
        <el-dialog :title="outTimeOpen.title" :visible.sync="outTimeOpen.open" width="800px">

            <el-card class="box-card">
                <el-row>

                    <el-col style="margin-top: 3%; display: flex;">
                        <span style="font-size: 16px;font-weight: bold; width: 120px; display: flex; align-items: center; justify-content: end;">过期时间：</span>
                        <el-input-number v-model="outTimeOpen.expiryTime" :min="1" :max="100"/>
                        <span style="font-size: 16px;font-weight: bold; display: flex; align-items: center; justify-content: end;">（小时）</span>
                    </el-col>

                    <el-col style="margin-top: 3%; display: flex;">
                        <span style="font-size: 16px;font-weight: bold; width: 120px; display: flex; align-items: center; justify-content: end;">次要节点天数：</span>
                        <el-input v-model="outTimeOpen.minConversionDay" style="width: 200px;"/>
                        <span style="font-size: 16px;font-weight: bold; display: flex; align-items: center; justify-content: end;">（天）</span>
                    </el-col>

                    <el-col style="margin-top: 3%; display: flex;">
                        <span style="font-size: 16px;font-weight: bold; width: 120px; display: flex; align-items: center; justify-content: end;">重要节点天数：</span>
                        <el-input v-model="outTimeOpen.maxConversionDay" style="width: 200px;"/>
                        <span style="font-size: 16px;font-weight: bold; display: flex; align-items: center; justify-content: end;">（天）</span>
                    </el-col>

                    <el-col style="margin-top: 3%;">
                        <span style="font-size: 16px;font-weight: bold;">发课开始天数：</span>
                        <el-input-number v-model="outTimeOpen.courseDay" :min="1" :max="100"></el-input-number>
                        （天）
                        <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-top: 2%">
                            <i class="el-icon-info"></i>
                            作用于【提醒看板】和【学习记录】的统计，由多少天开始计算。比如 模板里
                            第一天是先导课，第二天是正课，此处设置天数为2，则统计从第二天开始。如果无视模板天数，此处设置几天，则统计面板就从第几天开始统计
                        </div>
                    </el-col>

                    <el-col style="margin: 3% ">

                        <div style="float: right;margin-right: 3%">
                            <el-button type="primary" icon="el-icon-search" size="mini"
                                @click="handleUpdateExpiryTime">确定修改
                            </el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetUpdateExpiryTime">取消</el-button>
                        </div>
                    </el-col>

                </el-row>
            </el-card>
        </el-dialog>

        <!--  -->
        <el-dialog :title="autoSopOpen.title" :visible.sync="autoSopOpen.open" width="1300px" append-to-body>
            <el-form ref="autoSopTimeFrom" :model="form.autoSopTime" :rules="autoSopTimeRules">
                <el-form-item label="自动类型" prop="type" style="margin: 2%; display: flex; align-items: center;">
                    <el-radio-group v-model="form.autoSopTime.autoSopType">
                        <el-radio :label="Number(dict.dictValue)" v-for="dict in autoSopTypeOptions">{{ dict.dictLabel }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div style="display: flex; align-items: center; flex-wrap: nowrap;">
                    <div v-if="form.autoSopTime.autoSopType == 1" style="display: flex; align-items: center">
                        <el-form-item label="起始时间" prop="autoStartTime" label-width="100px"
                            style="margin: 2% 0;align-items: center;">
                            <el-time-select style="width: 120px;" placeholder="起始时间"
                                v-model="form.autoSopTime.autoStartTime" :picker-options="{
                                    start: '00:00',
                                    step: '00:15',
                                    end: '24:00'
                                }">
                            </el-time-select>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="autoEndTime" label-width="100px"
                            style="margin: 2% 0; align-items: center; ">
                            <el-time-select style="width: 120px;" placeholder="结束时间"
                                v-model="form.autoSopTime.autoEndTime" :picker-options="{
                                    start: '00:00',
                                    step: '00:15',
                                    end: '24:00',
                                    minTime: form.autoSopTime.autoEndTime
                                }">
                            </el-time-select>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item v-if="form.autoSopTime.autoSopType == 1" label="过期消息是否发送" prop="autoSopSend"
                    style="margin: 2%; display: flex; align-items: center;">
                    <el-radio-group v-model="form.autoSopTime.autoSopSend">
                        <el-radio :label="1">是
                        </el-radio>
                        <el-radio :label="2">否
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <div style="display: flex; align-items: center; flex-wrap: nowrap;"
                    v-if="form.autoSopTime.autoSopType == 3 || form.autoSopTime.autoSopType == 4">
                    <el-form-item label="选择一个或多个日期" prop="autoDateTime" label-width="150px">
                        <el-date-picker size="large" type="dates" style="width: 600px"
                            v-model="form.autoSopTime.autoDateTime" value-format="yyyy-MM-dd"
                            placeholder="选择一个或多个日期【ps:请先选择开始时间，不得小于任务开始时间】"
                            @change="sortSelectedDates(form.autoSopTime.autoDateTime)" :disabled="!form.startTime">
                        </el-date-picker>
                    </el-form-item>
                </div>


                <el-alert v-if="form.autoSopTime.autoSopType == 1" title="起始时间-结束时间之内的，当天立即创建自动化，时间之外的 次日创建自动化"
                    type="warning" style="font-size: 30px; margin-top: 3%;" :closable="false" show-icon>
                </el-alert>
                <el-alert v-if="form.autoSopTime.autoSopType == 3" type="warning" style="margin-top: 3%;"
                    :closable="false" show-icon>
                    <template #title>
                        <span style="font-size: 23px; line-height: 1.5;">
                            此功能用于正课区分营期，可以选择你想要开始营期的具体时间，选择后在此期间添加的用户将会自动进入对应营期。
                            例如今天1月1日，选择时间是1月1日，1月5日，1月10日。
                            用户1月1日-1月4日添加（添加上对应标签）则会进入1月5日的营期，1月5日-1月9日添加则会进入1月10日营期，1月5日自动给用户发送第一节科普
                        </span>
                    </template>
                </el-alert>
                <el-alert v-if="form.autoSopTime.autoSopType == 4" title="" type="warning"
                    style="font-size: 30px; margin-top: 3%;" :closable="false" show-icon>
                    <template #title>
                        <span style="font-size: 23px; line-height: 1.5;">
                            此功能用于先导课区分营期，可以选择先导课开始营期的具体时间，选择后在此期间添加的用户将会自动进入对应营期。
                            例如今天1月1日，选择时间是1月1日，1月5日，1月10日。
                            用户1月1日-1月4日添加（添加上对应标签）则会进入1月1日的营期，1月5日-1月9日添加则会进入1月5日营期，自动给用户匹配上对应应该听到天数的时间节点
                        </span>
                    </template>
                </el-alert>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAutoSopTimeFrom">确 定</el-button>
                <el-button @click="cancelAutoSopTime">取 消</el-button>
            </div>
        </el-dialog>

        <!--  执行详情  -->
        <el-drawer :title="sopLogsDialog.title" :visible.sync="sopLogsDialog.open" size="85%"
            style="font-weight: bolder">
            <sopLogsDetails ref="sopLogsDetails" :rowDetailFrom="sopLogsDialog.sopLogsForm"></sopLogsDetails>
        </el-drawer>
    </div>
</template>

<script>
import {
  addSop,
  courseList,
  videoList,
  delSop,
  exportSop,
  getSopVoiceList,
  listSop,
  updateAutoSopTime,
  getTempUserList,
  updateTemp,
  updateSop,
  updateSopStatus,
  updateStatus
} from "@/api/app/sop/info";
import {listSopTemp} from "@/api/app/sop/template";
import ImageUpload from "@/views/app/sop/info/ImageUpload";
import sopLogsDetails from '@/views/app/sop/userLogs/sopLogsList.vue'
import { listTagGroupForUserBindTag, } from "@/api/app/tag/tagGroup";

export default {
    name: "Sop",
    components: { ImageUpload, sopLogsDetails },
    data() {
        return {
            miniAppList: [],
            // 添加以下字段
            selectTags: [], // 已选择的标签
            tagGroupList: [], // 标签组列表
            tagTotal: 0, // 标签总数
            autoSopTypeOptions: [],
            // 标签弹窗相关
            changeTagDialog: {
                title: "",
                open: false,
            },
            queryTagParams: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                name: null,
                corpId: null,
            },
            luckyBagList: [],
            luckyBag: null,
            liveList: [],
            // 存储每一行的展开状态
            expandedRows: {},
            //模板查询
            tempListLoading: false,
            // 遮罩层
            loading: false,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            //选中的map
            selectionMap: {},
            myQwCompanyList: [],
            tempUser: {
                open: false,
                id: null,
                updateOpen: false,
                loading: true,
                list: [],
                form: {
                    id: null,
                    liveTempId: null,
                    liveTempSendTime: null,
                },
            },
            //客服员工列表
            companyUserLists: [],
            videoList: [],
            uploadUrl: process.env.VUE_APP_BASE_API + "/app/common/uploadOSS",
            uploadUrlByVoice: process.env.VUE_APP_BASE_API + "/app/common/uploadOSSByHOOKVoice",
            msgForm: {
                videoId: null,
                courseId: null,
                courseType: null,
                userIdParam: null,
                sendType: 1,
                setting: null,
                ids: null,
                sopId: null,
                startTime: null,
                chatIds: [],
                isRegister: 2
            },
            msgRules: {},
            courseList: [],
            // videoList:[],
            tags: null,
            excludeTags: null,
            // 非单个禁用
            single: true,
            setting: [],
            tagList: [],
            tempList: [],
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 企微sop表格数据
            sopList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            companyUserList: [],
            // 状态字典
            statusOptions: [],
            //sop状态
            sysSopStatus: [],

            autoSopOpen: {
                title: '',
                open: false,
                id: null,
                isAutoSop: null,
            },
            outTimeOpen: {
                title: '',
                open: false,
                id: null,
                tempId: null,
                expiryTime: null,
                minConversionDay: null,
                maxConversionDay: null,
                isLiveMgs: 0,
                liveTempId: null,
                liveTempSendTime: null,
                appId: null
            },
            voiceForm: {
                list: [],
                open: false,
                total: 0,
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    id: null,
                },
            },

            //SOP发送类型
            appSopType: [],
            chatList: [],

            //SOP科普观看状态
            sysFsSopWatchStatus: [],
            //插件版
            sysQwSopAiContentType: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                id: null,
                name: null,
                status: null,
                sendType: null,
                createTime: null,
                tagIds: null,
            },
            sopLogsDialog: {
                title: '',
                open: false,
                sopLogsForm: [],
            },
            // 表单参数
            form: {
                autoSopTime: { autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2, autoDateTime: [] },
            },
            courseLiveTempOption: [],
            userSelectList: [],
            listUser: {
                title: "",
                open: false
            },
            // 表单校验
            rules: {
                name: [{ required: true, message: "名称不能为空", trigger: "submit" }],
                type: [{ required: true, message: "不能为空", trigger: "submit" }],
                sendType: [{ required: true, message: "不能为空", trigger: "submit" }],
                startTime: [{ required: true, message: "开始时间不能为空", trigger: "submit" }],
                tempId: [{ required: true, message: "模板不能为空", trigger: "submit" }],
            },
            autoSopTimeRules: {
                autoSopType: [{ required: true, message: "选项不能为空", trigger: "submit" }],
                autoStartTime: [{ required: true, message: "起始时间不能为空", trigger: "submit" }],
                autoEndTime: [{ required: true, message: "结束时间不能为空", trigger: "submit" }],
                autoDateTime: [{ required: true, message: "日期不能为空", trigger: "submit" }],
            }
        };
    },
    created() {
        this.init();
    },
    watch: {
        userSelectList(newList) {
            this.form.qwUserIds = newList.map(item => item.id);
        }
    },
    methods: {
        /**
         * 初始化加载
         */
        async init() {
            this.getDicts("app_sop_status").then(response => {
                this.sysSopStatus = response.data;
            });
            this.getDicts("app_sop_plugin_settingType").then(response => {
                this.sysQwSopAiContentType = response.data;
            });
            this.getDicts("app_sop_watch_status").then(response => {
                this.sysFsSopWatchStatus = response.data;
            });
            this.getDicts("app_normal_disabled_status").then(response => {
                this.statusOptions = response.data;
            });
            this.getDicts("app_sop_autoType").then(response => {
                this.autoSopTypeOptions = response.data;
            });
            this.getDicts("app_sop_type").then(response => {
                this.appSopType = response.data;
            });
            let cl = this.getCourseList(null);
            this.courseList = cl.list;
            this.getList();
        },
        /**
         * 获取科普列表
         * @param keyword
         */
        async getCourseList(keyword) {
            let query = {
                keyword: keyword,
                pageNum: 1,
                pageSize: 50,
            };
            return await courseList(query);
        },
        // 搜索的标签
        hangleChangeTags() {
            this.changeTagDialog.title = "搜索的标签"
            this.changeTagDialog.open = true;
            this.queryTagParams.name = null;
            this.getPageListTagGroup();
        },

        // 删除一些选择的标签
        handleCloseTags(list) {
            const ls = this.selectTags.findIndex(t => t.id === list.id);
            if (ls !== -1) {
                this.selectTags.splice(ls, 1);
                this.selectTags = [...this.selectTags];
            }

            if (this.selectTags != null && this.selectTags.length > 0) {
                // 确保 this.form.tags 是数组
                if (!this.queryParams.tagIds) {
                    this.queryParams.tagIds = []; // 如果未定义，初始化
                } else {
                    this.queryParams.tagIds = []; // 清空已有数据
                }

                // 遍历并添加 tagId
                this.selectTags.forEach(tag => {
                    if (tag.id) { // 确保 tagId 存在
                        this.queryParams.tagIds.push(tag.id);
                    }
                });
                this.queryParams.tagIds = this.queryParams.tagIds.join(",");
            } else {
                this.queryParams.tagIds = null;
            }
        },

        // 选择/取消选择标签
        tagSelection(row) {
            row.isSelected = !row.isSelected;
            this.$forceUpdate();
        },

        // 确定选择标签
        tagSubmitForm() {
            for (let i = 0; i < this.tagGroupList.length; i++) {
                for (let x = 0; x < this.tagGroupList[i].tags.length; x++) {
                    if (this.tagGroupList[i].tags[x].isSelected === true) {
                        if (!this.selectTags) {
                            this.selectTags = [];
                        }

                        // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
                        let tagExists = this.selectTags.some(
                            tag => tag.id === this.tagGroupList[i].tags[x].id
                        );

                        // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
                        if (!tagExists) {
                            this.selectTags.push(this.tagGroupList[i].tags[x]);
                        }
                    }
                }
            }
            if (!this.selectTags || this.selectTags.length === 0) {
                return this.$message('请选择标签');
            }

            this.changeTagDialog.open = false;
        },

        // 取消选择标签
        tagCancel() {
            this.changeTagDialog.open = false;
        },

        // 获取标签组列表
        getPageListTagGroup() {
            //   this.queryTagParams.corpId = this.queryParams.corpId
            let qp = {...this.queryTagParams, groupName: this.queryTagParams.name}
            listTagGroupForUserBindTag(qp).then(response => {
                let rows = response.rows;
                this.tagGroupList = rows;
                this.tagTotal = response.total;
            });
        },

        // 搜索标签
        handleSearchTags(name) {
            this.getPageListTagGroup();
        },

        // 重置标签搜索
        cancelSearchTags() {
            this.resetSearchQueryTag()
            this.getPageListTagGroup();
        },

        // 重置标签查询参数
        resetSearchQueryTag() {
            this.queryTagParams = {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                name: null,
            };
        },

        // 在组件销毁前保存当前选择
        beforeDestroy() {
            // if (this.queryParams.corpId) {
            //     localStorage.setItem('selectedCorpId', this.queryParams.corpId);
            // }
        },
        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();
        },
        liveChange(content) {
            // content.liveId 是选中的直播间 ID（liveId）
            const selectedLive = this.liveList.find(live => live.liveId === content.liveId);
            if (selectedLive) {
                // 从选中的直播间对象中提取标题和封面，赋值给当前内容的对应字段
                // 假设直播间对象中标题字段为 liveTitle，封面字段为 coverImg（根据实际接口字段调整）
                content.miniprogramTitle = selectedLive.liveName || ''; // 自动填充标题
                content.miniprogramPicUrl = selectedLive.liveImgUrl || ''; // 自动填充封面
            } else {
                // 若未找到对应直播间，清空标题和封面（可选）
                content.miniprogramTitle = '';
                content.miniprogramPicUrl = '';
            }
        },
        voice(id) {
            this.voiceForm.queryParams.id = id;
            getSopVoiceList(this.voiceForm.queryParams).then(res => {
                this.voiceForm.list = res.rows;
                this.voiceForm.total = res.total;
                this.voiceForm.open = true;
            })
        },
        // 单元格点击事件
        handleCellClick(row, column, cell, event) {
            // 判断是否为规则编号列
            if (column.property === 'id') {
                this.handleRowClick(row); // 触发规则编号点击事件
            }
        },
        // handleUpdateTags(){
        //
        // },
        // handleUpdateQwUser(){
        //
        // },
        // handleUpdateSopTemp(){
        //
        // },
        handleRowClick(row, column, event) {
            // 判断状态是否符合条件
            if (row.status == 2 || row.status == 0 || row.status == 3 || row.status == 4) {
                this.handleUpdate(row, 2);
            }
        },
        // 切换某一行的展开状态
        toggleRow(row) {
            this.$set(this.expandedRows, row.id, !this.expandedRows[row.id]);
        },
        getSwitchVal(status) {
            return [2, 3, 4].includes(status) ? 2 : 0;
        },

        onSwitchChange(row, val) {
            this.loading = true;
            // ① 调用接口更新后端
            updateSopStatus({ id: row.id, status: val })
                .then(() => {
                    row.status = val;
                    this.loading = false;
                    this.$message.success("切换成功！");
                })
                .catch(() => {
                    this.loading = false;
                    this.$message.error("操作失败，请重试");
                });
        },

        switchSopStatusChange(row, checked) {

            let loadingRock = this.$loading({
                lock: true,
                text: '暂停中-请勿刷新页面-重复点击',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });


            updateSopStatus({ id: row, status: checked }).then(response => {
                this.$message.success("修改成功");
                this.getList();
            }).finally(res => {
                loadingRock.close();
            })
        },
        /**
         * 新客户自动创建sop
         * @param row
         * @param checked
         */
        switchAutoSopChange(row, checked) {
            this.form.startTime = row.startTime;
            this.form.autoSopTime = JSON.parse(row.autoSopTime);
            if (checked == 1) {
                this.autoSopOpen.title = '请设置相应时间段'
                this.autoSopOpen.open = true;
                this.autoSopOpen.id = row.id;
                this.autoSopOpen.isAutoSop = 1;
            } else {
                this.form.autoSopTime.createTime = this.formatDateTo24HourString(new Date());
                updateAutoSopTime({
                    id: row.id,
                    isAutoSop: checked,
                    autoSopTime: JSON.stringify(this.form.autoSopTime)
                }).then(response => {
                    this.getList();
                })
            }
        },
        updateCorpId() {
            if (this.queryParams.corpId) {
                localStorage.setItem('selectedCorpId', this.queryParams.corpId);
            }
            this.reset();
            this.refreshData(this.queryParams.corpId);
            this.queryParams.qwUserId = null;
            this.getList();
        },

        //刷新部分数据
        refreshData(row) {
            //   getQwAllUserList(row).then(response => {
            //     this.companyUserList = response.data;
            //   });

            //   listTag({corpId: row}).then(response => {
            //     this.tagList = response.rows;
            //   });

            if (row != null) {
                // allList(row).then(e => {
                //   this.chatList = e.data;
                // })
            }
        },

        //查询模板
        selectListSopTemp(type) {
            this.tempListLoading = true; // 开始查询，显示加载提示
            listSopTemp({ sendType: type }).then(response => {
                this.tempList = response.rows;
                this.tempListLoading = false;
            });
        },
        handlelistUser(type, sendType) {

            setTimeout(() => {
                this.$refs.QwUserList.getDetails(this.queryParams.corpId, type, sendType);
            }, 1);
            this.listUser.title = "选择企业成员"
            this.listUser.open = true;

        },
        selectUserList(list) {
            this.listUser.open = false;
            list.forEach(obj => {
                if (!this.userSelectList.some(item => item == obj.id)) {
                    this.userSelectList.push(obj.id);
                }
            });

        },

        //修改过期时间
        handleUpdateTemp(val) {
            this.tempUser.updateOpen = true;
            this.tempUser.form = {
                id: val.id,
                qwId: val.qwId,
                liveTempId: val.tempId,
                liveTempSendTime: val.sendTime,
            }
        },
        //修改过期时间
        submitTemp() {
            if (this.tempUser.form.liveTempId == null) {
                return this.$message.error("请选择直播模板")
            }
            if (this.tempUser.form.liveTempSendTime == null) {
                return this.$message.error("请选择发送时间")
            }
            updateTemp({ id: this.tempUser.form.id, sopId: this.tempUser.id, tempId: this.tempUser.form.liveTempId, sendTime: this.tempUser.form.liveTempSendTime, qwId: this.tempUser.form.qwId }).then(response => {
                this.msgSuccess("修改成功");
                this.tempUser.updateOpen = false;
                this.listTemp();
            });
        },
        handleUpdateOutTime(val) {
            this.outTimeOpen.title = "修改过期时间/评级";
            this.outTimeOpen.id = val.id;
            this.outTimeOpen.tempId = val.tempId;
            this.outTimeOpen.expiryTime = val.expiryTime;
            this.outTimeOpen.isRating = val.isRating;
            this.outTimeOpen.minConversionDay = val.minConversionDay;
            this.outTimeOpen.maxConversionDay = val.maxConversionDay;
            this.outTimeOpen.courseDay = val.courseDay;
            this.outTimeOpen.isSampSend = val.isSampSend;
            this.outTimeOpen.isLiveMgs = val.isLiveMgs;
            this.outTimeOpen.liveTempId = val.liveTempId;
            this.outTimeOpen.liveTempSendTime = val.liveTempSendTime;
            this.outTimeOpen.appId = val.appId;
            this.outTimeOpen.open = true;
        },

        handleUpdateExpiryTime() {
            updateSop({
                id: this.outTimeOpen.id,
                tempId: this.outTimeOpen.tempId,
                expiryTime: this.outTimeOpen.expiryTime,
                isRating: this.outTimeOpen.isRating,
                minConversionDay: this.outTimeOpen.minConversionDay,
                maxConversionDay: this.outTimeOpen.maxConversionDay,
                courseDay: this.outTimeOpen.courseDay,
                isLiveMgs: this.outTimeOpen.isLiveMgs,
                liveTempId: this.outTimeOpen.liveTempId,
                liveTempSendTime: this.outTimeOpen.liveTempSendTime,
                isSampSend: this.outTimeOpen.isSampSend,
                appId: this.outTimeOpen.appId,
            }).then(response => {
                this.msgSuccess("修改成功");
                this.resetUpdateExpiryTime()
                this.getList();
            });
        },
        resetUpdateExpiryTime() {
            this.outTimeOpen = {
                title: '',
                open: false,
                id: null,
                expiryTime: null,
                courseDay: null,
                isLiveMgs: 0,
                liveTempId: null,
                liveTempSendTime: null,
                minConversionDay: null,
                maxConversionDay: null,
                isRating: null,
                isSampSend: null,
                appId: null
            }
        },
        addContent(index) {
            // this.setting[index].content.push({type:1})
            if (this.form.sendType == 2) {
                this.setting[index].content.push({ type: 1 });
            } else {
                if (this.setting[index].content.length < 9) {
                    this.setting[index].content.push({ type: 1 });
                } else {
                    this.$message({
                        message: '最多只能添加 9 个内容',
                        type: 'warning'
                    });
                }
            }

        },

        //选择变动时的变动
        handleSendTypeChange(val) {
            this.tempList = [];
            this.form.tempId = null;
            if (val == 1) {
                // 遍历 this.setting 数组并清空每个对象的 content 属性
                this.setting.forEach(item => {
                    if (item.content.length > 9) {
                        item.content = item.content.slice(0, 9); // 保留前 9 个元素
                    }
                });
            }
        },
        delContent(index, contentIndex) {
            this.setting[index].content.splice(contentIndex, 1)
        },

        //添加SOP规则类型
        handleCommand(command) {
            this.setting.push({
                sopType: command,
                ruleType: null,
                name: null,
                type: 1,
                content: [],
                isBindUrl: 1,
                url: null,
                day: "0",
                hour: "0",
                minute: "0",
                time: ""
            })
        },

        //添加科普SOP
        handleCrouseCommand(command, val) {

        },

        delSetting(index) {
            this.setting.splice(index, 1)
        },
        handleClosegroupUser(list) {
            const index = this.userSelectList.findIndex(t => t === list);
            if (index !== -1) {
                this.userSelectList.splice(index, 1);
            }
        },
        /**
         * 查询sop列表
         */
        getList() {
            this.loading = true;
            listSop(this.queryParams).then(response => {
                this.sopList = response.rows;
                this.total = response.total;
                this.loading = false;
                listSopTemp().then(res => {
                    this.tempList = res.rows;
                });

            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                status: 1,
                sendType: 2,
                type: 2,
                filterType: 2,
                isLiveMgs: 0,
                qwUserIds: null,
                liveTempId: null,
                liveTempSendTime: null,
                corpId: null,
                setting: null,
                createBy: null,
                createTime: null,
                isAutoSop: null,
                autoSopTime: { autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2, autoDateTime: [] },
            };
            this.resetForm("form");
            this.tags = null;
            this.excludeTags = null;
        },
        /** 搜索按钮操作 */
        handleQuery() {
            // 处理标签ID参数
            if (this.selectTags != null && this.selectTags.length > 0) {
                this.queryParams.tagIds = this.selectTags.map(tag => tag.id).join(",");
            } else {
                this.queryParams.tagIds = null;
            }
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            // this.queryParams.corpId = this.myQwCompanyList[0].dictValue;
            this.selectTags = null;
            this.refreshData(this.queryParams.corpId);
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.selectionMap = selection;
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        // 新增按钮操作
        handleAdd() {
            this.reset();
            this.$router.push('/app/sop/addSop')
        },
        /** 修改按钮操作 */
        handleUpdate(row, type) {
            this.$router.push('/app/sop/updateSop/' + row.id + '/' + type)
        },
        handleTemp(id) {
            this.tempUser.open = true;
            this.tempUser.id = id;
            this.listTemp();
        },
        listTemp() {
            this.tempUser.loading = true;
            getTempUserList(this.tempUser.id).then(e => {
                this.tempUser.list = e.data;
                this.tempUser.loading = false;
            })
        },

        /**
         * 查看SOP任务内营期
         */
        selectSchedule(row) {
            // type 2：我的sop 1：部门sop/客服公司sop
            const query = {
                id: row.id,
                name: row.name,
                tempId: row.tempId,
                filterMode: row.filterMode,
                // corpId: row.corpId,
                type: 1,
            }
            // 使用 params 传递参数
            this.$router.push({
                path: `/app/sop/sopUserLogsSchedule/${query.id}`,
                query // 如果需要传递更多参数，可以使用 query
            });
        },


        /**
         * 查看营期内详情
         */
        handleScheduleDetail(row) {
            this.sopLogsDialog.title = '规则执行详情7';
            this.sopLogsDialog.open = true;
            this.sopLogsDialog.sopLogsForm = row;
            // 使用Vue.set或this.$set添加新字段
            this.$set(this.sopLogsDialog.sopLogsForm, 'filterSopType', 1);
        },

        /**
         * 查看模板
         */
        handleQueryDetails(row) {
            this.$router.push(`/user/sopTemp/updateSopTemp/${row.tempId}/3`)
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.userSelectList.length <= 0) {
                        return this.$message("请选择员工")
                    }
                    this.form.qwUserIds = this.userSelectList.join(",");
                    if (this.tags != null && this.tags.length > 0) {
                        this.form.tags = (this.tags).toString()
                    } else {
                        return this.$message.error("选择的标签不能为空！！请选择筛选的标签")
                    }
                    if (this.excludeTags != null) {
                        this.form.excludeTags = (this.excludeTags).toString()
                    }

                    this.form.setting = JSON.stringify(this.setting)
                    if (this.form.id != null) {
                        updateSop(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addSop(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        sortSelectedDates(dates) {

            if (!this.form.startTime) {
                this.$message.error("请先选择开始时间！不得小于任务开始时间");
                this.form.autoSopTime.autoDateTime = [];
                return;
            }

            // 1. 过滤掉 < startTime 的日期
            const validDates = dates.filter(date => new Date(date) >= new Date(this.form.startTime));

            // 2. 如果有被过滤掉的日期，提示用户
            if (validDates.length < dates.length) {
                this.$message.warning(`已自动移除小于 ${this.form.startTime} 的日期！`);
            }

            // 3. 升序排序
            validDates.sort((a, b) => new Date(a) - new Date(b));

            // 4. 更新数据
            this.form.autoSopTime.autoDateTime = validDates;
        },

        submitAutoSopTimeFrom() {

            if (this.form.autoSopTime.autoSopType == 3 || this.form.autoSopTime.autoSopType == 4) {
                if (this.form.autoSopTime.autoDateTime == null || this.form.autoSopTime.autoDateTime == "") {
                    return this.$message.error("选择的日期不能为空！！请选择日期")
                }
            }

            this.$refs["autoSopTimeFrom"].validate(valid => {
                if (valid) {
                    this.autoSopOpen.open = false
                    this.form.autoSopTime.createTime = this.formatDateTo24HourString(new Date());
                    updateAutoSopTime({
                        id: this.autoSopOpen.id,
                        isAutoSop: this.autoSopOpen.isAutoSop,
                        autoSopTime: JSON.stringify(this.form.autoSopTime)
                    }).then(response => {
                        this.msgSuccess("修改成功");
                    });
                }
                this.getList();
                this.reset();
            });
        },

        formatDateTo24HourString(date) {
            let year = date.getFullYear();
            let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份需要加 1 并补零
            let day = ('0' + date.getDate()).slice(-2); // 日需要补零
            let hours = ('0' + date.getHours()).slice(-2); // 小时需要补零
            let minutes = ('0' + date.getMinutes()).slice(-2); // 分钟需要补零
            let seconds = ('0' + date.getSeconds()).slice(-2); // 秒需要补零

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        cancelAutoSopTime() {
            this.autoSopOpen.open = false
            this.getList();
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除企微自动化编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delSop(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /**
         * 批量执行SOP任务
         */
        handleExecute() {
            const ids = this.selectionMap
                .filter(item => item.status === 1)
                .map(item => item.id);
            if (ids.length === 0) {
                this.msgError("选择的任务已经执行或正在执行，请选择待执行的任务");
                return;
            }
            this.$confirm('是否确认立即执行自动化编号为"' + ids + '"的数据项?', "警告【只能立即执行（待执行的）】", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.loading = true;
                // 执行更新操作
                return updateStatus(ids); // 返回一个Promise，直接在此链式调用
            }).then(res => {
                let msg = "";

                // 判断成功和失败的任务，并显示消息
                if (res.suc.length > 0) {
                    msg += "执行成功的自动化任务【" + res.suc.join(", ") + "】。<br>"; // 优化：将数组转换为字符串
                }
                if (res.err.length > 0) {
                    msg += "失败的自动化任务【" + res.err.join(", ") + "】，原因是已经执行或正在执行。<br>";
                }

                // 显示确认框，显示成功与失败信息
                return this.$confirm(msg, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    dangerouslyUseHTMLString: true // 允许HTML标签
                });

            }).then(() => {
                // 操作完成后刷新列表，并显示成功信息
                this.getList();
                this.msgSuccess("执行完成");
            }).catch(() => {
                // 处理任何异常，操作取消或者失败时显示提示信息
                this.msgError("操作失败，请重试");
            }).finally(() => {
                this.loading = false; // 操作完成后关闭加载状态
            });

        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有企微自动化数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportSop(queryParams);
            }).then(response => {
                this.download(response.msg);
                this.exportLoading = false;
            }).catch(() => {
            });
        },
        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.setting[i].contentType == 3 && this.msgForm.courseId != null) {
                        this.$set(this.setting[i], 'linkTitle', selectedCourse.dictLabel);
                        this.$set(this.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
                    }

                }

            }
            videoList(this.msgForm.courseId).then(response => {
                this.videoList = response.list;
            });
        },
        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.$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.$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: '',
            };
            // 将新设置项添加到 content.setting 数组中
            this.setting.push(newSetting);

        },
        isEmpty(obj) {
            if (null === obj || undefined === obj || 0 === obj.length) {
                return true;
            }
            return false;
        },
        videoIdChange() {
            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.$set(this.setting[i], 'miniprogramTitle', selectedVideo.dictLabel);
                        }


                    }
                }
            }
        },
    }
}
;
</script>
<style scoped>
.custom-input ::v-deep  .el-input__inner {
  height: 20px;
  padding: 0 4px;
  text-align: center;
  display: block;
}

.custom-input ::v-deep  .el-input__icon {
  line-height: 20px;
}

.el-button--text {
  cursor: pointer;
}

/* CSS 样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap; /* 超出宽度时自动换行 */
  gap: 8px; /* 设置标签之间的间距 */
}

.name-background {
  display: inline-block;
  background-color: #abece6; /* 背景颜色 */
  padding: 4px 8px; /* 调整内边距，让背景包裹文字 */
  border-radius: 4px; /* 可选：设置圆角 */
}

.tag-box {
  padding: 8px 12px;
  border: 1px solid #989797;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.tag-selected {
  background-color: #00bc98;
  color: #fff;
  border-color: #00bc98;
}
</style>
