<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('编辑艺人')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-artist-edit" th:object="${ArtistVo}">
        <input type="hidden" name="artistId" th:field="*{artistId}">
        
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">艺人名称：</label>
            <div class="col-sm-10">
                <input class="form-control" type="text" name="artistName" id="artistName" 
                       th:field="*{artistName}" maxlength="50" placeholder="最多输入50个字" required>
                <span class="help-block m-b-none text-muted">
                    <span id="nameCount">0</span>/50 字
                </span>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">艺人类型：</label>
            <div class="col-sm-10">
                <select class="form-control" name="artistType" id="artistType" th:field="*{artistType}" required>
                    <option value="">请选择艺人类型</option>
                    <option value="1">音乐人</option>
                    <option value="2">艺术家</option>
                    <option value="3">厂牌</option>
                    <option value="4">品牌方</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">艺人头像：</label>
            <div class="col-sm-10">
                <div class="file-loading">
                    <input id="fileinput-avatar" type="file" name="file" data-browse-on-zone-click="true">
                </div>
                <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 支持上传jpg、png格式图片，最大支持5M，上传后按照1:1格式进行裁剪</span>
            </div>
        </div>
        <input hidden id="avatarUrl" name="avatarUrl" th:field="*{avatarUrl}">
        
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">艺人简介：</label>
            <div class="col-sm-10">
                <div id="introduction" name="introduction"></div>
                <span class="help-block m-b-none text-muted">
                    <span id="introCount">0</span>/2000 字
                </span>
            </div>
        </div>
        
        <div class="form-group">
            <label class="col-sm-2 control-label">艺人相册：</label>
            <div class="col-sm-10">
                <div class="file-loading">
                    <input id="fileinput-album" type="file" name="file" multiple data-browse-on-zone-click="true">
                </div>
                <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 支持上传jpg、png格式图片，单次最多上传20张，每张最大支持5M</span>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: summernote-js"/>
<script th:inline="javascript">
    var prefix = ctx + "kylin/artist";
    var platformUrl = /*[[${platformUrl}]]*/ "";
    
    // 使用安全的方式获取数据，避免JavaScript语法错误
    var artistData = {
        artistId: /*[[${ArtistVo?.artistId}]]*/ "",
        artistName: /*[[${ArtistVo?.artistName}]]*/ "",
        artistType: /*[[${ArtistVo?.artistType}]]*/ 0,
        avatarUrl: /*[[${ArtistVo?.avatarUrl}]]*/ "",
        introduction: /*[[${ArtistVo?.introduction}]]*/ "",
        albumImages: /*[[${ArtistVo?.albumImages}]]*/ []
    };
    
    var albumImagesList = [];
    var originalArtistName = "";
    
    console.log("原始艺人数据:", artistData);
    
    // 安全地获取艺人数据
    if (artistData) {
        originalArtistName = artistData.artistName || "";
        
        // 初始化相册图片列表
        if (artistData.albumImages && Array.isArray(artistData.albumImages) && artistData.albumImages.length > 0) {
            albumImagesList = artistData.albumImages.slice(); // 复制数组
            console.log("初始化相册图片列表:", albumImagesList);
        } else {
            console.log("没有相册图片数据");
        }
    } else {
        console.error("艺人数据为空");
    }

    function submitHandler() {
        var artistName = $('#artistName').val().trim();
        if (!artistName) {
            $.modal.alertWarning("请填写艺人名称");
            $('#artistName').focus();
            return false;
        }
        
        if (artistName.length > 50) {
            $.modal.alertWarning("艺人名称最多输入50个字");
            $('#artistName').focus();
            return false;
        }

        // 如果艺人名称有修改，检查是否已存在
        if (artistName !== originalArtistName) {
            var nameExists = false;
            $.ajax({
                url: prefix + "/checkName",
                type: "post",
                data: { 
                    artistName: artistName,
                    artistId: artistData.artistId
                },
                async: false,
                success: function(result) {
                    if (result.code != 0) {
                        $.modal.alertWarning("艺人名称已被其他艺人使用");
                        $('#artistName').focus();
                        nameExists = true;
                    }
                }
            });
            
            if (nameExists) {
                return false;
            }
        }

        var artistType = $('#artistType').val();
        if (!artistType) {
            $.modal.alertWarning("请选择艺人类型");
            $('#artistType').focus();
            return false;
        }

        var avatarUrl = $('#avatarUrl').val();
        if (!avatarUrl) {
            $.modal.alertWarning("请上传艺人头像");
            return false;
        }

        var introduction = $('#introduction').summernote('code');
        if (!introduction || introduction.trim() === '' || introduction === '<p><br></p>') {
            $.modal.alertWarning("请填写艺人简介");
            return false;
        }
        
        var introText = $('<div>').html(introduction).text();
        if (introText.length > 2000) {
            $.modal.alertWarning("艺人简介最多输入2000个字");
            return false;
        }

        // 重新构建最终的相册列表
        // 方案：遍历当前显示的所有预览图，提取图片URL
        var finalAlbumList = [];
        
        // 获取所有预览框
        var previews = $("#fileinput-album").parent().find('.file-preview-frame');
        previews.each(function() {
            var $preview = $(this);
            // 检查是否是初始预览（有data-fileindex属性）
            if ($preview.attr('data-fileindex') !== undefined) {
                var fileIndex = parseInt($preview.attr('data-fileindex'));
                if (fileIndex >= 0 && fileIndex < albumImagesList.length) {
                    finalAlbumList.push(albumImagesList[fileIndex]);
                }
            } else {
                // 新上传的图片，从img标签获取src
                var imgSrc = $preview.find('img').attr('src');
                if (imgSrc && imgSrc.indexOf('https://img.zhengzai.tv/') === 0) {
                    finalAlbumList.push(imgSrc);
                }
            }
        });
        
        // 如果上面的方法没有获取到，使用albumImagesList作为备份
        if (finalAlbumList.length === 0 && albumImagesList.length > 0) {
            finalAlbumList = albumImagesList.slice();
        }
        
        console.log("最终相册列表:", finalAlbumList);
        var albumImagesJson = JSON.stringify(finalAlbumList);

        if ($.validate.form()) {
            var data = $('#form-artist-edit').serializeArray();
            data.push({name: 'introduction', value: introduction});
            data.push({name: 'albumImagesJson', value: albumImagesJson});
            $.operate.save(prefix + "/update", data);
        }
    }

    $(function () {
        console.log("页面加载完成");
        console.log("艺人数据:", artistData);
        console.log("相册图片列表:", albumImagesList);
        
        // 初始化字数统计
        var nameLength = $('#artistName').val().length;
        $('#nameCount').text(nameLength);

        // 艺人名称字数统计和实时校验
        $('#artistName').on('input', function() {
            var length = $(this).val().length;
            $('#nameCount').text(length);
            
            if (length > 50) {
                $(this).addClass('is-invalid');
                $(this).parent().find('.error-msg').remove();
                $(this).parent().append('<span class="error-msg text-danger">艺人名称不能超过50个字</span>');
            } else {
                $(this).removeClass('is-invalid');
                $(this).parent().find('.error-msg').remove();
            }
        });

        // 初始化富文本编辑器
        $('#introduction').summernote({
            height: 200,
            lang: 'zh-CN',
            placeholder: '请输入艺人简介，最多输入2000个字',
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']],
                ['view', ['fullscreen', 'codeview']]
            ],
            callbacks: {
                onChange: function(contents, $editable) {
                    var text = $('<div>').html(contents).text();
                    var length = text.length;
                    $('#introCount').text(length);
                    
                    if (length > 2000) {
                        $('#introCount').addClass('text-danger');
                    } else {
                        $('#introCount').removeClass('text-danger');
                    }
                },
                onImageUpload: function(files) {
                    var data = new FormData();
                    data.append("file", files[0]);
                    data.append("pathName", "artist/introduction");
                    data.append("buckType", 1);
                    $.ajax({
                        url: platformUrl + "/platform/basicServices/alOss/upload/unsm",
                        type: "post",
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function(result) {
                            if (result.code == 0 || result.code == 200) {
                                var imgPath = result.data.ossPath;
                                var fullUrl = "https://img.zhengzai.tv/" + imgPath;
                                $('#introduction').summernote('insertImage', fullUrl);
                            } else {
                                $.modal.alertWarning(result.msg || "图片上传失败");
                            }
                        },
                        error: function() {
                            $.modal.alertWarning("图片上传服务异常");
                        }
                    });
                }
            }
        });

        // 设置富文本内容
        if (artistData && artistData.introduction) {
            $('#introduction').summernote('code', artistData.introduction);
        }

        // 初始化头像上传
        console.log("头像URL:", artistData ? artistData.avatarUrl : "无数据");
        
        $("#fileinput-avatar").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload/unsm",
            "uploadExtraData": {
                "pathName": "artist/avatar",
                "buckType": 1
            },
            autoReplace: true,
            overwriteInitial: false,
            initialPreviewAsData: true,
            initialPreview: (artistData && artistData.avatarUrl) ? [artistData.avatarUrl] : [],
            initialPreviewConfig: (artistData && artistData.avatarUrl) ? [{
                caption: "当前头像",
                size: 0,
                width: "120px",
                key: 1,
                extra: {url: artistData.avatarUrl}
            }] : [],
            dropZoneTitle: "请上传艺人头像（1:1比例，仅限1张）",
            maxFileCount: 1,
            maxFileSize: 5120,
            allowedFileExtensions: ['jpg', 'png', 'jpeg'],
            msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB，最大支持上传5M文件',
            msgFilesTooMany: '只能上传1张头像图片！',
            deleteUrl: "#",  // 设置一个假的删除URL，启用删除按钮
            previewSettings: {
                image: {width: "auto", height: "160px"}
            }
        }).on('fileloaded', function(event, file, previewId, index, reader) {
            console.log("头像加载成功:", previewId);
        }).on('fileerror', function(event, data, msg) {
            console.error("头像加载错误:", msg);
        });

        $("#fileinput-avatar").on("fileuploaded", function (event, data, previewId, index) {
            var imgPath = data.response.data.ossPath;
            var fullUrl = "https://img.zhengzai.tv/" + imgPath;
            $("#avatarUrl").val(fullUrl);
            console.log("头像上传成功:", fullUrl);
        });

        // 监听头像删除事件
        $("#fileinput-avatar").on("filedeleted", function(event, key) {
            console.log("删除头像");
            $("#avatarUrl").val("");
        });

        // 监听头像清空事件
        $("#fileinput-avatar").on("filecleared", function(event) {
            console.log("清空头像");
            $("#avatarUrl").val("");
        });

        // 初始化相册上传
        console.log("相册图片列表:", albumImagesList);
        
        // 计算还可以上传多少张图片
        var remainingCount = 20 - (albumImagesList ? albumImagesList.length : 0);
        console.log("还可以上传:", remainingCount, "张图片");
        
        $("#fileinput-album").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload/unsm",
            "uploadExtraData": {
                "pathName": "artist/album",
                "buckType": 1
            },
            uploadAsync: true,  // 异步上传，每次上传一个文件
            overwriteInitial: false,
            initialPreviewAsData: true,
            initialPreview: (albumImagesList && albumImagesList.length > 0) ? albumImagesList : [],
            initialPreviewConfig: (albumImagesList && albumImagesList.length > 0) ? 
                albumImagesList.map(function(url, index) {
                    return {
                        caption: "相册图片" + (index + 1),
                        size: 0,
                        width: "120px",
                        key: index,
                        extra: {url: url}  // 保存URL用于后续处理
                    };
                }) : [],
            dropZoneTitle: "请上传艺人相册图片（最多20张）",
            maxFileCount: 20,  // 总共最多20张
            maxFileSize: 5120,
            allowedFileExtensions: ['jpg', 'png', 'jpeg'],
            msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB，最大支持上传5M文件',
            msgFilesTooMany: '选择的文件数量({n})超过了允许的最大数量{m}，相册最多只能上传20张图片！',
            showRemove: true,
            showUpload: false,
            deleteUrl: "#",  // 设置一个假的删除URL，启用删除按钮
            previewSettings: {
                image: {width: "auto", height: "160px"}
            },
            validateInitialCount: true,  // 验证初始文件数量
            maxTotalFileCount: 20  // 包括初始文件在内的最大文件总数
        }).on('fileloaded', function(event, file, previewId, index, reader) {
            console.log("文件加载成功:", previewId);
        }).on('fileerror', function(event, data, msg) {
            console.error("文件加载错误:", msg);
        }).on('filebatchselected', function(event, files) {
            // 检查选择的文件数量
            var currentCount = $("#fileinput-album").fileinput('getFilesCount');
            console.log("当前文件总数:", currentCount);
            if (currentCount > 20) {
                $.modal.alertWarning("相册最多只能上传20张图片！");
                return false;
            }
        });

        $("#fileinput-album").on("fileuploaded", function (event, data, previewId, index) {
            var imgPath = data.response.data.ossPath;
            var fullUrl = "https://img.zhengzai.tv/" + imgPath;
            albumImagesList.push(fullUrl);
            console.log("上传后相册列表:", albumImagesList);
        });

        // 监听初始预览图片的删除事件
        $("#fileinput-album").on("filedeleted", function(event, key) {
            console.log("删除图片，key:", key);
            // key 对应 initialPreviewConfig 中的 key
            if (key >= 0 && key < albumImagesList.length) {
                albumImagesList.splice(key, 1);
                console.log("删除后相册列表:", albumImagesList);
            }
        });
        
        // 监听文件清除事件
        $("#fileinput-album").on("filecleared", function(event) {
            console.log("清空所有文件");
            albumImagesList = [];
            console.log("清空后相册列表:", albumImagesList);
        });
    });
</script>
</body>
</html>
