<!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-add">
        <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" 
                       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" 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">
        
        <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 type="text/javascript">
    var prefix = ctx + "kylin/artist";
    var platformUrl = "[[${platformUrl}]]";
    var albumImagesList = [];

    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;
        }

        // 检查艺人名称是否已存在
        var nameExists = false;
        $.ajax({
            url: prefix + "/checkName",
            type: "post",
            data: { artistName: artistName },
            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;
        }

        // 将相册图片列表转换为JSON数组
        var albumImagesJson = JSON.stringify(albumImagesList);
        
        if ($.validate.form()) {
            var data = $('#form-artist-add').serializeArray();
            // 添加富文本内容
            data.push({name: 'introduction', value: introduction});
            // 添加相册图片（作为JSON数组字符串）
            data.push({name: 'albumImagesJson', value: albumImagesJson});
            $.operate.save(prefix + "/create", data);
        }
    }

    $(function () {
        // 艺人名称字数统计和实时校验
        $('#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();
            }
        });
        
        // 艺人名称失去焦点校验
        $('#artistName').on('blur', function() {
            var value = $(this).val().trim();
            $(this).parent().find('.error-msg').remove();
            
            if (!value) {
                $(this).addClass('is-invalid');
                $(this).parent().append('<span class="error-msg text-danger">请填写艺人名称</span>');
            } else if (value.length > 50) {
                $(this).addClass('is-invalid');
                $(this).parent().append('<span class="error-msg text-danger">艺人名称不能超过50个字</span>');
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        // 初始化富文本编辑器
        $('#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("图片上传服务异常");
                        }
                    });
                }
            }
        });

        // 初始化头像上传
        $("#fileinput-avatar").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload/unsm",
            "uploadExtraData": {
                "pathName": "artist/avatar",
                "buckType": 1
            },
            autoReplace: true,
            dropZoneTitle: "请上传艺人头像（1:1比例，仅限1张）",
            maxFileCount: 1,
            maxFileSize: 5120,
            allowedFileExtensions: ['jpg', 'png', 'jpeg'],
            msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB，最大支持上传5M文件',
            msgFilesTooMany: '只能上传1张头像图片！'
        });

        $("#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);
        });

        // 初始化相册上传
        $("#fileinput-album").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload/unsm",
            "uploadExtraData": {
                "pathName": "artist/album",
                "buckType": 1
            },
            uploadAsync: true,  // 异步上传，每次上传一个文件
            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,
            validateInitialCount: true,
            maxTotalFileCount: 20
        }).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);
        });

        $("#fileinput-album").on("fileremoved", function(event, id, index) {
            // 从列表中移除对应的图片
            if (index < albumImagesList.length) {
                albumImagesList.splice(index, 1);
            }
        });
    });
</script>
</body>
</html>
