<!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="files" 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}]]";
    var artistData = [[${ArtistVo}]];
    var albumImagesList = [];
    var originalArtistName = artistData.artistName;

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

        var albumImagesJson = JSON.stringify(albumImagesList);

        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 () {
        // 初始化字数统计
        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个字',
            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');
                    }
                }
            }
        });

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

        // 初始化相册图片列表
        if (artistData.albumImages && artistData.albumImages.length > 0) {
            albumImagesList = artistData.albumImages;
        }

        // 初始化头像上传
        var avatarInitialPreview = [];
        var avatarInitialPreviewConfig = [];
        if (artistData.avatarUrl) {
            avatarInitialPreview.push(artistData.avatarUrl);
            avatarInitialPreviewConfig.push({
                caption: "当前头像",
                url: "#",
                key: 1
            });
        }

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

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

        // 初始化相册上传
        var albumInitialPreview = [];
        var albumInitialPreviewConfig = [];
        if (albumImagesList.length > 0) {
            albumImagesList.forEach(function(img, index) {
                albumInitialPreview.push(img);
                albumInitialPreviewConfig.push({
                    caption: "相册图片" + (index + 1),
                    url: "#",
                    key: index + 1
                });
            });
        }

        $("#fileinput-album").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload/unsm",
            "uploadExtraData": {
                "pathName": "artist/album",
                "buckType": 1
            },
            initialPreview: albumInitialPreview,
            initialPreviewAsData: true,
            initialPreviewConfig: albumInitialPreviewConfig,
            dropZoneTitle: "请上传艺人相册图片",
            maxFileCount: 20,
            maxFileSize: 5120,
            allowedFileExtensions: ['jpg', 'png', 'jpeg'],
            msgSizeTooLarge: '文件 "{name}" ({size} KB) 超过了允许大小 {maxSize} KB，最大支持上传5M文件'
        });

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