<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
            <el-form-item label="客服" prop="customerRoles">
                <div @click="openCustomerPage(0)"
                    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 appCustomerSearchConfig.selected"
                            :key="list.id"
                            @close="handleCloseCustomer(list, 0)"
                            style="margin: 3px;"
                        >{{ list.memberName }}
                        </el-tag>
                    </div>
                </div>
            </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="sendStatus">
                <el-select v-model="queryParams.sendStatus" placeholder="请选择" clearable size="small">
                    <el-option label="是" :value="1"/>
                    <el-option label="否" :value="0"/>
                </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-button
                    type="primary"
                    plain
                    size="mini"
                    icon="el-icon-plus"
                    @click="handleAdd"
                    v-hasPermi="['app:welcome:add']"
                >
                    新增
                </el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="welcomeList" border>

            <el-table-column label="消息内容" align="left" prop="welcomeText" min-width="200">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.welcomeText" placement="top">
                        <div
                            style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; text-overflow: ellipsis;">
                            <span>{{ scope.row.welcomeText }}</span>
                        </div>
                    </el-tooltip>
                </template>
            </el-table-column>

            <el-table-column label="使用客服" align="center" prop="customerRoles" min-width="250">
                <template slot-scope="scope">
                    <div v-for="customerRole in (scope.row.customerRoles ? scope.row.customerRoles.split(',') : [])" :key="customerRole" style="display: inline;"
                        class="text-container">
                        <el-tag type="success" style="margin: 3px;">{{ customerRole }}</el-tag>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="发送状态" align="center" prop="sendStatus" min-width="120">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.sendStatus" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="0" active-text="开启" inactive-text="关闭" @change="toggleSendStatus($event, scope.row)">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center" prop="createTime" min-width="180" />
            <el-table-column label="更新时间" align="center" prop="updateTime" min-width="180" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180"
                fixed="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['app:welcome:edit']"
                    >
                        修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['app:welcome: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" v-loading="loading" width="1700px" append-to-body :close-on-click-modal="false">
            <div style="width: 1130px" class="app-container">
                <div>
                    <span style="font-size: 15px">基础信息</span>
                    <el-divider></el-divider>
                    <el-alert title="同一个客服，如果绑定了多个欢迎语，则以最新绑定的那一条为准，本次保存涉及的客服，那么当前的欢迎语就是最新绑定的！！" type="info" :closable="false" show-icon>
                    </el-alert>
                </div>
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="选择使用客服：" prop="customerRoles" style="margin-top: 2%">
                        <div>
                            <el-button size="medium" icon="el-icon-circle-plus-outline" plain
                                @click="openCustomerPage(1)">请选择使用客服</el-button>
                        </div>
                        <div>
                            <el-tag style="margin-left: 5px" size="medium" :key="s.id" v-for="s in appCustomerBindConfig.selected" closable
                                :disable-transitions="false" @close="handleCloseCustomer(s, 1)">
                                <span>{{ s.memberName }}</span>
                            </el-tag>
                        </div>
                    </el-form-item>
                    <el-form-item label="发送状态" prop="sendStatus">
                        <el-switch v-model="form.sendStatus" active-color="#13ce66" inactive-color="#ff4949"
                            :active-value="1" :inactive-value="0" active-text="开启" inactive-text="关闭">
                        </el-switch>
                    </el-form-item>
                    <div>
                        <span style="font-size: 15px">欢迎语</span>
                        <el-divider></el-divider>
                    </div>
                    <el-form-item label="默认欢迎语：" prop="welcomeText">
                        <el-input v-model="form.welcomeText" type="textarea" :rows="12" maxlength="1300" show-word-limit
                            placeholder="请输入消息内容" />
                        <!-- 附件和链接列表 -->
                        <el-row>
                            <el-col>
                                <div v-for="(item, index) in form.attachments" :key="index"
                                    style="background-color: #f5f7fa;padding: 5px;border: 1px solid #d9d9d9;">
                                    <div slot="header"
                                        style="display: flex;justify-content: space-between;align-items: center;">
                                        <div style="flex: 1;">
                                            <span v-if="item.contentType == '2'">【图片】: {{ item.image.imgUrl }}</span>
                                            <span v-else-if="item.contentType == '9'">【科普】: {{ item.course.courseTitle }}</span>
                                            <span v-else-if="item.contentType == '20'">【疗法】: {{ item.pkg.packageName }}</span>
                                            <span v-else-if="item.contentType == '21'">【直播】: {{ item.live.liveTitle }}</span>
                                        </div>
                                        <div style="display: flex;gap: 10px;">
                                            <el-button size="mini" type="text" icon="el-icon-edit" style="float: left;"
                                                @click="editFileItem(item, index)">修改</el-button>
                                            <el-button size="mini" type="text" icon="el-icon-delete"
                                                style="float: right;"
                                                @click="removeFileItem(index)">删除</el-button>
                                        </div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>

                        <el-dropdown @command="(command) => handleCommand(command)" trigger="click"
                            placement="top-start">
                            <el-dropdown-menu slot="dropdown" style="width: 120px;">
                                <!-- 和模板那边的消息类型一致，文本在上面输入框输入，故此不显示在此处 -->
                                <el-dropdown-item
                                    v-for="ct in contentTypeOptions"
                                    :key="ct.dictValue"
                                    :command="ct.dictValue"
                                    v-show="ct.dictValue != 11"
                                >
                                    <i class="el-icon-link" style="margin-right: 10px;"></i>{{ ct.dictLabel }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                            <span class="el-dropdown-link">
                                <el-link icon="el-icon-paperclip" type="text" style="color: rgb(24, 144, 255)">
                                    添加附件(最多9个)
                                </el-link>
                            </span>
                        </el-dropdown>
                    </el-form-item>
                </el-form>
            </div>

            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="submitForm">确定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 列表搜索条件：选择app客服角色 -->
        <el-dialog title="选择客服" :visible.sync="appCustomerSearchConfig.visible" width="1000px" append-to-body :close-on-click-modal="false">
            <CusRoleList
                ref="customerSearchRef"
                @confirm="customerSelectedConfirmCallForSearch"
                @selectionChange="customerSelectionChangeCallForSearch"
                :selected="appCustomerSearchConfig.selected"
            />
        </el-dialog>

        <!-- 新增编辑：选择app客服角色 -->
        <el-dialog title="选择客服" :visible.sync="appCustomerBindConfig.visible" width="1000px" append-to-body :close-on-click-modal="false">
            <CusRoleList
                ref="customerBindRef"
                @confirm="customerSelectedConfirmCallForBind"
                @selectionChange="customerSelectionChangeCallForBind"
                :selected="appCustomerBindConfig.selected"
            />
        </el-dialog>

        <!-- 新增/编辑页面内，欢迎语类型 -->
        <el-dialog :title="welcomeItem.title" :visible.sync="welcomeItem.visible" style="width: 1300px;height: 100%; margin-top: 10vh;"
            append-to-body :close-on-click-modal="false">
            <!-- 科普 -->
            <el-form  v-if="welcomeItem.contentType == '9'" ref="courseForm" :model="courseForm" :rules="courseFormRule" label-width="110px">
                <div>
                    <el-form-item label="选择科普" prop="videoId">
                        <el-select
                            v-model="courseForm.courseId"
                            placeholder="默认50条，可输入关键字检索"
                            style="margin-right: 10px;"
                            size="mini"
                            filterable
                            :loading="welcomeItem.courseLoading"
                            @change="courseChange(courseForm)"
                            remote
                            :remote-method="(keyword) => handleCourseRemoteSearch(keyword, courseForm)"
                        >
                            <el-option
                                v-for="dict in courseList"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="parseInt(dict.dictValue)"
                            />
                        </el-select>
                        <el-select
                            v-model="courseForm.videoId"
                            size="mini"
                            placeholder="请选择小节"
                            style="margin-right: 10px;"
                            @change="videoIdChange(courseForm, welcomeItem.contentType)"
                        >
                            <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-form-item>
                    <el-form-item label="科普标题：" prop="courseTitle">
                        <el-input
                            v-model="courseForm.courseTitle"
                            :rows="2"
                            maxlength="64"
                            placeholder="请输入科普标题，最长为64字节"
                            @input="checkByteLength(courseForm, 'courseTitle')"
                        />
                    </el-form-item>
                    <div v-if="courseForm.videoId != null ">
                        <el-form-item label="课节链接:" label-width="100px">
                            <el-tag type="warning">选择的科普小节 即为卡片链接地址</el-tag>
                        </el-form-item>
                    </div>
                    <div v-if="courseForm.videoId != null">
                        <el-form-item label="课节过期时间" style="margin-top: 1%" required label-width="110px">
                            <el-row>
                                <el-input-number v-model="courseForm.expireDays" :min="1" :max="9999"></el-input-number>
                                （天）
                            </el-row>
                            <el-row>
                                <span class="tip">默认为30天</span>
                            </el-row>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <!-- 图片 -->
            <el-form v-else-if="welcomeItem.contentType == '2'" ref="imageForm" :model="imageForm" :rules="imageFormRule" label-width="110px">
                <div>
                    <el-form-item label="图片：" prop="imgUrl">
                        <ImageUpload
                            v-model="imageForm.imgUrl"
                            type="image"
                            :num="10"
                            :width="150"
                            :height="150"
                        />
                    </el-form-item>
                </div>
            </el-form>
            <!--语音： welcomeItem.contentType == '12' -->
            <!--视频： welcomeItem.contentType == '6' -->
            <!-- 疗法： welcomeItem.contentType == '20' -->
            <el-form v-else-if="welcomeItem.contentType == '20'" ref="pkgForm" :model="pkgForm" :rules="pkgFormRule" label-width="110px">
                <div>
                    <el-form-item
                        label="选择疗法:"
                        label-width="100px"
                        required
                    >
                        <el-select
                            v-model="pkgForm.packageId"
                            placeholder="默认50条，可输入关键字检索"
                            style=" margin-right: 10px; width: 230px;"
                            size="mini"
                            filterable
                            clearable
                            :loading="pkgForm.pkgLoading"
                            remote
                            :remote-method="(keyword) => handlePkgRemoteSearch(keyword)"
                            @change="pkgChangeUpdate"
                        >
                        <el-option
                            v-for="dict in 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="pkgForm.packageName"
                            style="width: 90%;margin-top: 1%;"
                        />
                    </el-form-item>
                    <el-form-item
                        label="疗法封面:"
                        label-width="100px"
                    >
                        <ImageUpload
                            :disabled="true"
                            v-model="pkgForm.packageImgUrl"
                            type="image"
                            :num="1"
                            :file-size="1"
                            :width="150"
                            :height="150"
                            style="margin-top: 1%;"
                        />
                    </el-form-item>
                </div>
            </el-form>
            <!-- 直播 -->
<!--            <el-form v-else-if="welcomeItem.contentType == '21'" ref="liveForm" :model="liveForm" :rules="liveFormRule" label-width="110px">-->
<!--                <div>-->
<!--                    <el-card class="box-card">-->
<!--                        <el-form-item label="直播间"-->
<!--                            required-->
<!--                            style="margin-bottom: 5px;"-->
<!--                        >-->
<!--                            <el-select-->
<!--                                v-model="liveForm.liveId"-->
<!--                                placeholder="请选择直播间"-->
<!--                                size="mini"-->
<!--                                filterable-->
<!--                                @change="liveChange()"-->
<!--                            >-->
<!--                            <el-option-->
<!--                                v-for="dict in liveList"-->
<!--                                :key="dict.liveId"-->
<!--                                :label="dict.liveName"-->
<!--                                :value="parseInt(dict.liveId)"-->
<!--                            />-->
<!--                            </el-select>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="标题"-->
<!--                            prop="liveTitle"-->
<!--                            style="margin-bottom: 5px;"-->
<!--                        >-->
<!--                            <el-input-->
<!--                                v-model="liveForm.liveTitle"-->
<!--                                placeholder="请输入消息标题，最长为64字节"-->
<!--                                :rows="2"-->
<!--                                maxlength="64"-->
<!--                                type="textarea"-->
<!--                                disabled-->
<!--                                @input="checkByteLength(liveForm, 'liveTitle')"-->
<!--                            />-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="封面"-->
<!--                            prop="liveImgUrl"-->
<!--                        >-->
<!--                            <ImageUpload-->
<!--                                v-model="liveForm.liveImgUrl"-->
<!--                                type="image"-->
<!--                                :num="10"-->
<!--                                :width="150"-->
<!--                                :height="150"-->
<!--                                disabled-->
<!--                            />-->
<!--                        </el-form-item>-->
<!--                    </el-card>-->
<!--                </div>-->
<!--            </el-form>-->
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="confirmUpload">确定</el-button>
                <el-button @click="cancelUpload">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { list, getById, deleteByIds, save, setSendStatus } from "@/api/app/welcome";
import {listRole} from '@/api/app/user/userList';
import ImageUpload from "@/views/qw/sop/ImageUpload";
import CusRoleList from '@/views/app/user/CusRoleList.vue';
import {courseList, videoList} from "@/api/app/course";
import { getPackageOptions,} from "@/api/app/pkg";
// import { getLiveOptions,} from "@/api/app/live";

export default {
    name: "AppWelcome",
    components: { ImageUpload, CusRoleList },
    data() {
        return {
            loading: true,
            exportLoading: false,
            ids: [],
            appCustomerSearchConfig: {
                type: null,
                visible: false,
                enableFilter: false,
                selected: [],
            },
            appCustomerBindConfig: {
                type: null,
                visible: false,
                enableFilter: false,
                selected: [],
            },
            addForm: {
                visible: false,
                title: "",
            },
            contentTypeOptions: [],
            courseForm: {
                courseId: null,//科普-科普id
                videoId: null,//科普-科普小结id
                expireDays: 30,//科普-科普小节过期时间（天）
                courseTitle: null,//科普-科普小结标题
                courseLoading: false,
            },
            courseFormRule: {
                courseId: [
                    { required: true, message: "请选择科普信息", trigger: "blur" }
                ],
                videoId: [
                    { required: true, message: "请选择科普信息", trigger: "blur" }
                ],
                courseTitle: [
                    { required: true, message: "请输入科普标题", trigger: "blur" }
                ]
            },
            imageForm: {
                imgUrl: null,//图片url
            },
            pkgList: [],
            pkgForm: {
                packageId: null,
                packageName: null,
                packageImgUrl: null,
                loading: false,
            },
            pkgFormRule: {},
            imageFormRule: {},
            liveList: [],
            liveForm: {
                liveId: null,
                liveTitle: null,
                liveImgUrl: null,
            },
            liveFormRule: {},
            courseList: [],
            videoList: [],
            welcomeItem: {
                visible: false,//控制添加附件对话框是否显示
                title: null,//对话框标题
                contentType: null,//附件类型
                index: -1,//新增，还是编辑，-1即为新增，>-1即为编辑
            },
            showSearch: true,
            total: 0,
            welcomeList: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                customerRoles: [],
                createTime: null,
                sendStatus: null,
            },
            form: {},
            rules: {
                welcomeText: [
                    { required: true, message: "消息内容不能为空", trigger: "submit" }
                ],
            },
        };
    },
    async created() {
        let defaultCourse = await this.getCourseList(null, null);
        this.courseList = defaultCourse.list;
        let contentTypeOptions = await this.getDicts("app_sop_plugin_settingType");
        this.contentTypeOptions = contentTypeOptions.data;
        this.getList();
        let defaultPkg = await this.getPkgList(null, null);
        this.pkgList = defaultPkg.data;
        // let defaultLive = await this.getLiveList();
        // this.liveList = defaultLive.data;
    },
    methods: {
        /**
         * 获取科普信息
         */
        async getCourseList(keyword, selectedId) {
            let data = {
                keyword: keyword,
                selectedId: selectedId,
                pageNum: 1,
                pageSize: 50,
            };
            return await courseList(data);
        },
        /**
         * 获取疗信息
         */
        async getPkgList(keyword, selectedId) {
            let data = {
                keyword: keyword,
                metaId: selectedId,
                limit: 50
            };
            return await getPackageOptions(data);
        },
        /**
         * 获取直播间信息
         */
        // async getLiveList() {
        //     return await getLiveOptions();
        // },
        /**
         * 疗法下拉搜索
         * @param keyword
         */
        async handlePkgRemoteSearch(keyword) {
            this.pkgForm.pkgLoading = true;
            // 模拟远程接口请求（替换为你的真实接口）
            let cl = await this.getPkgList(keyword ? null : keyword, null);
            this.pkgForm.pkgLoading = false;
            this.pkgList = cl.data;
        },
        /**
         * 疗法变动处理
         */
        async pkgChangeUpdate() {
            this.pkgForm.packageName = null;
            this.pkgForm.packageImgUrl = null;
            if (this.pkgForm.packageId) {
                // 查找选中疗法的信息
                const selectedPkg = this.pkgList.find(pkg => parseInt(pkg.packageId) === this.pkgForm.packageId);
                this.pkgForm.packageName = selectedPkg.packageName;
                this.pkgForm.packageImgUrl = selectedPkg.imgUrl;
            }
        },
        // /**
        //  * 直播间切换
        //  */
        // liveChange() {
        //     this.liveForm.liveTitle = null;
        //     this.liveForm.liveImgUrl = null;
        //     const selectedLive = this.liveList.find(live => live.liveId === this.liveForm.liveId);
        //     if (selectedLive) {
        //         this.liveForm.liveTitle = selectedLive.liveName; // 自动填充标题
        //         this.liveForm.liveImgUrl = selectedLive.liveImgUrl; // 自动填充封面
        //     }
        // },
        /**
         * 搜索条件：客服选中确认回调
         */
        customerSelectedConfirmCallForSearch() {
            this.appCustomerSearchConfig.visible = false;
        },
        /**
         * 新增/编辑：客服选中确认回调
         */
        customerSelectedConfirmCallForBind() {
            this.appCustomerBindConfig.visible = false;
        },
        /**
         * 搜索条件：客服选中变更回调
         * @param config
         */
        customerSelectionChangeCallForSearch(config) {
            let selected = config.selected;
            //单行操作
            if (config.mode === 0) {
                let row = config.row;
                if (selected) {
                    if (!this.appCustomerSearchConfig.selected.some(s => s.id == row.id)) {
                        this.appCustomerSearchConfig.selected.push(row);
                    }
                } else {
                    this.appCustomerSearchConfig.selected = this.appCustomerSearchConfig.selected.filter(m => m.id != row.id);
                }
            }
            //操作当前页所有行
            else {
                let list = config.rows;
                if (selected) {
                    list.map(l => {
                        if (!this.appCustomerSearchConfig.selected.some(s => s.id == l.id)) {
                            this.appCustomerSearchConfig.selected.push(l);
                        }
                    });
                } else {
                    list.map(l => {
                        for (let i = 0; i < this.appCustomerSearchConfig.selected.length; i++) {
                            if (l.id == this.appCustomerSearchConfig.selected[i].id) {
                                this.appCustomerSearchConfig.selected.splice(i, 1);
                            }
                        }
                    })
                }
            }
        },
        /**
         * 新增/编辑：客服选中变更回调
         * @param config
         */
        customerSelectionChangeCallForBind(config) {
            let selected = config.selected;
            //单行操作
            if (config.mode === 0) {
                let row = config.row;
                if (selected) {
                    if (!this.appCustomerBindConfig.selected.some(s => s.id == row.id)) {
                        this.appCustomerBindConfig.selected.push(row)
                    }
                } else {
                    this.appCustomerBindConfig.selected = this.appCustomerBindConfig.selected.filter(m => m.id != row.id);
                }
            }
            //操作当前页所有行
            else {
                let list = config.rows;
                if (selected) {
                    list.map(l => {
                        if (!this.appCustomerBindConfig.selected.some(s => s.id == l.id)) {
                            this.appCustomerBindConfig.selected.push(l)
                        }
                    });
                } else {
                    list.map(l => {
                        for (let i = 0; i < this.appCustomerBindConfig.selected.length; i++) {
                            if (l.id == this.appCustomerBindConfig.selected[i].id) {
                                this.appCustomerBindConfig.selected.splice(i, 1);
                            }
                        }
                    })
                }
            }
        },
        /**
         * 打开选择客服页面
         * @param mode 0-搜索，1-新增/编辑
         */
        openCustomerPage(mode) {
            if (mode == 0) {
                this.appCustomerSearchConfig.visible = true;
            } else {
                this.appCustomerBindConfig.visible = true;
            }
        },
        /**
         * 删除客服
         * @param cus
         * @param mode
         */
        handleCloseCustomer(cus, mode) {
            if (mode == 0) {
                this.appCustomerSearchConfig.selected = this.appCustomerSearchConfig.selected.filter(item => item.id != cus.id);
            } else {
                this.appCustomerBindConfig.selected = this.appCustomerBindConfig.selected.filter(item => item.id != cus.id);
            }
        },
        getList() {
            this.loading = true;
            list(this.queryParams).then(response => {
                this.welcomeList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /**
         * 检查长度
         * @param formInfo
         * @param key
         */
        checkByteLength(formInfo, key) {
            const text = formInfo[key];
            const byteLength = this.getByteLength(text);
            if (byteLength > 64) {
                this.$set(formInfo, key, this.truncateTextByByteLength(text, 64));
            }
        },
        /**
         * 获取字节长度
         * @param text
         */
        getByteLength(text) {
            return new Blob([text]).size;
        },
        /**
         * 截断字节长度
         * @param text
         * @param maxByteLength
         */
        truncateTextByByteLength(text, maxByteLength) {
            let byteLength = 0;
            let result = "";
            for (let i = 0; i < text.length; i++) {
                const char = text[i];
                const charByteLength = this.getByteLength(char);
                if (byteLength + charByteLength <= maxByteLength) {
                    result += char;
                    byteLength += charByteLength;
                } else {
                    break;
                }
            }
            return result;
        },
        /**
         * 点击具体的欢迎语选项进行新增附件
         * @param command
         */
        handleCommand(command) {
            if (this.form.attachments.length >= 9) {
                return this.$message.error('附件数量已达上限，无法添加更多附件');
            }
            this.welcomeItem = {
                visible: true,
                title: '添加' + this.getTitleByCommand(command),
                contentType: command,
                index: -1,
            };
        },
        /**
         * 根据消息类型编码获取消息类型名称
         * @param command
         */
        getTitleByCommand(command) {
            let option = this.contentTypeOptions.find(cto => cto.dictValue == command);
            return option.dictLabel;
        },
        /**
         *
         */
        async handleCourseRemoteSearch(keyword, courseForm) {
            this.welcomeItem.courseLoading = true;
            // 模拟远程接口请求（替换为你的真实接口）
            let cl = await this.getCourseList((keyword ? keyword : null), courseForm.courseId);
            this.courseList = cl.list;
            this.welcomeItem.courseLoading = false;
        },
        /**
         * 科普变化
         * @param form
         */
        courseChange(form) {
            this.$set(form, 'videoId', null);
            this.$set(form, 'courseTitle', null);
            this.videoList = [];
            if (form.courseId != null) {
                videoList({courseId: form.courseId}).then(response => {
                    this.videoList = response.list;
                });
            }
        },
        /**
         * 科普小节改变
         * @param form
         * @param type
         */
        videoIdChange(form, type) {
            if (form.videoId != null) {
                let selectedVideo = this.videoList.find(course => course.dictValue == form.videoId);
                //科普
                if (selectedVideo && type == '9') {
                    this.$set(form, 'courseTitle', this.truncateTextByByteLength(selectedVideo.dictLabel, 64));
                    this.$set(form, 'expireDays', 30);
                }
            }
        },
        /**
         * 编辑附件信息
         * @param item
         */
        async editFileItem(item, index) {
            this.welcomeItem = {
                visible: true,
                title: '编辑' + this.getTitleByCommand(item.contentType),
                contentType: item.contentType,
                index,
            };
            //图片
             if (item.contentType == '2') {
                this.imageForm = JSON.parse(JSON.stringify(item.image));//深拷贝
            }
            // 科普
            else if (item.contentType == '9') {
                this.courseForm = JSON.parse(JSON.stringify(item.course));//深拷贝
                if (item.course.courseId) {
                    let cl = await this.getCourseList(null, this.courseForm.courseId);
                    this.courseList = cl.list;
                    videoList({courseId: item.course.courseId}).then(response => {
                        this.videoList = response.list;
                    });
                }
            }
        },
        /**
         * 移除欢迎语附件
         * @param index
         */
        removeFileItem(index) {
            this.form.attachments.splice(index, 1);
        },
        /**
         * 确认添加附件
         */
        confirmUpload() {
            const { contentType, index } = this.welcomeItem;
            //科普
            if (contentType == '9') {
                this.$refs["courseForm"].validate(valid => {
                    if (valid) {
                        this.addFile(index, {
                            contentType: 9,
                            course: {...this.courseForm},
                        });
                    }
                });
            }
            //图片
            else if (contentType == '2') {
                this.$refs["imageForm"].validate(valid => {
                    if (valid) {
                        this.addFile(index, {
                            contentType: 2,
                            image: {...this.imageForm},
                        });
                    }
                });
            }
            //疗法
            else if (contentType == '20') {
                this.$refs["pkgForm"].validate(valid => {
                    if (valid) {
                        this.addFile(index, {
                            contentType: 20,
                            pkg: {...this.pkgForm},
                        });
                    }
                });
            }
            //直播
            else if (contentType == '21') {
                this.$refs["liveForm"].validate(valid => {
                    if (valid) {
                        this.addFile(index, {
                            contentType: 21,
                            live: {...this.liveForm},
                        });
                    }
                });
            }
        },
        /**
         * 添加附件
         * @param index
         * @param attachment
         */
        addFile(index, attachment) {
            //编辑模式：执行替换
            if (index > -1) {
                this.form.attachments.splice(index, 1, attachment);
            }
            //新增模式：直接追加
            else {
                this.form.attachments.push(attachment);
            }
            this.resetFileForm();
            this.welcomeItem.visible = false;
        },
        /**
         * 取消添加附件
         */
        cancelUpload() {
            this.resetFileForm();
            this.welcomeItem.visible = false;
        },
        /**
         * 取消新增欢迎语
         */
        cancel() {
            this.addForm.visible = false;
            this.reset();
        },
        /**
         * 重置附件表单
         */
        resetFileForm() {
            //清空科普表单信息
            for (let key in this.courseForm) {
                this.courseForm[key] = null;
            }
            //清空图片表单信息
            for (let key in this.imageForm) {
                this.imageForm[key] = null;
            }
            this.welcomeItem = {
                visible: false,
                title: null,
                contentType: null,
                index: -1,
            };
            this.videoList = [];
        },
        /**
         * 切换发送状态
         * @param val
         */
        async toggleSendStatus(val, row) {

            let activeName = val == 0 ? '关闭' : '开启';
            this.$confirm(`是否确认${activeName}发送？`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async res => {
                await setSendStatus({id: row.id, sendStatus: val});
                this.msgSuccess(`${activeName}成功！`);
                this.getList();
            }).catch(() => {
                this.getList();
            });
        },
        /**
         * 重置新增欢迎语表单
         */
        reset() {
            this.form = {
                id: null,
                attachments: [],
                sendStatus: 1,
                welcomeText: null,
            };
            this.appCustomerBindConfig.selected = [];
            this.resetForm("form");
            this.resetFileForm();
        },
        /**
         * 执行查询
         */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.queryParams.customerRoles = this.appCustomerSearchConfig.selected.map(s => s.id) || null;
            this.getList();
        },
        /**
         * 重置查询
         */
        resetQuery() {
            this.resetForm("queryForm");
            this.appCustomerSearchConfig.selected = [];
            this.handleQuery();
        },
        /**
         * 新增欢迎语
         */
        handleAdd() {
            this.reset();
            this.addForm.visible = true;
            this.addForm.title = "新建欢迎语";
        },
        /**
         * 编辑欢迎语
         * @param row
         */
        async handleUpdate(row) {
            this.reset();
            const id = row.id;
            let info = await getById(id);
            let data = info.data;
            if (data.attachments) {
                data.attachments = JSON.parse(data.attachments);
            }
            if (data.customerRoles) {
                let roleList = await listRole({ids: data.customerRoles.split(',')});
                this.appCustomerBindConfig.selected = roleList.rows;
            }
            this.form = data;
            this.addForm.visible = true;
            this.addForm.title = "修改欢迎语";
        },
        /**
         * 提交欢迎语表单
         */
        submitForm() {
            this.loading = true;
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.commitForm();
                }
            });
        },
        /**
         * 提交表单
         */
        async commitForm() {
            const requestData = { ...this.form };
            requestData['customerRoles'] = this.appCustomerBindConfig.selected.map(s => s.id);
            requestData.attachments = JSON.stringify(this.form.attachments);
            await save(requestData);
            this.reset();
            this.addForm.visible = false;
            this.getList();
        },
        /**
         * 删除
         * @param row
         */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除欢迎语：编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return deleteByIds(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => { });
        },
    }
};
</script>

<style>
.text-container {
    max-height: 7.5em;
    overflow-y: auto;
    line-height: 1.5em;
}
</style>
