<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加问题</title>
    <%@include file="/views/common.jsp" %>
    <link rel="stylesheet" href="${path}/static/css/formSelects-v4.css">
    <style>
        .layui-input, .layui-input-inline {
            width: 370px
        }

        .form .layui-form-label {
            windth: 100px;
        }

        .layui-upload-img {
            height: 200px;
            width: 200px
        }
    </style>
</head>
<body>
<div style="padding: 20px; background-color: #F2F2F2;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md3"></div>
        <div class="layui-col-md6">
            <div class="layui-card"
                 style="border-radius: 20px; border: 2px solid buttonface; box-shadow: 5px 5px 5px #F2F2F2 inset;">
                <div class="layui-card-body">
                    <div class="layui-input-block layui-form" lay-filter="addUser"
                         style="margin-top: 30px">
                        <form class="layui-form form">
                            <div class="layui-form-item">
                                <label class="layui-form-label">问题页面</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="product" lay-verify="product"
                                           placeholder="发现问题或不足的菜单" class="layui-input" id="product">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">情况说明</label>
                                <div class="layui-input-inline">
										<textarea rows="8" cols="50" name="bugRemark"
                                                  placeholder="说明" id="bugRemark"></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">上传图片</label>
                                <div class="layui-input-inline">
                                    <input type="file" id="uploaderImage"/>
                                    <input name="images" type="hidden" id="images"/>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label" style="color: #FF5722">点击图片可以删除</label>
                                <div class="layui-input-inline" id="preview">

                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit="" lay-filter="enadd">提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div style="height: 50px"></div>
        </div>
        <div class="layui-col-md3"></div>
    </div>
</div>
<script src="${path}/js/alioss.js"></script>
<script>
    function delImage(index) {
        layer.confirm('是否确认删除该图片', {
            btn: ['确定', '关闭'] //按钮
        }, function (layIndex) {
            let textImage = $("#images").val();
            let list = textImage == "" ? [] : textImage.split(",");
            list.splice(index, 1);
            $("#images").val(list.join(","));
            previewImage($("#images").val());
            layer.close(layIndex);
        }, function () {
        });

    }

    $("#images").val("");
    $("#preview").empty();
    const client = new OSS({
        // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-hangzhou",
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        accessKeyId: "LTAI5tE7wuNkeT9jZ42bQnyr",
        accessKeySecret: "NnutvWhKl4HbQFSad3HosYbCkEkbjN",
        // 填写存储空间名称。
        bucket: "ltcloudfile",
        endpoint: "https://oss-cn-hangzhou.aliyuncs.com",
    });

    function previewImage(textImage) {
        let textImageList = textImage == "" ? [] : textImage.split(",");
        let html = "";
        textImageList.forEach((item, index) => {
            if (item != "") {
                html += "<img src='" + item + "' class='layui-upload-img' style='width: 50px;height: 50px;margin-right: 5px;' onclick='delImage(\"" + index + "\")'/>";
            }
        })
        $("#preview").empty().append(html);

    }


    async function putObject(file) {
        try {
            let fileDir = dateFtt("yyyyMMdd", new Date())
            let name = "priceImages/" + fileDir + "/" + guid() + getSuff(file.name);
            // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
            // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
            // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
            const options = {
                headers: {"Content-Type": "text/plain"},
            };
            const result = await client.put(name, file, options);
            let textImage = $("#images").val();
            let list = textImage == "" ? [] : textImage.split(",");
            list.push(result.url);
            $("#images").val(list.join(","));
            previewImage($("#images").val());
        } catch (e) {
            console.log(e);
        }
    }

    document.getElementById('uploaderImage').addEventListener('change', function (e) {
        const file = e.target?.files[0];
        putObject(file);

        document.getElementById('uploaderImage').value = "";
    });

    function dateFtt(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,                 //月份
            "d+": date.getDate(),                    //日
            "h+": date.getHours(),                   //小时
            "m+": date.getMinutes(),                 //分
            "s+": date.getSeconds(),                 //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

        }
        return fmt;

    }

    function getSuff(name) {
        return name.substring(name.lastIndexOf("."));
    }

    function guid() {
        return "xxxxxxxx-xxxx-4xxx-yxxx".replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }

    layui.use(['form', 'layer', 'upload'], function () {
        var $ = layui.$,
            form = layui.form,
            layer = layui.layer,
            upload = layui.upload;


        //监听提交
        form.on('submit(enadd)', function (data) {
            let fromData = $(data.form).serialize()
            let data_list = fromData.split("&");
            for (let i = 0; i < data_list.length; i++) {
                let data_list_item = data_list[i].split("=");
                if (data_list_item[0] == "product" && data_list_item[1] == "") {
                    layer.msg('请填写问题页面', {icon: 6, offset: "auto", time: 2000});//提示框
                    return false
                }
                if (data_list_item[0] == "bugRemark" && data_list_item[1] == "") {
                    layer.msg('请填写问题详情', {icon: 6, offset: "auto", time: 2000});//提示框
                    return false
                }
                if (data_list_item[0] == "images" && data_list_item[1] == "") {
                    layer.msg('请上传图片', {icon: 6, offset: "auto", time: 2000});//提示框
                    return false
                }
            }
            $.ajax({
                url: '${path}/addBug',
                dataType: 'json',
                data: fromData,
                type: 'post',
                success: function (data) {
                    if (data.code == 200) {
                        layer.msg('提交成功，谢谢您的反馈！', {
                            icon: 6,
                            offset: "auto",
                            time: 2000
                        });//提示框
                        $("#product").val("")
                        $("#bugRemark").val("")
                        $("#images").val("");
                        $("#preview").empty();
                        form.render()
                    } else {
                        layer.msg('提交出错了！', {
                            icon: 5,
                            offset: "auto",
                            time: 2000
                        });//提示框
                    }
                }
            })
            return false;
        });

    })
</script>
</body>
</html>