var exhibitionId = getUrlParam("exhibition_id");
var exhibitId = getUrlParam("exhibit_id");
var number = getUrlParam("number");
var exhibitionStyle = getUrlParam("style")
$(function () {
    if (exhibitId == null) {
        // 标题
        let content = 
        `<h1 class="title" id="title">编辑#${number}展位</h1>
        <input class="back-btn" type="button" value="返回" onclick="back()">
        <input class="preview-btn" type="button" value="预览" onclick="preview()">`
        $('#top-panel').html(content)
        return
    }
    $.ajax({
        type: "POST",
        url: "/manage_exhibits/edit",
        data: JSON.stringify({
            id: Number(exhibitId)
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            // 标题
            let content = 
            `<h1 class="title" id="title">编辑#${number}展位</h1>
            <input class="back-btn" type="button" value="返回" onclick="back()">
            <input class="preview-btn" type="button" value="预览" onclick="preview()">`
            $('#top-panel').html(content)

            // 上传展品
            content = 
            `<div class="cover-frame">
                <img class="cover-img" id="cover-img" src="${data.Url}" ${checkVisibleState(isImage(data.Url))}>
                <video class="cover-video" id="cover-video" src="${data.Url}" controls ${checkVisibleState(isVideo(data.Url))}></video>
            </div>
            <div class="cover-input-panel">
                <h3>上传展品(格式mp4)</h3>
                <input type="file" id="upload-cover-btn" accept="video/mp4" onchange="_uploadExhibit(this)">
                <p>视频分辨率比例必须为16:9</p>
            </div>`
            $('#cover-panel').html(content)

            // 简介说明
            content = 
            `<p>作品信息</p>
            <input class="detail-title" id="detail-title" type="text" spellcheck="false" value="${data.Title}">`
            $('#title-panel').html(content)

            // 音频介绍
            content = 
            `<p>语音介绍(格式mp3/ogg)</p>
            <audio class="detail-audio" id="detail-audio" src="${data.Audio}" controls></audio>
            <input class="input-audio" type="file" accept="audio/mpeg,audio/ogg" onchange="_uploadExhibitAudioDetail(this)">`
            $('#detail-audio-panel').html(content)

            // 音频介绍
            content = 
            `<p>作品介绍</p>
            <textarea class="input-introduction" id="input-introduction" maxlength="1000" spellcheck="false" placeholder="最大输入长度1000字">${data.Introduction}</textarea>`
            $('#detail-introduction-panel').html(content)

            // 展品图文详情
            let detailDatas = JSON.parse(data.Details)
            insertDetails(detailDatas)
            
            // 作者介绍
            content = 
            `<p>艺术家介绍</p>
            <textarea class="input-author-introduction" id="input-author-introduction" maxlength="1000" spellcheck="false" placeholder="最大输入长度1000字">${data.AuthorIntroduction}</textarea>`
            $('#detail-author-introduction-panel').html(content)
        },
        error: function (xhr, textStatus, error) {
            var msg = JSON.parse(xhr.responseText);
            alert(msg.error);
        }
    });
})

function back() {
    history.back();
}

function preview() {
    if (exhibitId == null) {
        alert("视频尚未保存，无法预览")
        return
    }
    if (exhibitionStyle == "1") {
        window.open("/resources/studio_modern/index.html?id="+exhibitionId+"&number="+number+"&ignore_visit=1",null,"height=540,width=960,status=no,toolbar=no,menubar=no,alwaysRaised=yes,depended=yes,location=no,z-look=yes")
    } else if (exhibitionStyle == "2") {
        window.open("/resources/studio_ancient/index.html?id="+exhibitionId+"&number="+number+"&ignore_visit=1",null,"height=540,width=960,status=no,toolbar=no,menubar=no,alwaysRaised=yes,depended=yes,location=no,z-look=yes")
    }
}

function update() {
    // 展品
    var exhibit = document.getElementById("cover-img");
    if (exhibit.src.length == 0 || !isImage(exhibit.src)) {
        exhibit = document.getElementById("cover-video");
        if (exhibit.src.length == 0 || !isVideo(exhibit.src)) {
            alert("展品不可为空！");
            return;
        }
    }
    // 展品标题
    var detailTitle = document.getElementById("detail-title");
    if (detailTitle.value.length == 0) {
        alert("作品信息不可为空！");
        return
    }
    // 语音介绍
    var detailAudio = document.getElementById("detail-audio");
    // 作品介绍
    var introduction = document.getElementById("input-introduction");
    // if (introduction.value.length == 0) {
    //     alert("作品介绍不可为空！");
    //     return
    // }
    // 作品详情
    var detailList = document.getElementById("detail-list-panel");
    // if (detailList.children.length == 0) {
    //     alert("作品详情不可为空!");
    //     return
    // }
    var detailListData = []
    for (let i = 0; i < detailList.children.length; i++) {
        let detailData = getDetailItemData(detailList.children[i])
        if (detailData.media.length == 0) {
            alert("作品详情文件不可为空!");
            return
        }
        detailListData.push(detailData)
    }
    // if (detailListData.length == 0) {
    //     alert("作品详情不可为空!");
    //     return
    // }
    // 艺术家介绍
    var authorIntroduction = document.getElementById("input-author-introduction");
    // if (authorIntroduction.value.length == 0) {
    //     alert("艺术家介绍不可为空！");
    //     return
    // }
    $.ajax({
        type: "POST",
        url: "/manage_exhibits/update",
        data: JSON.stringify({
            exhibition_id: Number(exhibitionId),
            room_index: 3, // 3表示类型为演播厅
            number: Number(number),
            url: exhibit.src,
            // 详情
            title: detailTitle.value,
            audio: detailAudio.src,
            introduction: introduction.value,
            details: JSON.stringify(detailListData),
            author_introduction: authorIntroduction.value
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert("更新展位成功")
        },
        error: function (xhr, textStatus, error) {
            var msg = JSON.parse(xhr.responseText);
            alert(msg.error);
        }
    });
}

function deleteExhibit() {
    if (exhibitId == null) {
        alert("该展品尚未保存，无法删除!")
        return
    }
    if (confirm("展品删除后不可恢复，确认删除吗？")) {
        $.ajax({
            type: "POST",
            url: "/manage_exhibits/delete",
            data: JSON.stringify({
                id: Number(exhibitId)
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert("删除展品成功")
                back();
            },
            error: function (xhr, textStatus, error) {
                var msg = JSON.parse(xhr.responseText);
                alert(msg.error);
            }
        });
    }
}

// 插入作品所有详情
function insertDetails(details) {
    let content = ''
    details.forEach(d => {
        let imgSrc = ""
        let videoSrc = ""
        if (isImage(d.media)) {
            imgSrc = d.media
        } else if (isVideo(d.media)) {
            videoSrc = d.media
        }
        content += 
        `<div class="detail-item-panel">
            <hr style="width: 70%;background: #eee;">
            <img class="detail-media-img" src="${imgSrc}" ${checkVisibleState(imgSrc.length > 0)}>
            <video class="detail-media-video" src="${videoSrc}" controls ${checkVisibleState(videoSrc.length > 0)}></video>
            <input class="input-detail-media" type="file" accept="image/jpeg,image/png,video/mp4" onchange="_uploadExhibitDetail(this)">
            <input class="input-detail-delete-btn" type="button" value="删除" onclick="deleteDetail(this)">
            <textarea class="detail-label" maxlength="50" spellcheck="false" placeholder="最大输入长度50字">${d.detail}</textarea>
        </div>`
    })
    if (content.length > 0) {
        $('#detail-list-panel').html(content)
    }
}

// 添加作品详情
function addDetail(btn) {
    let detailItem = 
    `<div class="detail-item-panel">
        <hr style="width: 70%;background: #eee;">
        <img class="detail-media-img" src="">
        <video class="detail-media-video" src="" controls hidden></video>
        <input class="input-detail-media" type="file" accept="image/jpeg,image/png,video/mp4" onchange="_uploadExhibitDetail(this)">
        <input class="input-detail-delete-btn" type="button" value="删除" onclick="deleteDetail(this)">
        <textarea class="detail-label" maxlength="50" spellcheck="false" placeholder="最大输入长度50字"></textarea>
    </div>`
    $('#detail-list-panel').append(detailItem)
}

// 删除作品详情
function deleteDetail(btn) {
    if (confirm("确定删除该条数据吗？")) {
        var detailList = document.getElementById("detail-list-panel")
        detailList.removeChild(btn.parentNode)
    }
}

function getDetailItemData(item) {
    var dest = {}
    item.children.forEach(element => {
        if (element.className == "detail-label") {
            dest.detail = element.value
        } else {
            var src = ""
            if (element.className == "detail-media-img") {
                if (element.src.length > 0) {
                    src = element.src
                }
            }
            if (src.length == 0) {
                if (element.className == "detail-media-video") {
                    if (element.src.length > 0) {
                        src = element.src
                    }
                }
            }
            if (src.length > 0 && (isImage(src) || isVideo(src))) {
                dest.media = src
            }
        }
    });
    return dest
}

// upload
function _uploadExhibit(file) {
    uploadExhibit(file, function (url) {
        var imgExhibit = document.getElementById("cover-img");
        var videoExhibit = document.getElementById("cover-video");
        if (isImage(url)) {
            imgExhibit.hidden = false
            videoExhibit.hidden = true
            imgExhibit.src = url
            videoExhibit.src = ""
        } else if (isVideo(url)) {
            imgExhibit.hidden = true
            videoExhibit.hidden = false
            videoExhibit.src = url
            imgExhibit.src = ""
        }
    })
}

function _uploadExhibitAudioDetail(file) {
    uploadExhibitAudioDetail(file, function (url) {
        var audio = document.getElementById("detail-audio");
        audio.src = url;
    })
}

function _uploadExhibitDetail(file) {
    uploadExhibitDetail(file, function (url) {
        var imgExhibit = null
        var videoExhibit = null
        file.parentNode.children.forEach(element => {
            if (element.className == "detail-media-img") {
                imgExhibit = element
            } else if (element.className == "detail-media-video") {
                videoExhibit = element
            }
        })
        if (isImage(url)) {
            imgExhibit.hidden = false
            videoExhibit.hidden = true
            imgExhibit.src = url
            videoExhibit.src = ""
        } else if (isVideo(url)) {
            imgExhibit.hidden = true
            videoExhibit.hidden = false
            videoExhibit.src = url
            imgExhibit.src = ""
        }
    })
}