<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('添加商品')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <th:block th:include="include :: summernote-css" />
    <link rel="stylesheet" href="">
    <style>
        .layui-form {
            padding: 20px;
        }
        .main_title, .main_type, .money, .scope_application, .sendType,.phoneNumber,.playMethod {
            margin-bottom: 20px;
        }

        .phoneNumber,.playMethod {
            display: none;
        }
        .labelName {
            display: inline-block;
            width: 100px;
            text-align: right;
        }
        input {
            border: 1px solid #ddd;
            border-radius: 4px;
            background: transparent;
            outline: none;
            padding-left: 5px;
            height: 30px;
        }
        .main_type .form-control.kv-fileinput-caption {
            height: 42px !important;
        }
        .main_title input {
            width: 200px;
        }
        .prompt {
            margin-left: 100px !important;
        }

        .main_type input, .sendType input,.playMethod input {
            margin-top: -2px;
            margin-right: 5px;
        }
        .main_type span, .sendType span, .playMethod span {
            margin-right: 12px;
            line-height: 28px;
        }
        .layui-form .money input {
            width: 60px;
        }
        .changeData .dataOne {
            margin-bottom: 20px;
        }
        .changeData .dataOne p {
            margin: 12px 0 0 20px;
            color: #ccc;
        }
        .changeData .dataOne input {
            width: 60px;
        }
        .main_bottom .describe, .main_bottom .sendTime {
            margin-bottom: 20px;
        }
        .describe,.main_type {
            display: flex;
        }
        .describe textarea,.phoneNumber textarea {
            width: 400px;
        }
        .sendTime {
            display: flex;
        }
        .sendTime input {
            margin-top: -6px;
            margin-right: 5px;
        }
        .bottom_btn {
            width: 25%;
            text-align: center;
        }
        select {
            border: 1px solid #ddd;
            border-radius: 4px;
            background: transparent;
            outline: none;
            height: 30px;
            width: 200px;
        }
        .search_ipt ul,.search_ipt li{
            padding: 0;
            margin: 0;
            font-style: normal;
            list-style: none;
        }
        .search_ipt ul {
            display: none;
            position: absolute;
            left: 0;
            top: 26px;
            padding: 5px 0;
            z-index: 899;
            min-width: 200px;
            border: 1px solid #eee;
            max-height: 300px;
            overflow-y: auto;
            background-color: #fff;
            border-radius: 2px;
            box-sizing: border-box;
            box-shadow: 1px 1px 4px rgb(0 0 0 / 8%);
        }
        .search_ipt li {
            background-color: #fff;
            cursor: pointer;
            padding-left: 10px!important;
            color: #999;
            padding: 0 10px;
            line-height: 36px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .search_ipt li:hover {
            background: #F6F6F6;
        }
        .search_ipt .layui-input {
            width: 200px;
        }
        .required {
            font-style: normal;
            color: red;
        }
        .ibox-content {
            border-style: none;
            border-width: 0px;
        }
        .main_type .file-footer-buttons .kv-file-remove {
            display: none !important;
        }
    </style>
</head>
<body>
<form id="form-user-add"  class="layui-form">
    
    <div class="main_type">
        <span class="labelName">商品类型：</span>
        <div class="layui-input-block" style="display: flex">
            <input type="radio" value="0" name="typeOne" checked><span>全场</span>
            <input type="radio" value="1" name="typeOne"><span>演出</span>
            <input type="radio" value="2" name="typeOne"><span>商品</span>
            <input type="radio" value="3" name="typeOne"><span>优先购</span>
        </div>
    </div>
    <div class="scope_application" id="scope_application">
        <span class="labelName"><i class="required">*</i>商品名称：</span>
        <div class="search_ipt" style="position: relative;display: inline;">
            <input type="text" id="searchIpt" autocomplete="off" class="layui-input" placeholder="全部">
            <ul id="dataList" style="position: absolute;"></ul>
        </div>
    </div>
    <div class="main_type">
        <span class="labelName"><i class="required">*</i>展示图：</span>
        
        <div class="layui-input-block" style="display: flex;flex-direction: column;">
            <img id="viewImg" src="" alt="" style="max-height:242px;">
            <div class="ibox-content">
                <div class="form-group">
                    <div class="file-loading">
                        <input id="fileinput" type="file" name="file" data-browse-on-zone-click="true" data-theme="fas">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="money">
        <span class="labelName"><i class="required">*</i>所需积分：</span><input type="text" id="integralNum" />  <span>请输入>=0的整数</span>
    </div>
    <div class="money">
        <span class="labelName"><i class="required">*</i>所需金额：</span><input type="text" id="moneyNum" value="0" disabled />  <span>请输入>=0的整数</span>
    </div>
    <div class="money">
        <span class="labelName"><i class="required">*</i>总库存：</span><input type="text" id="inventory" />
    </div>
    <div class="sendType">
        <div style="display: flex;align-items: center;">
            <span class="labelName"><i class="required">*</i>每人限兑次数：</span>
            <div class="layui-input-block" style="display: flex">
                <input type="radio" value="0" name="sendType" checked><span>不限</span>
                <input type="radio" value="1" name="sendType"><span>每人限兑</span>
                <input id="linit" type="text" style="width: 50px;"><span>次</span>
            </div>
        </div>
    </div>
    <div class="main_bottom">
        <div class="describe">
                <span class="labelName">
                    <i class="required">*</i>商品详情：
                </span>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="ibox float-e-margins">
                            <!-- <div class="ibox-title">
                                <h5>Summernote 富文本编辑器</h5>
                            </div> -->
                            <div class="ibox-content no-padding">
                                <div class="summernote" id="summernote">
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <!-- <textarea id="goodsDetail" class="form-control" rows="4"></textarea> -->
        </div>
        <div class="describe">
                <span class="labelName">
                    <i class="required">*</i>注意事项：
                </span>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="ibox float-e-margins">
                            <!-- <div class="ibox-title">
                                <h5>Summernote 富文本编辑器</h5>
                            </div> -->
                            <div class="ibox-content no-padding">
                                <div class="summernote" id="summernoteNotice">
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
        </div>
        <div class="sendTime">
            <span class="labelName"><i class="required">*</i>上架时间：</span>
            <div class="layui-input-block" style="display: flex">
                <input type="radio" name="sex" value="1" title="立即" checked><span>不限</span>
                <span style="margin-right:12px;" id="iptModal"><p style="display:flex"><input type="radio" name="sex" value="2" title="预约" style="margin-left: 12px;">选择时间</p></span>
            </div>
            <input type="text" class="layui-input" id="startTime" placeholder="请选择起始时间">
            <span>~</span>
            <input type="text" class="layui-input" id="endTime" placeholder="请选择结束时间" style="margin-left: 6px;">
        </div>
        <div class="bottom_btn">
            <!-- <button type="button" class="layui-btn btn btn-primary" lay-filter="formDemo" onclick="create()">创建代金券</button> -->
            <button type="button" class="btn btn-primary" onclick="create()">确定</button>
        </div>
    </div>
</form>
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: bootstrap-suggest-js"/>
<th:block th:include="include :: bootstrap-fileinput-js" />
<th:block th:include="include :: summernote-js" />
</body>
<script th:inline="javascript">
    var phpMallUrl = [[${phpMallUrl}]]; // https://devmall.zhengzai.tv/admin/goodListForQuick?title=
    var roadShowId = '[[${roadShowId}]]'.replaceAll("\"", "");
    var prefix = ctx + "candy/coupon/mgt";
    let typeOne = '0'; // 类别
    let sendType = '0'; // 发送类型
    let searchVal = ''; // 输入框内数据
    let searchData = []; // 搜索总数据
    let showId = ''; // 选中演出id
    let shelves = '1';
    let showPicture = ''; // 展示图片
    let limit = ''; // 限兑次数
    let itemId = ''; // 
    $(document).ready(function() {
        var $summernote = $('#summernote').summernote({
            height: 300,
            minHeight: null,
            maxHeight: null,
            focus: true,
            //调用图片上传
            callbacks: {
                onImageUpload: function (files) {
                    sendFile($summernote, files[0]);
                }
            }
        });
        var $summernoteNotice = $('#summernoteNotice').summernote({
            height: 300,
            minHeight: null,
            maxHeight: null,
            focus: true,
            //调用图片上传
            callbacks: {
                onImageUpload: function (files) {
                    sendFile($summernoteNotice, files[0]);
                }
            }
        });

        //ajax上传图片
        function sendFile($summernote, file) {
            var formData = new FormData();
            formData.append("file", file);
            $.ajax({
                url: "https://devplatform.zhengzai.tv/platform/basicServices/alOss/upload",//路径是你控制器中上传图片的方法，下面controller里面我会写到
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function (data) {
                    console.log(data, data.data.ossPath, '????')
                    $summernote.summernote('insertImage', 'https://img.zhengzai.tv/' + data.data.ossPath)
                }
            });
        }
    });

    $(function() {
        itemId = getUrlParms('id')
        function getUrlParms(name){
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if(r!=null)
                return unescape(r[2]);
                return null;
        }
        if (itemId) {
            let data = {
                itemId: itemId
            }
            promiseMethods(ctx + "stone/item/details",'get',data).then(res=>{
                console.log(res, '???')
                let data = res.data;
                if (res.code == 0) {
                    showPicture = data.img;
                    $("#viewImg").attr('src', data.img);
                    $("#searchIpt").val(data.targetTitle);
                    $("#integralNum").val(data.score);
                    $("#inventory").val(data.generalTotal);
                    // $("#goodsDetail").val(data.details);
                    $('#summernote').summernote('code', data.details)
                    $('.summernote').eq(1).summernote('code', data.notice)
                    // $("#attention").val(data.notice);
                    if (data.limitCount != 0) {
                        sendType = 1
                        $("input[name='sendType'][value='1']").attr("checked", "checked").siblings().removeAttr('checked');
                        $("#linit").val(data.limitCount)
                    }
                    if (data.status != 1) {
                        shelves = 2;
                        $("#endTime").val(data.endTime);
                        $("#startTime").val(data.startTime);
                        $("input[name='sex'][value='2']").attr("checked", "checked").siblings().removeAttr('checked');
                    }
                }
            })
        }
        $("#fileinput").fileinput({
            'theme': 'explorer-fas',
            'uploadUrl': "https://devplatform.zhengzai.tv/platform/basicServices/alOss/upload",
            "uploadExtraData": {
                "pathName" : "banner",
                "buckType" : 1
            },
            autoReplace: true,
            showCaption: false,
            showPreview: false,
            showRemove: false,
            showUpload: false,
            showCancel: false,
            showClose: false,
            autoReplace: true,
            dropZoneTitle: "请上传文件",
            maxFileCount: 1
        }).on("filebatchselected", function (event, files) {         //默认上传
            $(this).fileinput("upload");
        })
        .on("fileuploaded", function (event, data) {       //上传回调事件
            showPicture = 'https://img.zhengzai.tv/' + data.response.data.ossPath;
            $("#viewImg").attr('src', showPicture)
        })
        // $("#fileinput").on("fileuploaded", function (event, data, previewId, index) {
        //     showPicture = 'https://img.zhengzai.tv/' + data.response.data.ossPath;
        //     $("#viewImg").attr('src', showPicture)
        //     console.log(event, data, previewId, index)
        // });
    })
    function getMallList() {
        let data = {
            keyword: searchVal,
            busiType: typeOne,
            pageSize: 20,
            pageNum: 1
        }
        let str = '';
        promiseMethods(prefix + "/list",'post',data,'application/x-www-form-urlencoded').then(res=>{
            if (res.rows.length>0) {
                searchData = res.rows;
                searchData.forEach((item,index)=>{
                    str+= `<li class="selectData" onclick="selectOne('${item.couponId}', 'couponId')">${item.title}</li>`
                })
                $('#dataList').html(str);
            } else {
                $('#dataList').html('<li style="width:100%;text-align:center;color:#ccc;">--- 暂无数据 ---</li>');
            }
        })
    };
    function selectOne(id, name) {
        searchData.some( item => {
            if (item[name] == id) {
                return $("#searchIpt").val(item.title);
            }
        } )
        // $("#searchIpt").val(name);
        showId = id;
        console.log(showId, 'showId')
    };
    $("#searchIpt").focus(function(){
        getMallList()
        $('#dataList').show()
    });
    $("#searchIpt").blur(function(){
        setTimeout(() => {
            $('#dataList').hide() 
        }, 500);
    });
    $("#integralNum").blur(function() {
        let reg = /^[0-9]*[1-9][0-9]*$/;
        if (!reg.test($("#integralNum").val())) {
            $("#integralNum").val('')
        }
    })
    $("#moneyNum").blur(function() {
        let reg = /^[0-9]*[1-9][0-9]*$/;
        if (!reg.test($("#moneyNum").val())) {
            $("#moneyNum").val('')
        }
    })
    $("#searchIpt").keyup(function(){
        searchVal = $("#searchIpt").val()
        getMallList()
    });
    
    $("input[name=typeOne]").change(function(e){
        typeOne = e.target.value;
    });
    $("input[name=sendType]").change(function(e){
        sendType = e.target.value;
        if (sendType == 1) {
            limit = $('#limit').val();
        } else {
            limit = 0;
        }
    });
    $("input[name=sex]").change(function(e){
        shelves = e.target.value;
    });
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#startTime', //指定元素
            type: 'datetime'
        });
        laydate.render({
            elem: '#endTime', //指定元素
            type: 'datetime'
        });
    });
    
    function create() {
        console.log($('#searchIpt').val(),showPicture,$('#integralNum').val(),$('#moneyNum').val(),$('#inventory').val(),$('#summernote').summernote('code'),$('#summernoteNotice').summernote('code'))
        if (!$('#searchIpt').val() || !showPicture || !$('#integralNum').val() || !$('#moneyNum').val() || !$('#inventory').val() || !$('#summernote').summernote('code') || !$('.summernote').eq(1).summernote('code')) {
            return layer.msg('请将必填项输入完整～！');
        }
        if (sendType == 1) {
            if (!$("#linit").val()) {
                return layer.msg('请填写限兑次数！');
            } else {
                limit = $("#linit").val()
            }
        }
        let startTime = '';
        let endTime = '';
        if (shelves != 1) {
            if (!$("#startTime").val()) {
                return layer.msg('请选择起始时间！');
            } else if (!$("#endTime").val()) {
                return layer.msg('请选择结束时间！');
            } else {
                startTime = $("#startTime").val();
                endTime = $("#endTime").val();
            }
        }
        let data = {
            details: $('#summernote').summernote('code'), // 商品详情
            endTime: $.common.dateFormat(endTime, 'yyyy-MM-dd HH:mm:ss'), // 下架时间（status = 2 必传）
            generalTotal: Number($("#inventory").val()), // 总库存
            img: showPicture, // 展示图
            itemId: itemId, // 物品积分id
            limitCount: Number(limit), // 限兑次数
            notice: $('.summernote').eq(1).summernote('code'), // 注意事项
            score: $("#integralNum").val(), // 所需积分
            startTime: $.common.dateFormat(startTime, 'yyyy-MM-dd HH:mm:ss'), // 上架时间status = 2 必传）
            status: Number(shelves), // 上架状态[1-不限|2-定时|7-下线]
            targetId: showId, // 目标物品id
            targetTitle: $('#searchIpt').val() // 目标物品标题
        }
        if (!itemId) {
            delete data.itemId
        }
        if (shelves == 1) {
            delete data.startTime
            delete data.endTime
        }
        promiseMethods(ctx+'stone/item','post',data).then(res=>{
            layer.msg('' + res);
            if (res.code != undefined && res.code != web_status.SUCCESS) {
                $.modal.alertWarning(res.msg);
                return [];
            } else if (res.code == web_status.SUCCESS) {
                $.operate.successTabCallback(res);
                closeItem();
            }
        })
    }
    function promiseMethods(url,type,data,contentType) {
        return new Promise((resolve,reject)=>{
            $.ajax({
                url,
                type,
                data,
                contentType,
                success:function(res) {
                    resolve(res);
                }
            })
        })
    }
</script>
</html>
