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

            <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="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                    <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>

            <el-form-item label="科普" prop="courseId">
                <el-select
                    v-model="queryParams.courseId"
                    placeholder="默认50条，可输入关键字检索"
                    style=" margin-right: 10px;"
                    size="mini"
                    filterable
                    clearable
                    :loading="courseLoading"
                    remote
                    :remote-method="(keyword) => handleCourseRemoteSearch(keyword, 0)"
                    @change="courseChangeUpdate(0)"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option
                        v-for="dict in queryCourseList"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="parseInt(dict.dictValue)"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="小节" prop="videoId">
                <el-select
                    v-model="queryParams.videoId"
                    placeholder="请选择小节"
                    size="mini"
                    style=" margin-right: 10px;"
                    filterable
                    clearable
                    :disabled="!queryParams.courseId"
                    @change="videoIdChange(0)"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option
                        v-for="dict in queryVideoList"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="parseInt(dict.dictValue)"
                    >
                        <div :style="{ color: dict.isPause == 1 ? '#f56c6c' : 'inherit', display: 'flex', alignItems: 'center' }">
                            <span>{{ dict.dictLabel }}</span>
                            <span v-if="dict.isPause == 1" style="font-size: 12px; margin-left: 8px; color: #f56c6c;">
                                (该科普已被关闭)
                            </span>
                        </div>
                    </el-option>
                </el-select>
            </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:finishTemp:add']"
                >
                    新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDelete"
                    :disabled="multiple"
                    v-hasPermi="['app:finishTemp:delete']"
                >
                    删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="courseFinishTempList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="模板ID" align="center" prop="id" />
            <el-table-column label="模板名称" align="center" prop="name" />
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="statusOptions" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="科普名称" align="center" prop="courseName" />
            <el-table-column label="小节名称" align="center" prop="videoName" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="修改时间" align="center" prop="updateTime" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row, true)"
                        v-hasPermi="['app:finishTemp:edit']"
                    >
                        修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-s-promotion"
                        @click="handleUpdate(scope.row, false)"
                    >
                        详情
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['app:finishTemp: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" />

        <!-- 添加或修改完课模板对话框 -->
        <el-dialog
            :title="addForm.title"
            :visible.sync="addForm.visible"
            width="1000px"
            v-loading="addForm.loading"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">

                <el-form-item label="模板名称" prop="name">
                    <el-input v-model="addForm.name" :disabled="!addForm.canOp" placeholder="请输入模板名称" />
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.status">
                        <el-radio v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :disabled="!addForm.canOp"
                            :label="parseInt(dict.dictValue)"
                        >
                            {{ dict.dictLabel }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="科普"
                    style="margin-bottom: 15px;"
                    prop="videoId"
                >
                
                    <el-select
                        v-model="addForm.courseId"
                        placeholder="默认50条，可输入关键字检索"
                        style=" margin-right: 10px;"
                        size="mini"
                        filterable
                        clearable
                        :loading="courseLoading"
                        remote
                        :disabled="!addForm.canOp"
                        :remote-method="(keyword) => handleCourseRemoteSearch(keyword, 1)"
                        @change="courseChangeUpdate(1)"
                    >
                        <el-option
                            v-for="dict in courseList"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="parseInt(dict.dictValue)"
                        />
                    </el-select>

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

                    <!-- 默认完课消息 -->
                    <el-select
                        v-model="addForm.courseType"
                        placeholder="请选择消息类型"
                        size="mini"
                        style=" margin-right: 10px;"
                        disabled
                    >
                        <el-option
                            v-for="dict in sysFsSopWatchStatus"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="Number(dict.dictValue)"
                        />
                    </el-select>

                </el-form-item>

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

                                    </el-form-item>

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

                                    </el-form-item>

                                    <!-- 文本 -->
                                    <el-form-item label="内容" v-else-if="[11].includes(Number(content.contentType))">
                                        <el-input
                                            v-model="content.value"
                                            type="textarea"
                                            :rows="3"
                                            placeholder="内容"
                                            :disabled="!addForm.canOp"
                                            style="width: 90%; margin-top: 10px;"
                                            @keydown.native="handleKeydown($event, contentIndex)"
                                            :ref="`textarea-${contentIndex}`"
                                        />

                                    </el-form-item>

                                    <!-- 语音 -->
                                    <el-form-item label="内容" v-else-if="[12].includes(Number(content.contentType))">

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

                                        </div>

                                    </el-form-item>

                                    <!-- 图片 -->
                                    <el-form-item label="内容" v-else-if="[2].includes(Number(content.contentType))">

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

                                    </el-form-item>

                                    <!-- 视频 -->
                                    <el-form-item label="内容" v-else-if="[6].includes(Number(content.contentType))">

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

                                    </el-form-item>

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

                                    </el-form-item>

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

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

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

                <el-form-item label="所属客服" prop="appCustomerIds" label-width="100px">
                    <div>
                        <el-button size="medium" icon="el-icon-circle-plus-outline" plain :disabled="!addForm.canOp"
                            @click="openSelectCustomerPage">请选择客服</el-button>
                    </div>
                    <div>
                        <el-tag style="margin-left: 5px" size="medium" :key="s.id" v-for="s in customerConfig.selected" closable
                            :disable-transitions="false" @close="handleCloseCustomer(s)">
                            <span>{{ s.memberName }}</span>
                        </el-tag>
                    </div>
                    <div style="
                        color: #999;
                        font-size: 14px;
                        display: flex;
                        align-items: center;
                    ">
                        <i class="el-icon-info"></i>
                        选择了客服之后,此科普小节的完课 消息
                        只作用于此客服
                    </div>
                </el-form-item>
            
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="addForm.canOp" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 选择app客服角色 -->
        <el-dialog title="选择客服" :visible.sync="customerConfig.visible" width="1300px" append-to-body>
            <CusRoleList
                :selected="customerConfig.selected"
                @confirm="customerSelectedConfirmCallForBind"
                @selectionChange="customerSelectionChangeCallForBind"
            />
        </el-dialog>

    </div>
</template>

<script>
import {
    findList,
    // exportList,
    add,
    edit,
    getById,
    deleteByIds,
} from "@/api/app/course/courseFinishTemp";
import { courseList, videoList } from "@/api/app/course";
import { getPackageOptions,} from "@/api/app/pkg";
import ImageUpload from "@/views/qw/sop/ImageUpload.vue";
import CusRoleList from '@/views/app/user/CusRoleList.vue';
import {listRole} from '@/api/app/user/userList';

export default {
    name: "CourseFinishTemp",
    components: { ImageUpload, CusRoleList, },
    data() {
        return {
            //上传语音的遮罩层
            voiceLoading: false,
            uploadUrl: process.env.VUE_APP_BASE_API + "/app/common/uploadOSS2",
            uploadUrlByVoice: process.env.VUE_APP_BASE_API + "/app/common/uploadOSSByHOOKVoice",
            videoLoading: false,
            videoOptionsLoading: false,
            courseLoading: false,
            videoOptions: [],
            sysFsSopWatchStatus: [],
            // 状态字典
            statusOptions: [],
            courseList: [],
            videoList: [],
            pkgList: [],
            queryCourseList: [],
            queryVideoList: [],
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            formType: 1,
            // 总条数
            total: 0,
            // 完课模板表格数据
            courseFinishTempList: [],
            //插件版
            sysQwSopAiContentType: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                status: null,
                courseId: null,
                videoId: null
            },
            // 表单校验
            rules: {
                name: [
                    { required: true, message: '模板名称不能为空', trigger: 'submit' }
                ],
                status: [
                    { required: true, message: '状态不能为空', trigger: 'submit' }
                ],
                courseId: [
                    { required: true, message: '科普/课节/类型不能为空', trigger: 'submit' }
                ],
                videoId: [
                    { required: true, message: '科普/课节/类型不能为空', trigger: 'submit' }
                ],
                courseType: [
                    { required: true, message: '科普/课节/类型不能为空', trigger: 'submit' }
                ],
            },
            finishTempList: [],
            //用来记录上次选择部门的数组
            addForm: {
                visible: false,
                title: '',
                canOp: true,
                id: null,
                name: null,
                status: 1,
                courseId: null,
                videoId: null,
                courseType: 3,//指定是完课消息
                setting: [],
                loading: false,
            },
            //选择客服对话框
            customerConfig: {
                visible: false,
                selected: [],
            },
        };
    },
    async created() {
        this.getList();
        this.getDicts("app_normal_disabled_status").then((response) => {
            this.statusOptions = 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;
        });
        let courseList = await this.getCourseList(null, null);
        this.queryCourseList = courseList.list;
        let defaultPkg = await this.getPkgList(null, null);
        this.pkgList = defaultPkg.data;
    },
    methods: {
        //--------------------------------------------------------------列表 begin---------------------------------------------------------
        /**
         * 查询完课模板列表
         */
        getList() {
            this.loading = true;
            findList(this.queryParams).then((response) => {
                this.courseFinishTempList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /**
         * 搜索按钮操作
         */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /**
         * 重置按钮操作
         */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /**
         * 多选框选中数据
         * @param selection 
         */
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /**
         * 新增按钮操作
         */
        async handleAdd() {
            this.reset();
            this.addContent();
            this.addForm.title = "添加完课模板";
            this.addForm.loading = true;
            this.addForm.visible = true;
            let courseList = await this.getCourseList(null, null);
            this.courseList = courseList.list;
            this.addForm.loading = false;
        },
        /**
         * 修改按钮操作
         * @param row 
         */
        async handleUpdate(row, canOp) {
            this.reset();
            const id = row.id;
            this.addForm.title = canOp ? "修改完课模板" : "完课模板详情";
            this.addForm.canOp = canOp;
            this.addForm.loading = true;
            this.addForm.visible = true;
            let info = await getById(id);
            for (let key in this.addForm) {
                if (info.data.hasOwnProperty(key) && key !== 'setting') {
                    this.addForm[key] = (key === 'status' ? parseInt(info.data.status) : info.data[key]);
                }
            }
            this.addForm.setting = JSON.parse(info.data.setting);
            this.addForm.setting.forEach(async st => {
                if (st.contentType == 20) {
                    if (!st.packageId) {
                        this.$set(st, 'meta', {
                            pkgLoading: false,
                            pkgList: []
                        });
                    } else {
                        let pkgList = await this.getPkgList(null, st.packageId);
                        this.$set(st, 'meta', {
                            pkgLoading: false,
                            pkgList: pkgList.data,
                        });
                    }
                }
                
            })
            if (info.data.appCustomerIds) {
                let userInfo = await listRole({ids: info.data.appCustomerIds});
                this.customerConfig.selected = userInfo.rows;
            }
            if (this.addForm.courseId) {
                let courseList = await this.getCourseList(null, this.addForm.courseId);
                this.courseList = courseList.list;
                let videoList = await this.getVideoList(this.addForm.courseId, null);
                this.videoList = videoList.list;
            }
            this.addForm.loading = false;
        },
        /**
         * 删除按钮操作
         * @param row 
         */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm(
                '是否确认删除完课模板ID为"' + ids + '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(async () => {
                    await deleteByIds(ids);
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        //--------------------------------------------------------------新增/编辑 begin---------------------------------------------------------
        customerSelectedConfirmCallForBind() {
            this.customerConfig.visible = false;
        },
        /**
         * 选中的用户列表
         * @param list 
         */
        customerSelectionChangeCallForBind(config) {
            let selected = config.selected;
            //单行操作
            if (config.mode === 0) {
                let row = config.row;
                if (selected) {
                    if (!this.customerConfig.selected.some(s => s.id == row.id)) {
                        this.customerConfig.selected.push(row)
                    }
                } else {
                    this.customerConfig.selected = this.customerConfig.selected.filter(m => m.id != row.id);
                }
            }
            //操作当前页所有行
            else {
                let list = config.rows;
                if (selected) {
                    list.map(l => {
                        if (!this.customerConfig.selected.some(s => s.id == l.id)) {
                            this.customerConfig.selected.push(l)
                        }
                    });
                } else {
                    list.map(l => {
                        for (let i = 0; i < this.customerConfig.selected.length; i++) {
                            if (l.id == this.customerConfig.selected[i].id) {
                                this.customerConfig.selected.splice(i, 1);
                            }
                        }
                    })
                }
            }
        },
        /**
         * 提交按钮
         */
        submitForm() {
            this.$refs["addForm"].validate(async (valid) => {
                if (valid) {
                    if (this.checkData(this.addForm)) {
                        let data = JSON.parse(JSON.stringify(this.addForm));
                        data.setting.forEach(ele => {
                            delete ele.meta;
                        });
                        data['appCustomerIds'] = this.customerConfig.selected.map(s => s.id).join(',');
                        data['contentType'] = data.type;
                        data['setting'] = JSON.stringify(data.setting);
                        if (data.id != null) {
                            await edit(data);
                            this.msgSuccess("修改成功");
                            this.reset();
                            this.getList();
                        } else {
                            await add(data);
                            this.msgSuccess("新增成功");
                            this.reset();
                            this.getList();
                        }
                    }
                }
            });
        },
        /**
         * 校验数据
         * @param data 
         */
        checkData(data) {

            if (this.isEmpty(data.name)) {
                this.$message.error("模板名称不能为空")
                return false;
            }
            if (this.isEmpty(data.status)) {
                this.$message.error("状态不能为空")
                return false;
            }
            if (this.isEmpty(data.courseId)) {
                this.$message.error("请选择科普")
                return false;
            }
            if (this.isEmpty(data.videoId)) {
                this.$message.error("请选择课节")
                return false;
            }
            if (this.isEmpty(data.courseType)) {
                this.$message.error("消息类型不能为空")
                return false;
            }

            if (data.setting.length == 0) {
                this.$message.error("请添加规则！")
                return false;
            }

            for (let i = 0; i < data.setting.length; i++) {
                let setting = data.setting[i];
                if (setting.contentType == 11 && this.isEmpty(setting.value)) {
                    this.$message.error("内容不能为空")
                    return false;
                }
                if (setting.contentType == 12 && this.isEmpty(setting.value)) {
                    this.$message.error("语音文本不能为空")
                    return false;
                }
                if (setting.contentType == 2 && this.isEmpty(setting.imgUrl)) {
                    this.$message.error("图片不能为空")
                    return false;
                }
                if (9 == setting.contentType && this.isEmpty(setting.linkTitle)) {
                    this.$message.error("链接标题不能为空")
                    return false;
                }
                if (9 == setting.contentType && this.isEmpty(setting.linkDescribe)) {
                    this.$message.error("链接描述不能为空")
                    return false;
                }
                if (9 == setting.contentType && this.isEmpty(setting.linkImageUrl)) {
                    this.$message.error("链接图片不能为空")
                    return false;
                }
                if (20 == setting.contentType && this.isEmpty(setting.packageId)) {
                    this.$message.error("疗法不能为空")
                    return false;
                }
            }
    
            return true;
        },
        /**
         * 取消按钮
         */
        cancel() {
            this.reset();
        },
        /**
         * 表单重置
         */
        reset() {
            this.addForm = {
                visible: false,
                title: '',
                canOp: true,
                id: null,
                name: null,
                status: 1,
                courseId: null,
                videoId: null,
                courseType: 3,
                setting: [],
                loading: false,
            };
            this.customerConfig.selected = [];
            this.resetForm("addForm");
        },
        /**
         * 科普小节变化
         * @param mode 模式，0-查询列表，1-新增编辑页 
         */
        videoIdChange(mode) {
            if (mode == 1) {
                //选择了科普小节则 默认绑上
                let selectedVideo;
                // 查找选中的科普对应的 label
                if (this.addForm.videoId) {
                    selectedVideo = this.videoList.find(course => parseInt(course.dictValue) == this.addForm.videoId);
                }
                for (let i = 0; i < this.addForm.setting.length; i++) {
                    let contentItem = this.addForm.setting[i];
                    //科普消息-文本内容
                    if (contentItem == 11) {
                        this.$set(contentItem, 'isBindUrl', '2');
                    }
                    //如果是科普的才上
                    if (selectedVideo && this.addForm.videoId != null) {

                        if (contentItem.contentType == 9) {
                            this.$set(contentItem, 'linkDescribe', selectedVideo.dictLabel);
                        }
                    }
                }
            }
        },
        /**
         * 疗法下拉搜索
         * @param keyword 
         * @param content 
         */
        async handlePkgRemoteSearch(keyword, content) {
            content.meta.pkgLoading = true;
            // 模拟远程接口请求（替换为你的真实接口）
            let cl = await this.getPkgList(this.isEmpty(keyword) ? null : keyword, null);
            content.meta.pkgLoading = false;
            content.meta.pkgList = cl.data;
        },
        /**
         * 删除内容节点
         * @param index 
         */
        delContentNode(index){
            this.addForm.setting.splice(index, 1)
        },
        /**
         * 添加规则内容
         */
        addContent() {
            let content = {
                contentType: '11',//默认文本类型，其余类型暂时禁用
                value: '',
            };
            this.addForm.setting.push(content);
            this.handleContentTypeChange();
        },
        /**
         * 内容类别切换
         */
        handleContentTypeChange() {
            //获取选中的科普
            const selectedCourse = this.addForm.courseId != null
                ? this.courseList.find(course => parseInt(course.dictValue) == this.addForm.courseId)
                : null;
                //获取选中的视频
            const selectedVideo = this.addForm.videoId != null
                ? this.videoList.find(course => parseInt(course.dictValue) === this.addForm.videoId)
                : null;
            for (let i = 0; i < this.addForm.setting.length; i++) {
                let contentItem = this.addForm.setting[i];
                
                // 科普
                if (Number(contentItem.contentType) === 9) {
                    // 处理科普链接标题/封面
                    if (selectedCourse) {
                        this.$set(contentItem, 'linkTitle', selectedCourse.dictLabel);
                        this.$set(contentItem, 'linkImageUrl', selectedCourse.dictImgUrl);
                    }
                    // 处理视频链接描述
                    if (selectedVideo) {
                        this.$set(contentItem, 'linkDescribe', selectedVideo.dictLabel);
                    }
                }
                // 疗法
                else if (Number(contentItem.contentType) === 20) {
                    if (!contentItem.packageId) {
                        this.$set(contentItem, 'meta', {
                            pkgLoading: false,
                            pkgList: this.pkgList,
                        });
                    } else {
                        let pkgList = this.getPkgList(null, contentItem.packageId);
                        this.$set(contentItem, 'meta', {
                            pkgLoading: false,
                            pkgList: pkgList.data,
                        });
                    }
                }
            }
        },
        /**
         * 疗法变动处理
         * @param content 
         */
        async pkgChangeUpdate(content) {
            //将当前规则已选中的视频小节清空
            this.$set(content, 'packageName', null);
            this.$set(content, 'packageImgUrl', null);
            if (content.packageId) {
                // 查找选中疗法的信息
                const selectedPkg = content.meta.pkgList.find(pkg => parseInt(pkg.packageId) === content.packageId);
                this.$set(content, 'packageName', selectedPkg.packageName);
                this.$set(content, 'packageImgUrl', selectedPkg.imgUrl);
            }
        },
        /**
         * 打开选择客服的对话框
         */
        openSelectCustomerPage() {
            this.customerConfig.visible = true;
        },
        /**
         * 删除客服
         * @param list 
         */
        handleCloseCustomer(node) {
            const index = this.customerConfig.selected.findIndex(t => t == node);
            if (index !== -1) {
                this.customerConfig.selected.splice(index, 1);
            }
        },
        //--------------------------------------------------------------公共 begin---------------------------------------------------------
        /**
         * 获取科普信息
         */
        async getCourseList(keyword, selectedId) {
            let data = {
                keyword: keyword,
                selectedId: selectedId,
                pageNum: 1,
                pageSize: 50,
            };
            return await courseList(data);
        },
        /**
         * 科普变动处理
         * @param mode 模式，0-查询列表，1-新增编辑页
         */
        async courseChangeUpdate(mode) {
            if (mode == 1) {
                //将当前规则已选中的视频小节清空
                this.addForm.videoId = null;
                this.videoList = [];
                // 查找选中的科普的信息
                const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) == this.addForm.courseId);
                for (let i = 0; i < this.addForm.setting.length; i++) {
                    let contentItem = this.addForm.setting[i];
                    this.$set(contentItem, 'linkTitle', null);
                    this.$set(contentItem, 'linkDescribe', null);
                    this.$set(contentItem, 'linkImageUrl', null);

                    //如果是科普才上
                    if (selectedCourse && this.addForm.courseId) {
                        //响应式直接给链接的标题/封面上值
                        if (contentItem.contentType == 9) {
                            this.$set(contentItem, 'linkTitle', selectedCourse.dictLabel);
                            this.$set(contentItem, 'linkImageUrl', selectedCourse.dictImgUrl);
                        }
                    }
                }
                if (this.addForm.courseId) {
                    let vl = await this.getVideoList(this.addForm.courseId, null);
                    this.videoList = vl.list;
                } else {
                    let cl = await this.getCourseList(null, null);
                    this.courseList = cl.list;
                }
            } else {
                if (this.queryParams.courseId) {
                    let vl = await this.getVideoList(this.queryParams.courseId, null);
                    this.queryVideoList = vl.list;
                } else {
                    this.queryParams.videoId = null;
                    let cl = await this.getCourseList(null, null);
                    this.queryCourseList = cl.list;
                    let vl = await this.getVideoList(null, null);
                    this.queryVideoList = vl.list;
                }
            }
        },
        /**
         * 科普下拉远程搜索
         * @param {*} keyword 搜索关键字
         * @param {*} mode    模式，0-查询列表，1-新增编辑页
         */
        async handleCourseRemoteSearch(keyword, mode) {
            this.courseLoading = true;
            // 模拟远程接口请求（替换为你的真实接口）
            let cl = await this.getCourseList(this.isEmpty(keyword) ? null : keyword, null);
            this.courseLoading = false;
            if (1 == mode) {
                this.courseList = cl.list;
            } else {
                this.queryCourseList = cl.list;
            }
        },
        /**
         * 根据科普获取视频小节
         * @param courseId 
         * @param title 
         */
        async getVideoList(courseId, title) {
            return await videoList({
                courseId: courseId,
                title: title
            });
        },
        /**
         * 获取疗信息
         */
        async getPkgList(keyword, selectedId) {
            let data = {
                keyword: keyword,
                metaId: selectedId,
                limit: 50
            };
            return await getPackageOptions(data);
        },
        /**
         * 空校验
         * @param obj 
         */
        isEmpty(obj) {
            return obj === null || obj === undefined || obj.length === 0;
        },
    },
};
</script>
