layui.define(['jquery',], function (exports) {
    var $ = layui.jquery;

    //删除图片
    $('.upload-image').on('click', '.delete-button', function () {
        var uploadImageContainer = $(this).closest('.upload-image');
        var inputElement = uploadImageContainer.siblings('input[type="hidden"]');
        var inputName = inputElement.attr('name');
        var existing = $('input[name="' + inputName + '"]').val();
        var tagValues = existing.split(','); // 将现有标签值转换为数组
        tagValues.splice(imgSrc, 1);
        var updated = tagValues.join(',');
        $('input[name="' + inputName + '"]').val(updated);

        var container = $(this).closest('.images');
        var imgSrc = container.find('img').attr('src');
        container.remove();
    });
    // 查看大图
    $('.upload-image').on('click', 'img', function () {
        var src = $(this).attr('src');
        window.photo(src);
    });
    window.photo = function (src) {
        var auto_img = {};
        var img = new Image();
        img.src = src;
        img.onload = function () {
            var max_height = $(window).height() - 100;
            var max_width = $(window).width();
            var rate1 = max_height / img.height;
            var rate2 = max_width / img.width;
            var rate3 = 1;
            var rate = Math.min(rate1, rate2, rate3);
            auto_img.height = img.height * rate;
            auto_img.width = img.width * rate;
            layer.open({
                type: 1,
                title: false,
                area: ['auto'],
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: "<img src='" + src + "' width='" + auto_img.width + "px' height='" + auto_img.height + "px'>"
            })
        }
    };
    //单张图片上传
    if ($('button.upload-image').length) {
        $('button.upload-image').each(function () {
            var _this = $(this);
            _upload(_this, {
                success: function (res) {
                    if (res.Status == true) {
                        layer.msg(res.Msg, {
                            icon: 1
                        });
                        _this.next().val(res.data.src).next().find('img.upload-image').attr('src', res.data.thumb);
                    } else {
                        layer.msg(res.Msg, {
                            icon: 2
                        });
                    }
                }
            });
        });
        $('div.upload-image span').click(function () {
            $(this).next().attr('src', '').parent().prev().val('');
        });
    }
    //多张图片上传
    if ($('button.upload-images').length) {
        $('button.upload-images').each(function () {
            var _this = $(this);
            _upload(_this, {
                success: function (res) {
                    if (res.Status == true) {
                        layer.msg(res.Msg, {
                            icon: 1
                        });
                        var newText = res.data.thumb;
                        var inputName = _this.next().attr('name');
                        var existing = $('input[name="' + inputName + '"]').val();
                        console.log(existing);
                        if (existing == "") {
                            //如果是空的直接增加
                            $('input[name="' + inputName + '"]').val(newText);
                        } else {
                            var ImgValues = existing.split(','); // 将现有标签值转换为数组
                            // 检查新标签是否已经存在
                            if (ImgValues.indexOf(newText) === -1) {
                                // 如果新标签不存在，则添加到数组中
                                ImgValues.push(newText);
                            }
                            // 将数组转换为以逗号分隔的字符串，并更新 input 元素的值
                            var updatedImgs = ImgValues.join(',');
                            $('input[name="' + inputName + '"]').val(updatedImgs);
                        } var uploadImageContainer = _this.siblings('div.upload-image');
                        console.log(uploadImageContainer);
                        uploadImageContainer.append('<div class="images"><img src="' + res.data.thumb + '" style="max-width: 170px;"><div class="delete-button"><i class="layui-icon layui-icon-delete"></i></div></div>');
                    } else {
                        layer.msg(res.Msg, {
                            icon: 2
                        });
                    }
                }
            });
        });
    }
    function _upload(elem, options) {
        var leftUrl = window.location.pathname.split("/")[1];
        if (leftUrl.indexOf(".php") > 0) {
            var leftUrl = '/' + leftUrl;
        } else {
            var leftUrl = '';
        }

        var Item = elem.next().attr('name');

        var form, name = 'file',
            accept = 'image/*',
            path = 'image',
            url = '/api.php/Api/Attachment/Upload/';
        form = Math.random().toString(36).substr(2);
        var input = '<input accept="' + accept + '" name="' + name + '" type="file"/>';
        $('body').append('<form enctype="multipart/form-data" id="' + form + '" style="display: none;">' + input + '</form>');
        $('body').on('change', '#' + form + ' input', function () {
            var _this = $(this);
            var data = new FormData();
            data.append(name, _this[0].files[0]);
            data.append('Item', Item);
            data.append('Path', path);
            settings = {
                contentType: false,
                data: data,
                processData: false,
                url: url,
                async: true,
                cache: false,
                complete: function (xhr) {
                    xhr = null;
                },
                dataType: 'json',
                type: 'post',
            };
            $.extend(settings, options);
            $.ajax(settings);
            _this.remove();
            $('#' + form).append(input);
        });
        $(elem).click(function () {
            $('#' + form + ' input').click();
        });
    }
    exports('uploads', {});
});