<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" @submit.native.prevent>
                <el-form-item label="课程分类">
                    <el-select v-model="categoryValue" placeholder="请选择" clearable @change="searchList" size="small">
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程名称">
                    <el-input v-model="keyword" placeholder="请输入" clearable @change="searchList" size="small"></el-input>
                </el-form-item>
                <el-form-item label="讲师">
                    <el-input v-model="instructor" placeholder="请输入" clearable @change="searchList" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addCourse" size="small" >添加课程</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="batchManage" size="small">分类管理</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
            <el-table :data="list" highlight-current-row v-loading="listLoading" :height="tableHeight" style="width: 100%;">
            <el-table-column type="index" width="50" align="center" label="#"></el-table-column>
            <el-table-column label="封面" width="120" align="center">
                <template slot-scope="scope">
                    <img v-if="scope.row.coverImage" :src="scope.row.coverImage" class="course-cover-image" />
                    <span v-else>无封面</span>
                </template>
            </el-table-column>
            <el-table-column prop="courseTypeName" label="课程分类" min-width="120" align="center"></el-table-column>
            <el-table-column prop="courseName" label="课程名称" min-width="180" align="center"></el-table-column>
            <el-table-column prop="courseInstructor" label="讲师" min-width="120" align="center"></el-table-column>
            <el-table-column prop="coursePrice" label="价格" min-width="100" align="center">
                <template slot-scope="scope">
                    <span>¥{{ scope.row.coursePrice }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="courseDuration" label="课程时间" min-width="120" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.courseDuration ? scope.row.courseDuration + '分钟' : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="视频" min-width="100" align="center">
                <template slot-scope="scope">
                    <span v-if="!scope.row.courseUrl">无</span>
                    <el-button v-else type="text" @click="playVideo(scope.row)">
                        <i class="el-icon-video-play" style="font-size: 20px; color: #409EFF;"></i>
                    </el-button>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" width="250" class-name="btns" header-align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button size="small" type="danger" @click="deleteItem(scope.row)">删除</el-button>
                    <el-button size="small" type="primary" @click="editItem(scope.row)">编辑</el-button>
                    <el-button size="small" :type="scope.row.courseStatus === 1 ? 'warning' : 'success'" @click="uploadItem(scope.row)">{{scope.row.courseStatus === 1 ? '下架' : '上架'}}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                style="float:right;"
            ></el-pagination>
        </el-col>
        <!-- 新增/编辑课程 -->
        <el-dialog :visible.sync="addDialogVisible" :title="newCourse.id ? '编辑课程' : '添加课程'" width="900px" :close-on-click-modal="false" @close="stopCourseVideo">
            <el-form :model="newCourse" ref="newCourseForm" label-width="100px" :rules="courseRules">
                <el-form-item label="课程分类" prop="categoryValue">
                    <el-select v-model="newCourse.categoryValue" placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程名称" prop="courseName">
                    <el-input v-model="newCourse.courseName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="课程介绍" prop="courseDesc">
                    <el-input
                        v-model="newCourse.courseDesc"
                        type="textarea"
                        :rows="5"
                        placeholder="请输入课程介绍"
                    />
                </el-form-item>
                <el-form-item label="讲师" prop="instructor">
                    <el-input v-model="newCourse.instructor" placeholder="请输入讲师姓名"></el-input>
                </el-form-item>
                <el-form-item label="讲师介绍" prop="instructorDesc">
                    <el-input
                        v-model="newCourse.instructorDesc"
                        type="textarea"
                        :rows="5"
                        placeholder="请输入讲师介绍"
                    />
                </el-form-item>
                <el-form-item label="课程价格" prop="price">
                    <el-input v-model="newCourse.price" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="课程时间" prop="duration">
                    <el-input v-model="newCourse.duration" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="课程封面">
                    <el-upload
                        class="cover-uploader"
                        action="#"
                        :show-file-list="false"
                        :on-change="handleCoverImageChange"
                        :auto-upload="false"
                        :before-upload="beforeImageUpload">
                        <img v-if="newCourse.coverImageUrl" :src="newCourse.coverImageUrl" class="cover-image" />
                        <i v-else class="el-icon-plus cover-uploader-icon"></i>
                    </el-upload>
                    <div class="upload-tip">请上传课程封面图片，建议尺寸 16:9</div>
                </el-form-item>
                <el-form-item label="讲师照片" prop="instructorImg">
                    <el-upload
                        class="instructor-uploader"
                        action="#"
                        :show-file-list="false"
                        :on-change="handleInstructorImageChange"
                        :auto-upload="false"
                        :before-upload="beforeImageUpload">
                        <img v-if="newCourse.instructorImageUrl" :src="newCourse.instructorImageUrl" class="instructor-image" />
                        <i v-else class="el-icon-plus instructor-uploader-icon"></i>
                    </el-upload>
                    <div class="upload-tip">请上传讲师照片，建议尺寸 1:1</div>
                </el-form-item>
                <el-form-item label="课程视频">
                    <el-upload
                        action="#"
                        :auto-upload="false"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :file-list="newCourse.videoFiles"
                        :on-change="handleVideoChange"
                        :before-upload="beforeVideoUpload"
                        accept="video/mp4,video/avi,video/x-msvideo">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传单个mp4/avi文件</div>
                    </el-upload>
                    <div v-if="newCourse.courseUrl" class="video-preview">
                        <div class="video-header">
                            <span class="video-title">视频预览</span>
                            <el-button 
                                type="text" 
                                class="delete-video-btn" 
                                @click="deleteVideo">
                                <i class="el-icon-delete"></i> 删除视频
                            </el-button>
                        </div>
                        <video 
                            controls
                            width="300"
                            ref="courseVideoPlayer"
                            :src="newCourse.courseUrl"
                            style="margin-top: 10px; max-width: 100%">
                            您的浏览器不支持视频播放
                        </video>
                        <div class="video-name" v-if="newCourse.videoFiles && newCourse.videoFiles.length > 0">
                            {{ newCourse.videoFiles[0].name }}
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitNewCourse('newCourseForm')">{{newCourse.id ? '保存' : '添加'}}</el-button>
            </span>
        </el-dialog>
        <!-- 分类管理 -->
        <el-dialog :visible.sync="categoryManageVisible" title="分类管理" width="600px">
            <el-table :data="categoryList" style="width: 100%" max-height="400">
                <el-table-column prop="label" label="分类名称" width="180"></el-table-column>
                <el-table-column label="封面" width="180">
                    <template slot-scope="scope">
                        <img v-if="scope.row.coverImage" :src="scope.row.coverImage" class="category-cover-image" />
                        <span v-else>无封面</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="setCategoryCover(scope.$index, scope.row)">设置封面</el-button>
                        <el-button size="mini" type="danger" @click="deleteCategory(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px;">
                <el-form :inline="true" :model="newCategory" class="demo-form-inline">
                    <el-form-item label="分类名称">
                        <el-input v-model="newCategory.label" placeholder="请输入分类名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addCategory">添加</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-dialog">
                <el-button @click="categoryManageVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
        
        <!-- 设置分类封面 -->
        <el-dialog :visible.sync="coverDialogVisible" title="设置分类封面" width="500px">
            <div class="cover-upload-container">
                <el-upload
                    class="cover-uploader"
                    action="#"
                    :show-file-list="false"
                    :on-change="handleCoverChange"
                    :auto-upload="false"
                    :before-upload="beforeCoverUpload">
                    <img v-if="coverImageUrl" :src="coverImageUrl" class="cover-image" />
                    <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
                <div class="cover-tip">请上传分类封面图片，建议尺寸 16:9</div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="coverDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveCategoryCover">确 定</el-button>
            </span>
        </el-dialog>
        
        <!-- 视频播放对话框 -->
        <el-dialog :visible.sync="videoDialogVisible" title="视频播放" width="800px" center @close="stopVideo">
            <div class="video-player-container">
                <video 
                    v-if="currentVideoUrl"
                    controls
                    autoplay
                    ref="videoPlayer"
                    class="video-player"
                    :src="currentVideoUrl">
                    您的浏览器不支持视频播放
                </video>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeVideoDialog">关 闭</el-button>
            </span>
        </el-dialog>
        
        <!-- 新增飞书企业 -->
        <el-dialog v-if="addFeishuDig" :visible.sync="addFeishuDig" title="新增飞书客户">
            <el-form :model="feishuInfo" :rules="feishuInfoRules" ref="feishuInfo" label-width="100px" class="demo-ruleForm">
                <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="feishuInfo.companyName"></el-input>
                </el-form-item>
                <el-form-item label="corpId" prop="corpId">
                    <el-input v-model="feishuInfo.corpId"></el-input>
                </el-form-item>
                <el-form-item label="appId" prop="appId">
                    <el-input v-model="feishuInfo.appId"></el-input>
                </el-form-item>
                <el-form-item label="appSecret" prop="appSecret">
                    <el-input v-model="feishuInfo.appSecret"></el-input>
                </el-form-item>
                <el-form-item label="管理员" prop="managerName">
                    <el-input v-model="feishuInfo.managerName"></el-input>
                </el-form-item>
            </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="addFeishuDig = false">取 消</el-button>
                <el-button type="primary" @click="addFeishuInfo('feishuInfo')">确 定</el-button>
            </span>
        </el-dialog>
    </section>
</template>
<script>
import App from '../../App.vue';
    
export default {
    components: { App },
    data() {
        return {
            // 课程分类选择
            categoryValue: '',
            categoryOptions: [],
            // 搜索条件
            keyword: null, // 课程名称
            instructor: null, // 讲师
            
            // 表格相关
            tableHeight: 0,
            listLoading: false,
            total: 0,
            page: 1,
            size: 20,
            list: [],
            
            // 对话框控制
            editDialogVisible: false,
            addDialogVisible: false,
            categoryManageVisible: false,
            videoDialogVisible: false, // 视频播放对话框
            currentVideoUrl: '', // 当前播放的视频URL
            
            // 当前编辑的课程数据
            currentCourse: null,
            
            // 新增课程数据
            newCourse: {
                categoryValue: '',
                courseName: '',
                courseDesc: '',
                instructor: '',
                instructorDesc: '',
                price: '',
                duration: '',
                coverImage: '',
                instructorImg: '',
                courseUrl: '',
                // 图片和文件上传
                coverImageUrl: '',
                coverImageFile: null,
                instructorImageUrl: '',
                instructorImageFile: null,
                videoFiles: []
            },
            
            // 表单验证规则
            courseRules: {
                categoryValue: [
                    { required: true, message: '请选择课程分类', trigger: 'change' }
                ],
                courseName: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' }
                ],
                instructor: [
                    { required: true, message: '请输入讲师姓名', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入课程价格', trigger: 'blur' },
                    { 
                        pattern: /^\d+(\.\d{1,1})?$/, 
                        message: '请输入正确的价格格式（整数或最多1位小数）', 
                        trigger: 'blur' 
                    }
                ],
                duration: [
                    { required: true, message: '请输入课程时长', trigger: 'blur' },
                    { 
                        pattern: /^[1-9]\d*$/, 
                        message: '请输入整数分钟数', 
                        trigger: 'blur' 
                    }
                ]
            },
            
            // 文件上传
            videoFiles: [],
            attachmentFiles: [],
            
            // 分类管理
            categoryList: [],
            newCategory: {
                label: '',
                value: '',
                coverImage: ''
            },
            
            // 分类封面设置
            coverDialogVisible: false,
            currentCategoryIndex: -1,
            coverImageUrl: '',
            coverImageFile: null,
            
            // 用户信息
            user: sessionStorage.user ? JSON.parse(sessionStorage.user) : {},
            
            // 保留原有的一些变量，以防其他功能依赖
            dialogData: null,
            editDialogA: false,
            editDialogB: false,
            editDialogC: false,
            editDialogD: false,
            editDialogF: false,
            editDialogG: false,
            editDialogH: false,
            dingdingSync: false,
            isMeal: 0,
            addStaffCountMaxNum: 0,
            expirationNewDate: null,
            reportFormList: [],
            roleList: [],
            roleIdArr: [],
            onlyContract: false,
            addFeishuDig: false,
            feishuInfo: {
                companyName: '',
                corpId: '',
                appId: '',
                appSecret: '',
                managerName: '',
            },
            feishuInfoRules: {
                companyName: [
                    { required: true, message: '请输入客户名称', trigger: 'blur' },
                ],
                corpId: [
                    { required: true, message: '请输入corpId', trigger: 'blur' },
                ],
                appId: [
                    { required: true, message: '请输入appId', trigger: 'blur' },
                ],
                appSecret: [
                    { required: true, message: '请输入appSecret', trigger: 'blur' },
                ],
                managerName: [
                    { required: true, message: '请输入管理员名称', trigger: 'blur' },
                ],
            }
        };
    },
    // 过滤器
    filters: {
    },
    methods: {
        // 播放视频
        playVideo(row) {
            if (row.courseUrl) {
                this.currentVideoUrl = row.courseUrl;
                this.videoDialogVisible = true;
            } else {
                this.$message.warning('该课程没有视频');
            }
        },
        
        // 停止视频播放
        stopVideo() {
            if (this.$refs.videoPlayer) {
                const videoElement = this.$refs.videoPlayer;
                videoElement.pause();
                videoElement.currentTime = 0;
                videoElement.src = '';
            }
            this.currentVideoUrl = '';
        },
        
        // 关闭视频对话框
        closeVideoDialog() {
            this.stopVideo();
            this.videoDialogVisible = false;
        },
        
        // 停止课程视频播放
        stopCourseVideo() {
            if (this.$refs.courseVideoPlayer) {
                const videoElement = this.$refs.courseVideoPlayer;
                videoElement.pause();
                videoElement.currentTime = 0;
                // 不清除视频源，只暂停播放
            }
        },
        
        // 删除视频
        deleteVideo() {
            this.$confirm('确认删除该视频?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 清空视频相关数据
                this.newCourse.courseUrl = '';
                this.newCourse.videoFiles = [];
                
                this.$message({
                    type: 'success',
                    message: '视频已删除!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        
        // 搜索课程列表
        searchList() {
            this.page = 1;
            this.getList();
        },
        
        // 添加课程
        addCourse() {
            this.addDialogVisible = true;
            // 这里可以初始化新课程数据
            this.newCourse = {
                categoryValue: '',
                courseName: '',
                courseDesc: '',
                instructor: '',
                instructorDesc: '',
                price: '',
                duration: '',
                coverImage: '',
                instructorImg: '',
                courseUrl: '',
                // 图片和文件上传
                coverImageUrl: '',
                coverImageFile: null,
                instructorImageUrl: '',
                instructorImageFile: null,
                videoFiles: []
            };
            
            // 使用 $nextTick 确保表单已经渲染完成后再重置验证状态
            this.$nextTick(() => {
                if (this.$refs.newCourseForm) {
                    this.$refs.newCourseForm.clearValidate();
                }
            });
        },
        
        // 分类管理
        batchManage() {
            this.categoryManageVisible = true;
            // 加载分类数据
            this.http.post('/course-type/list', {}, res => {
                if (res.code == "ok") {
                    // 将后端返回的数据转换为前端需要的格式
                    this.categoryList = res.data.map(item => ({
                        label: item.typeName,
                        value: item.id,
                        coverImage: item.coverImage || ''
                    }));
                    
                    // 同步更新下拉选项
                    this.categoryOptions = [...this.categoryList];
                } else {
                    this.$message({
                        message: res.msg || '获取分类列表失败',
                        type: 'error'
                    });
                }
            }, error => {
                this.$message({
                    message: error || '获取分类列表失败',
                    type: 'error'
                });
            });
        },
        
        // 删除课程
        deleteItem(row) {
            this.$confirm('确认删除该课程?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 调用后端API删除课程
                this.http.post('/course-info/deleteCourse', {
                    id: row.id
                }, res => {
                    if (res.code == "ok") {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList();
                    } else {
                        this.$message({
                            message: res.msg || '删除课程失败',
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error || '删除课程失败',
                        type: 'error'
                    });
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        // 编辑课程
        editItem(row) {
            // 显示加载状态
            this.listLoading = true;
            
            // 调用API获取课程详情
            this.http.post('/course-info/getDetail', {
                id: row.id
            }, res => {
                this.listLoading = false;
                if (res.code == "ok") {
                    // 使用API返回的详细数据
                    const courseDetail = res.data;
                    
                    // 重置新增课程表单，用于编辑
                    this.newCourse = {
                        id: courseDetail.id,
                        categoryValue: courseDetail.courseTypeId,
                        courseName: courseDetail.courseName,
                        courseDesc: courseDetail.courseDesc || '',
                        instructor: courseDetail.courseInstructor,
                        instructorDesc: courseDetail.instructorDesc || '',
                        price: courseDetail.coursePrice,
                        duration: courseDetail.courseDuration || '',
                        instructorImg: courseDetail.instructorImg || '',
                        coverImage: courseDetail.coverImage || '',
                        courseUrl: courseDetail.courseUrl || ''
                    };
                    
                    // 设置课程封面和讲师照片URL（如果有）
                    this.newCourse.coverImageUrl = courseDetail.coverImage ? courseDetail.coverImage : '';
                    this.newCourse.instructorImageUrl = courseDetail.instructorImg ? courseDetail.instructorImg : '';
                    
                    this.newCourse.videoFiles = courseDetail.courseUrl ? [{
                        name: '已上传视频',
                        url: courseDetail.courseUrl
                    }] : [];
                    
                    // 打开添加课程对话框（用于编辑）
                    this.addDialogVisible = true;
                    
                    // 修改对话框标题为"编辑课程"
                    setTimeout(() => {
                        const dialogTitle = document.querySelector('.el-dialog__title');
                        if (dialogTitle) {
                            dialogTitle.textContent = '编辑课程';
                        }
                    }, 100);
                } else {
                    // 如果API调用失败，使用表格行数据
                    this.currentCourse = JSON.parse(JSON.stringify(row));
                    this.editDialogVisible = true;
                    
                    this.$message({
                        message: res.msg || '获取课程详情失败',
                        type: 'warning'
                    });
                }
            }, error => {
                this.listLoading = false;
                // 如果API调用出错，使用表格行数据
                this.currentCourse = JSON.parse(JSON.stringify(row));
                this.editDialogVisible = true;
                
                this.$message({
                    message: error || '获取课程详情失败',
                    type: 'error'
                });
            });
        },
        
        // 上架/下架课程
        uploadItem(row) {
            const action = row.courseStatus === 1 ? '下架' : '上架';
            this.$confirm(`确认${action}该课程?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 调用后端API上架/下架课程
                this.http.post('/course-info/saveOrUpdate', {
                    id: row.id,
                    courseStatus: row.courseStatus === 1 ? 0 : 1 // 0: 下架, 1: 上架
                }, res => {
                    if (res.code == "ok") {
                        row.courseStatus = row.courseStatus === 1 ? 0 : 1;
                        this.$message({
                            type: 'success',
                            message: `${action}成功!`
                        });
                    } else {
                        this.$message({
                            message: res.msg || `${action}失败`,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error || `${action}失败`,
                        type: 'error'
                    });
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: `已取消${action}`
                });          
            });
        },
        
        // 处理视频文件上传前的验证
        beforeVideoUpload(file) {
            const isVideo = file.type === 'video/mp4' || file.type === 'video/avi' || file.type === 'video/x-msvideo';
            const isLt100M = file.size / 1024 / 1024 < 100;
            
            if (!isVideo) {
                this.$message.error('只能上传 MP4 或 AVI 格式的视频文件!');
            }
            if (!isLt100M) {
                this.$message.error('视频文件大小不能超过 100MB!');
            }
            
            return isVideo && isLt100M;
        },
        
        // 处理超出上传数量限制
        handleExceed(files, fileList) {
            this.$message.warning('只能上传单个视频文件，请先删除已有视频再上传新的!');
        },
        
        // 处理视频文件上传
        handleVideoChange(file, fileList) {
            // 限制只保留最新的一个文件
            if (fileList.length > 1) {
                fileList = [fileList[fileList.length - 1]];
            }
            this.newCourse.videoFiles = fileList;
            
            // 立即上传视频文件
            if (file && file.raw) {
                this.listLoading = true;
                this.uploadFile(file.raw, fileName => {
                    this.listLoading = false;
                    if (fileName) {
                        // 如果是添加课程，更新newCourse对象
                        if (this.addDialogVisible) {
                            this.newCourse.courseUrl = fileName;
                        } 
                        // 如果是编辑课程，更新currentCourse对象
                        else if (this.editDialogVisible && this.currentCourse) {
                            this.currentCourse.courseUrl = fileName;
                        }
                        this.$message({
                            type: 'success',
                            message: '视频上传成功!'
                        });
                    }
                });
            }
        },
        
        // 处理附件上传
        handleAttachmentChange(file, fileList) {
            this.attachmentFiles = fileList;
            // 立即上传附件文件
            if (file && file.raw) {
                this.listLoading = true;
                this.uploadFile(file.raw, fileName => {
                    this.listLoading = false;
                    if (fileName) {
                        // 如果是添加课程，更新newCourse对象
                        if (this.addDialogVisible) {
                            this.newCourse.attachmentUrl = fileName;
                        } 
                        // 如果是编辑课程，更新currentCourse对象
                        else if (this.editDialogVisible && this.currentCourse) {
                            this.currentCourse.attachmentUrl = fileName;
                        }
                        this.$message({
                            type: 'success',
                            message: '附件上传成功!'
                        });
                    }
                });
            }
        },
        
        // 处理讲师照片上传前的验证
        beforeImageUpload(file) {
            const isImage = file.type.indexOf('image/') === 0;
            const isLt2M = file.size / 1024 / 1024 < 2;
            
            if (!isImage) {
                this.$message.error('上传图片只能是图片格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            
            return isImage && isLt2M;
        },
        
        // 处理课程封面变更
        handleCoverImageChange(file) {
            this.newCourse.coverImageFile = file.raw;
            if (this.newCourse.coverImageFile) {
                this.newCourse.coverImageUrl = URL.createObjectURL(this.newCourse.coverImageFile);
                // 立即上传课程封面
                this.listLoading = true;
                this.uploadFile(this.newCourse.coverImageFile, fileName => {
                    this.listLoading = false;
                    if (fileName) {
                        this.newCourse.coverImage = fileName;
                        this.$message({
                            type: 'success',
                            message: '课程封面上传成功!'
                        });
                    }
                });
            }
        },

        // 处理讲师照片变更
        handleInstructorImageChange(file) {
            this.newCourse.instructorImageFile = file.raw;
            if (this.newCourse.instructorImageFile) {
                this.newCourse.instructorImageUrl = URL.createObjectURL(this.newCourse.instructorImageFile);
                // 立即上传讲师照片
                this.listLoading = true;
                this.uploadFile(this.newCourse.instructorImageFile, fileName => {
                    this.listLoading = false;
                    if (fileName) {
                        this.newCourse.instructorImg = fileName;
                        this.$message({
                            type: 'success',
                            message: '讲师照片上传成功!'
                        });
                    }
                });
            }
        },
        
        // 上传文件到服务器
        uploadFile(file, callback) {
            if (!file) {
                callback(null);
                return;
            }
            
            const formData = new FormData();
            formData.append('multipartFile', file);
            
            this.http.uploadFile('/common/uploadFile', formData, res => {
                if (res.code == "ok") {
                    callback(res.data);
                } else {
                    this.$message({
                        message: res.msg || '文件上传失败',
                        type: 'error'
                    });
                    callback(null);
                }
            }, error => {
                this.$message({
                    message: error || '文件上传失败',
                    type: 'error'
                });
                callback(null);
            });
        },
        
        // 提交课程（新增或编辑）
        submitNewCourse(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 显示加载状态
                    this.listLoading = true;
                    
                    // 准备课程数据
                    let categoryOption = this.categoryOptions.find(
                        option => option.value === this.newCourse.categoryValue
                    );
                    
                    // 准备API请求参数
                    const params = {
                        courseTypeId: this.newCourse.categoryValue,
                        courseName: this.newCourse.courseName,
                        courseDesc: this.newCourse.courseDesc,
                        courseInstructor: this.newCourse.instructor,
                        instructorDesc: this.newCourse.instructorDesc,
                        coursePrice: this.newCourse.price,
                        instructorImg: this.newCourse.instructorImg,
                        coverImage: this.newCourse.coverImage,
                        courseUrl: this.newCourse.courseUrl,
                        courseDuration: this.newCourse.duration
                    };
                    
                    // 如果是编辑模式，添加课程ID
                    if (this.newCourse.id) {
                        params.id = this.newCourse.id;
                    } else {
                        // 新增课程默认为未上架状态
                        params.courseStatus = 0;
                    }
                    
                    // 调用后端API保存课程数据
                    this.http.post('/course-info/saveOrUpdate', params, res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            // 清空表单
                            this.newCourse = {
                                categoryValue: '',
                                courseName: '',
                                courseDesc: '',
                                instructor: '',
                                instructorDesc: '',
                                price: '',
                                duration: '',
                                coverImage: '',
                                instructorImg: '',
                                courseUrl: '',
                                // 图片和文件上传
                                coverImageUrl: '',
                                coverImageFile: null,
                                instructorImageUrl: '',
                                instructorImageFile: null,
                                videoFiles: []
                            };
                            
                            this.addDialogVisible = false;
                            
                            this.$message({
                                type: 'success',
                                message: params.id ? '更新课程成功!' : '添加课程成功!'
                            });
                            
                            // 刷新列表
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg || (params.id ? '更新课程失败' : '添加课程失败'),
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.listLoading = false;
                        this.$message({
                            message: error || (params.id ? '更新课程失败' : '添加课程失败'),
                            type: 'error'
                        });
                    });
                } else {
                    return false;
                }
            });
        },
        
        // 更新课程
        updateCourse(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 显示加载状态
                    this.listLoading = true;
                    
                    // 准备课程数据
                    let categoryOption = this.categoryOptions.find(
                        option => option.value === this.currentCourse.categoryValue
                    );
                    
                    // 调用后端API更新课程数据
                    this.http.post('/course-info/saveOrUpdate', {
                        id: this.currentCourse.id,
                        courseTypeId: this.currentCourse.categoryValue,
                        courseName: this.currentCourse.courseName,
                        courseInstructor: this.currentCourse.instructor,
                        coursePrice: this.currentCourse.price.replace(/¥/g, ''),
                        courseUrl: this.currentCourse.courseUrl,
                        attachmentUrl: this.currentCourse.attachmentUrl
                    }, res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            // 更新课程对象
                            const categoryName = categoryOption ? categoryOption.label : this.currentCourse.category;
                            this.currentCourse.category = categoryName;
                            this.currentCourse.videos = this.videoFiles.length + '个';
                            this.currentCourse.attachments = this.attachmentFiles.length + '个';
                            
                            this.editDialogVisible = false;
                            
                            this.$message({
                                type: 'success',
                                message: '更新课程成功!'
                            });
                            
                            // 刷新列表
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg || '更新课程失败',
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.listLoading = false;
                        this.$message({
                            message: error || '更新课程失败',
                            type: 'error'
                        });
                    });
                } else {
                    return false;
                }
            });
        },
        
        // 添加分类
        addCategory() {
            if (!this.newCategory.label || !this.newCategory.label.trim()) {
                this.$message({
                    type: 'warning',
                    message: '请输入分类名称!'
                });
                return;
            }
            
            // 调用后端API保存课程分类
            this.http.post('/course-type/saveOrUpdate', {
                typeName: this.newCategory.label
            }, res => {
                if (res.code == "ok") {
                    // 生成唯一ID作为value，实际项目中应该使用后端返回的ID
                    const categoryId = res.data && res.data.id ? res.data.id : 'category_' + Date.now();
                    this.newCategory.value = categoryId;
                    
                    // 添加到分类列表
                    this.categoryList.push({...this.newCategory});
                    this.categoryOptions.push({...this.newCategory});
                    
                    // 清空输入
                    this.newCategory.label = '';
                    this.newCategory.value = '';
                    
                    this.$message({
                        type: 'success',
                        message: '添加分类成功!'
                    });
                } else {
                    this.$message({
                        message: res.msg || '添加分类失败',
                        type: 'error'
                    });
                }
            }, error => {
                this.$message({
                    message: error || '添加分类失败',
                    type: 'error'
                });
            });
        },
        
        // 删除分类
        deleteCategory(index, row) {
            this.$confirm('确认删除该分类?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 调用后端API删除课程分类
                this.http.post('/course-type/delete', {
                    id: row.value
                }, res => {
                    if (res.code == "ok") {
                        // 从分类列表中删除
                        this.categoryList.splice(index, 1);
                        
                        // 从下拉选项中删除
                        const optionIndex = this.categoryOptions.findIndex(item => item.value === row.value);
                        if (optionIndex !== -1) {
                            this.categoryOptions.splice(optionIndex, 1);
                        }
                        
                        this.$message({
                            type: 'success',
                            message: '删除分类成功!'
                        });
                    } else {
                        this.$message({
                            message: res.msg || '删除分类失败',
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error || '删除分类失败',
                        type: 'error'
                    });
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        
        // 设置分类封面
        setCategoryCover(index, row) {
            this.currentCategoryIndex = index;
            this.coverImageUrl = row.coverImage || '';
            this.coverDialogVisible = true;
        },
        
        // 处理封面图片上传前的验证
        beforeCoverUpload(file) {
            const isImage = file.type.indexOf('image/') === 0;
            const isLt2M = file.size / 1024 / 1024 < 2;
            
            if (!isImage) {
                this.$message.error('上传封面图片只能是图片格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传封面图片大小不能超过 2MB!');
            }
            
            return isImage && isLt2M;
        },
        
        // 处理封面图片变更
        handleCoverChange(file) {
            this.coverImageFile = file.raw;
            if (this.coverImageFile) {
                this.coverImageUrl = URL.createObjectURL(this.coverImageFile);
                
                // 获取当前分类的ID
                if (this.currentCategoryIndex >= 0) {
                    const categoryId = this.categoryList[this.currentCategoryIndex].value;
                    
                    // 立即上传封面图片
                    this.listLoading = true;
                    
                    // 创建FormData对象用于上传文件
                    const formData = new FormData();
                    formData.append('id', categoryId);
                    formData.append('coverImage', this.coverImageFile);
                    
                    // 调用上传图片的API
                    this.http.uploadFile('/course-type/uploadCover', formData, res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            // 上传成功后，获取返回的图片URL
                            const imageUrl = res.data && res.data.url ? res.data.url : this.coverImageUrl;
                            
                            // 更新本地数据
                            this.categoryList[this.currentCategoryIndex].coverImage = imageUrl;
                            
                            // 同步更新到分类选项中
                            const optionIndex = this.categoryOptions.findIndex(item => item.value === categoryId);
                            if (optionIndex !== -1) {
                                this.categoryOptions[optionIndex].coverImage = imageUrl;
                            }
                            
                            this.$message({
                                type: 'success',
                                message: '封面图片上传成功!'
                            });
                        } else {
                            this.$message({
                                message: res.msg || '上传封面图片失败',
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.listLoading = false;
                        this.$message({
                            message: error || '上传封面图片失败',
                            type: 'error'
                        });
                    });
                }
            }
        },
        
        // 保存分类封面
        saveCategoryCover() {
            if (!this.coverImageUrl) {
                this.$message.warning('请先上传封面图片!');
                return;
            }
            
            // 关闭对话框
            this.coverDialogVisible = false;
            this.$message({
                type: 'success',
                message: '设置封面成功!'
            });
        },
        
        // 添加飞书信息
        addFeishuInfo(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.http.post('/company/addFeiShuInfo', {
                        companyName: this.feishuInfo.companyName,
                        corpId: this.feishuInfo.corpId,
                        appId: this.feishuInfo.appId,
                        appSecret: this.feishuInfo.appSecret,
                        managerName: this.feishuInfo.managerName,
                    }, res => {
                        if (res.code == 'ok') {
                            this.addFeishuDig = false;
                            this.feishuInfo = {};
                            this.$message({
                                message: '新增飞书客户初始化成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, err => {
                        this.$message({
                            message: err,
                            type: 'error'
                        });
                    });
                } else {
                    return false;
                }
            });
        },
        
        // 分页相关
        handleCurrentChange(val) {
            this.page = val;
            this.getList();
        },
        handleSizeChange(val) {
            this.size = val;
            this.getList();
        },
        
        // 获取课程列表
        getList() {
            this.listLoading = true;
            
            // 调用后端API获取课程列表
            this.http.post('/course-info/list', {
                page: this.page,
                size: this.size,
                courseType: this.categoryValue,
                courseName: this.keyword,
                courseInstructor: this.instructor
            }, res => {
                this.listLoading = false;
                if (res.code == "ok") {
                    this.list = res.data.records;
                    this.total = res.data.total;
                } else {
                    // 如果API调用失败，使用模拟数据（实际项目中可以移除这部分）
                    this.useMockData();
                    this.$message({
                        message: res.msg || '获取课程列表失败',
                        type: 'error'
                    });
                }
            }, error => {
                // 如果API调用出错，使用模拟数据（实际项目中可以移除这部分）
                this.useMockData();
                this.listLoading = false;
                this.$message({
                    message: error || '获取课程列表失败',
                    type: 'error'
                });
            });
        },
        
        // 使用模拟数据（实际项目中可以移除这个方法）
        useMockData() {
            // 模拟数据
            const mockData = [
                {
                    id: 1,
                    category: '考试认证流程介绍',
                    courseName: '考试认证流程详解',
                    instructor: '张老师',
                    price: '¥299',
                    duration: '2小时',
                    videos: '5个',
                    attachments: '3个',
                    isUploaded: true
                },
                {
                    id: 2,
                    category: '线下研修班',
                    courseName: '线下实战培训',
                    instructor: '李老师',
                    price: '¥599',
                    duration: '8小时',
                    videos: '0个',
                    attachments: '5个',
                    isUploaded: true
                },
                {
                    id: 3,
                    category: '基础法规班',
                    courseName: '法规基础知识',
                    instructor: '王老师',
                    price: '¥199',
                    duration: '3小时',
                    videos: '10个',
                    attachments: '2个',
                    isUploaded: false
                },
                {
                    id: 4,
                    category: '高级培训班',
                    courseName: '高级实战技巧',
                    instructor: '赵老师',
                    price: '¥899',
                    duration: '12小时',
                    videos: '15个',
                    attachments: '8个',
                    isUploaded: true
                }
            ];
            
            // 过滤数据
            let filteredData = [...mockData];
            
            if (this.categoryValue) {
                let categoryOption = this.categoryOptions.find(option => option.value === this.categoryValue);
                const categoryName = categoryOption ? categoryOption.label : '';
                filteredData = filteredData.filter(item => item.category === categoryName);
            }
            
            if (this.keyword) {
                filteredData = filteredData.filter(item => 
                    item.courseName.toLowerCase().includes(this.keyword.toLowerCase())
                );
            }
            
            if (this.instructor) {
                filteredData = filteredData.filter(item => 
                    item.instructor.toLowerCase().includes(this.instructor.toLowerCase())
                );
            }
            
            this.total = filteredData.length;
            
            // 分页
            const start = (this.page - 1) * this.size;
            const end = start + this.size;
            this.list = filteredData.slice(start, end);
        }
    },
    created() {
        let height = window.innerHeight;
        this.tableHeight = height - 195;
        const that = this;
        window.onresize = function temp() {
            that.tableHeight = window.innerHeight - 195;
        };
        
        // 初始化分类列表
        this.categoryList = [...this.categoryOptions];
    },
    mounted() {
        // 获取课程分类数据
        this.http.post('/course-type/list', {}, res => {
            if (res.code == "ok") {
                // 将后端返回的数据转换为前端需要的格式
                this.categoryList = res.data.map(item => ({
                    label: item.typeName,
                    value: item.id,
                    coverImage: item.coverImage || ''
                }));
                
                // 同步更新下拉选项
                this.categoryOptions = [...this.categoryList];
            } else {
                this.$message({
                    message: res.msg || '获取分类列表失败',
                    type: 'error'
                });
            }
        }, error => {
            this.$message({
                message: error || '获取分类列表失败',
                type: 'error'
            });
        });
        
        // 获取课程列表
        this.getList();
    }
};
</script>

<style lang="scss" scoped>
.rg_span{
    display: inline-block;
}
.rg_span span {
    text-align: right;
    box-sizing: border-box;
    padding-right: 10px;
}
.el-dialog__title {
    display: inline-table;
    margin-top: 20px;
}
.btns .el-button{
    margin-left: 10px;
    margin-bottom: 5px;
}
</style>
<style>
.course-cover-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 4px;
}

.otherForm .el-form-item{
    float: left;
    width: 50%;
    margin: 0;
}

/* 视频播放器样式 */
.video-player-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

.video-player {
    max-width: 100%;
    max-height: 500px;
}

.video-preview {
    margin-top: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    background-color: #f9f9f9;
}

.video-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.video-title {
    font-weight: bold;
    color: #303133;
}

.delete-video-btn {
    color: #f56c6c;
    padding: 0;
}

.delete-video-btn:hover {
    color: #f78989;
}

.video-name {
    margin-top: 5px;
    color: #606266;
    font-size: 14px;
}

/* 编辑器样式 */
.editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.editor-toolbar {
    background-color: #f5f7fa;
    padding: 5px;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
}

.editor-btn {
    background: none;
    border: none;
    padding: 5px 8px;
    margin: 0 2px;
    cursor: pointer;
    border-radius: 3px;
}

.editor-btn:hover {
    background-color: #e4e7ed;
}

.editor-separator {
    width: 1px;
    height: 16px;
    background-color: #dcdfe6;
    margin: 0 5px;
}

.editor-select {
    height: 24px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    margin: 0 5px;
}

.editor-content {
    width: 100%;
    min-height: 120px;
    padding: 10px;
    border: none;
    resize: vertical;
    outline: none;
    font-family: Arial, sans-serif;
    font-size: 14px;
}

/* 上传链接样式 */
.upload-item {
    margin-bottom: 20px;
}

.upload-link {
    color: #409eff;
    cursor: pointer;
    font-size: 14px;
}

.upload-link:hover {
    text-decoration: underline;
}

/* 分类封面图片样式 */
.category-cover-image {
    width: 100px;
    height: 56px;
    object-fit: cover;
    border-radius: 4px;
}

.cover-upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
}

.cover-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 100px;
    margin-bottom: 10px;
}

.cover-uploader:hover {
    border-color: #409EFF;
}

.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.cover-image {
    width: 178px;
    height: 100px;
    display: block;
    object-fit: cover;
}

.cover-tip {
    color: #909399;
    font-size: 12px;
    margin-top: 10px;
}

/* 讲师照片上传样式 */
.instructor-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
}

.instructor-uploader:hover {
    border-color: #409EFF;
}

.instructor-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.instructor-image {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}

.upload-tip {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
}
</style>
