<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('模板新增')"/>
    <th:block th:include="include :: layout-latest-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>

    <style>
        body {
            padding: 0 !important;
        }

        .pane1 {
            padding-bottom: 0;
        }

        .pane2 {
            padding-top: 0;
        }

        .template-div {
            display: inline-block;
            margin-right: 10px;
        }

        .template-body {
            padding: 10px;
            border-radius: 5px 5px 0 0;
            border: 1px solid #1c84c6;
        }

        .template-footer {
            background-color: #1c84c6;
            color: white;
            padding: 5px;
            border-radius: 0 0 5px 5px;
            border: 1px solid #1c84c6;
        }

        .floor-text {
            display: flex;
            align-items: baseline;
            flex-wrap: wrap;
            position: relative;
            top: 2px;
        }

        .floor-input {
            width: 50px;
        }

        .dropdown-btn {
            height: 31px;
        }

        .oper-banner {
            display: flex;
            justify-content: space-between;
            padding: 15px;
        }

        .oper-banner-start {
            display: flex;
            align-items: center;
        }

        .oper-banner-end {
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }

        .yuan-symbol {
            color: red;
            font-size: large;
        }

        .multiply-symbol {
            font-size: large;
            text-align: center;
        }

        .goodsNumList {
            padding: 5px 8px 14px 5px;
            min-height: 40px;
            border: 1px solid #dcdfe6;
            box-sizing: border-box;
            border-radius: 4px;
        }

        .oneGoodsNumList {
            padding: 5px 8px 5px 5px;
            min-height: 40px;
            border: 1px solid #dcdfe6;
            box-sizing: border-box;
            border-radius: 4px;
        }

        .goodsNum {
            margin: 2px 0;
            height: 24px;
        }

        #categoryCxSelect {
            z-index: 101
        }

        #categoryCxSelect .eo-cascader-menu:nth-child(-n+3) .has-child label {
            display: none;
        }
    </style>

    <th:block th:include="include :: datetimepicker-css" />
    <link rel="stylesheet" href="../../../static/css/cascader.css" th:href="@{/css/cascader.css}">
</head>
<body class="gray-bg">
    <form id="addTemplateForm">
    <div class="pane1 wrapper wrapper-content animated fadeIn">
        <div class="ibox float-e-margins">
            <div class="ibox-title">
                商品信息
            </div>
            <div class="ibox-content">
                <div class="template-grid" id="template-grid">
                    <div class="template-div">
                        <div class="template-body">MR1234</div>
                        <div class="template-footer">快速发布</div>
                    </div>
                </div>

                <div class="form-horizontal m">
                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">服务类目：</label>
                        <div class="col-sm-6" style="padding-right: 0">
                            <div id="categoryCxSelect" class="cascader-wrap">
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="category1 form-control m-b" name="category1" required></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="category2 form-control m-b" name="category2" required></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="category3 form-control m-b" name="category3" required></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="category4 form-control m-b" name="category4" required></select>-->
<!--                                </div>-->
                            </div>
                        </div>
                        <div class="col-sm-1 multiply-symbol">×</div>
                        <div id="goodsNumList" class="col-sm-1 oneGoodsNumList">
                            <input type="number" name="goodsNum" class="form-control" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">服务品牌：</label>
                        <div class="col-sm-8 row">
                            <div class="col-sm-3">
                                <input type="text" name="goodsBrand" class="form-control" placeholder="品牌" required>
                            </div>
                            <div class="col-sm-3">
                                <input type="text" name="goodsSpecification" class="form-control" placeholder="规格（非必填）">
                            </div>
                            <div class="col-sm-3">
                                <select class="form-control">
                                    <option value="后台订单">后台订单</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">服务时间：</label>
                        <div class="col-sm-4">
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input type="text" class="form-control" id="servDate" name="servDate" required readonly style="background: white;">
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <select class="form-control" name="servTime" required>
                                <option value="08:00-10:00">08:00-10:00</option>
                                <option value="10:00-12:00">10:00-12:00</option>
                                <option value="12:00-14:00">12:00-14:00</option>
                                <option value="14:00-16:00">14:00-16:00</option>
                                <option value="16:00-18:00">16:00-18:00</option>
                                <option value="18:00-20:00">18:00-20:00</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">视频链接：</label>
                        <div class="col-sm-8">
                            <input type="text" name="videoUrl" class="form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">图片上传：</label>
                        <div class="col-sm-8">
                            <input type="text" name="imageUrl" value="" hidden>
                            <input type="file" name="imageUrlStr" id="imageUrlStr" multiple class="file" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">服务地址：</label>
                        <div class="col-sm-6">
                            <div id="areaCxSelect" class="cascader-wrap">
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="province form-control m-b" name="province" id="province" required onchange="selectRegion('province', 'city')"></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="city form-control m-b" name="city" id="city" required onchange="selectRegion('city', 'district')"></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="district form-control m-b" name="district" id="district" required onchange="selectRegion('district', 'street')"></select>-->
<!--                                </div>-->
<!--                                <div class="col-sm-3">-->
<!--                                    <select class="street form-control m-b" name="streetId" id="streetId" required></select>-->
<!--                                </div>-->
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label"></label>
                        <div class="col-sm-8">
                            <input type="text" name="fullAddress" class="form-control" required placeholder="请输入详细的门牌号">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">客户姓名：</label>
                        <div class="col-sm-4">
                            <input type="text" name="customerName" class="form-control" placeholder="请输入客户姓名" required>
                        </div>
                        <div class="col-sm-4">
                            <input type="text" name="customerPhone" class="form-control" placeholder="请输入客户手机号码" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">下单模式：</label>
                        <div class="col-sm-8 row" id="orderModeRadioGroup">
                            <div class="col-sm-2">
                                <label><input type="radio" value="02" name="orderMode" checked > 带价发布</label>
                            </div>
                            <div class="col-sm-2">
                                <label><input type="radio" value="01" name="orderMode"> 一票价发布</label>
                            </div>
                            <div class="col-sm-2">
                                <label><input type="radio" value="03" name="orderMode"> 回收模式</label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label is-required">发布价格：</label>
                        <div class="col-sm-2">
                            <input type="text" name="price" class="form-control" required placeholder="发布价格（佣金）">
                        </div>
                        <div class="col-sm-2">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" value="1" name="isOnSiteQuote" checked>上门报价</label>
                            </div>
                        </div>
                        <div class="col-sm-2">
                            <input type="text" name="agencyFund" class="form-control" placeholder="上门代收款额（非必填）">
                        </div>
                        <div class="col-sm-2">
                            <div class="input-group">
                                <input type="text" name="informationFee" class="form-control" placeholder="信息费">
                                <div class="input-group-btn">
                                    <button data-toggle="dropdown" class="btn btn-white dropdown-toggle dropdown-btn" type="button" id="informationFeeUnit">单位<span class="caret"></span></button>
                                    <ul class="dropdown-menu pull-right">
                                        <li onclick="changeInformationFeeUnit('%')"><a>%</a></li>
                                        <li onclick="changeInformationFeeUnit('元')"><a>元</a></li>
                                    </ul>
<!--                                    <select class="form-control dropdown-menu pull-right" name="informationFeeUnit">-->
<!--                                        <option value="%">%</option>-->
<!--                                        <option value="元">元</option>-->
<!--                                    </select>-->
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">奖励金：</label>
                        <div class="col-sm-4">
                            <input type="text" name="bonus" class="form-control" placeholder="准时服务奖励金">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">备注说明：</label>
                        <div class="col-sm-8">
                            <textarea class="form-control" name="remark" placeholder="请输入备注说明（不超过512个字符）"></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">物流单号：</label>
                        <div class="col-sm-4">
                            <input type="text" name="logisticsCode" class="form-control" placeholder="请输入物流单号">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label"></label>
                        <div class="col-sm-8">
                            <label class="checkbox-inline">
                                <input type="checkbox" value="1" name="needWagon">需提供货拉拉或58速运类业务，本次服务需拉货</label>
                            <div class="row">
                                <div class="col-sm-2">
                                    <label class="checkbox-inline">
                                        <input type="checkbox" value="1" name="needCarry">需要搬货</label>
                                </div>
                                <div class="col-sm-8">
                                    <div class="floor-text">
                                        <div>需提供可搬货人员，楼层</div>
                                        <div class="floor-input"><input type="number" name="floor" class="form-control"></div>
                                        <div>层（费用另行计算）；</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="pane2 wrapper wrapper-content animated fadeIn">
        <div class="ibox float-e-margins">
            <div class="oper-banner">
                <div class="oper-banner-start col-sm-5">
                    <span>合计金额：</span>
                    <span class="yuan-symbol">¥</span>
                    <span class="yuan-symbol" id="totalMoney">0</span>
                </div>
                <div class="oper-banner-end col-sm-5" >
                    <div class="m-r">
                        <div class="checkbox">
                            <a href="#" shiro:hasPermission="consult:order:add"><input id="consultOrder" type="checkbox" value="02" name="consultOrder" onclick="changeConsultOrder(this)" >合约订单</a>
                        </div>
                    </div>
                    <div class="m-r">
                        <div class="checkbox">
                            <label><input id="payOnDoorMode" type="checkbox" value="02" name="payMode" onclick="changePayOnDoorMode(this)">上门到付/保外单</label>
                        </div>
                    </div>
                    <div class="m-r">
                        <button type="button" class="btn btn-w-m btn-success" onclick="submitOrder()">提交订单</button>
                    </div>
                    <div>
                        <button type="button" class="btn btn-w-m btn-success" onclick="addTemplate()">保存模版</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>

    <th:block th:include="include :: footer"/>
    <th:block th:include="include :: layout-latest-js"/>
    <th:block th:include="include :: jquery-cxselect-js" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <script th:src="@{/js/plugins/miniCascader/cascader.js}"></script>
    <script th:src="@{/data/four-level-area.js}"></script>
    <script type="text/javascript">
    // 级联下拉
    let categoryCascader = new eo_cascader([], {
        elementID: 'categoryCxSelect',
        multiple: true, // 是否多选
        separator: '-', // 分割符 山西-太原-小店区 || 山西/太原/小店区
        clearable: true, // 是否可一键删除已选
        value: 'goodsCategoryId',
        label: 'goodsCategoryName',
        children: 'child',
        checkedCallback: checkedCategoryCallback
    });
    let areaCascader = new eo_cascader(fourLevelAreaList, {
        elementID: 'areaCxSelect',
        multiple: false, // 是否多选
        separator: '-', // 分割符 山西-太原-小店区 || 山西/太原/小店区
        clearable: false, // 是否可一键删除已选
        value: 'areaId',
        label: 'areaName',
        children: 'child'
    });
    $(function(){
        var icon = "<i class='fa fa-times-circle'></i> ";
        // $("#addTemplateForm").validate({
        //     rules: {
        //     },
        //     messages: {
        //     }
        // });

        $.ajax({
            type: "POST",
            dataType:"json",
            url: ctx + "goods/deptcategory/app/list",
            data: JSON.stringify({deptId: 101, goodsCategoryId: 1}),
            contentType: 'application/json',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
<!--                    $('#categoryCxSelect').cxSelect({-->
<!--                        selects: ['category1', 'category2', 'category3', 'category4'],-->
<!--                        jsonValue: 'deptGoodsCategoryId',-->
<!--                        jsonName: 'goodsCategoryName',-->
<!--                        jsonSub: 'child',-->
<!--                        data: result.data-->
<!--                    });-->
                    categoryCascader = new eo_cascader(result.data, {
                        elementID: 'categoryCxSelect',
                        multiple: true, // 是否多选
                        checkedValue: null,
                        separator: '-', // 分割符 山西-太原-小店区 || 山西/太原/小店区
                        clearable: true, // 是否可一键删除已选
                        value: 'deptGoodsCategoryId',
                        label: 'goodsCategoryName',
                        children: 'child',
                        checkedCallback: checkedCategoryCallback
                    })
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

<!--        $.ajax({-->
<!--            type: "POST",-->
<!--            dataType:"json",-->
<!--            url: ctx + "system/area/list",-->
<!--            success: function (result) {-->
<!--                if (result.code == web_status.SUCCESS) {-->
<!--                    $('#areaCxSelect').cxSelect({-->
<!--                        selects: ['province', 'city', 'district', 'street'],-->
<!--                        jsonValue: 'areaId',-->
<!--                        jsonName: 'areaName',-->
<!--                        data: result.data-->
<!--                    });-->
<!--                } else {-->
<!--                    $.modal.msgError("数据加载错误，请重试！")-->
<!--                }-->
<!--            }-->
<!--        })-->

        $("#servDate").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $('#template-grid').html('');
        $.ajax({
            type: "GET",
            dataType:"json",
            url: ctx + "order/template/selectByUserId",
            success: function (result) {
                if (result != null) {
                    result.forEach(function(item) {
                        $('#template-grid').append('<div class="template-div">' +
                            '                        <div class="template-body">模版' + item.id + '</div>' +
                            '                        <div class="template-footer">快速发布</div>' +
                            '                    </div>');
                    });
                }
            }
        })

        // 多图上传
        // $("#multipleFile").fileinput({
        //     uploadUrl: ctx + 'common/uploads',
        //     uploadAsync: false
        // }).on('filebatchuploadsuccess', function (event, data, previewId, index) {
        //     var rsp = data.response;
        //     log.info("return urls：" + rsp.urls)
        //     log.info("reutrn fileNames：" + rsp.fileNames)
        // }).on('fileremoved', function (event, id, index) {
        //     this.$("input[name='" + event.currentTarget.id + "']").val('')
        // })
    });

    function checkedCategoryCallback() {
        let checkedIdArr = categoryCascader.getCheckedByID();
        if (checkedIdArr && checkedIdArr.length > 0) {
            $('#goodsNumList').html(null);
            $('#goodsNumList').removeClass('oneGoodsNumList');
            $('#goodsNumList').addClass('goodsNumList');
            checkedIdArr.forEach(function(id, index) {
                $('#goodsNumList').append('<input type="number" name="goodsNum' + id + '" class="form-control goodsNum" required>');
            });
        } else {
            $('#goodsNumList').removeClass('goodsNumList');
            $('#goodsNumList').addClass('oneGoodsNumList');
            $('#goodsNumList').html('<input type="number" name="goodsNum" class="form-control" required>');
        }
    }

    function changeInformationFeeUnit(unit) {
        this.$('#informationFeeUnit').html(unit + '<span class="caret"></span>');
    }

<!--    function selectRegion(regionLevelName, nextRegionLevelName) {-->
<!--        var regionId = $("#" + regionLevelName).val();-->
<!--        if ($.common.isEmpty(regionId)) {-->
<!--            return;-->
<!--        }-->

<!--        //Ajax调用处理-->
<!--        $.ajax({-->
<!--            type: "POST",-->
<!--            dataType:"json",-->
<!--            url: ctx + "system/area/list",-->
<!--            data: {parentCode: regionId},-->
<!--            success: function (result) {-->
<!--                if (result.code == web_status.SUCCESS) {-->
<!--                    $('#areaCxSelect').cxSelect({-->
<!--                        selects: [nextRegionLevelName],-->
<!--                        jsonValue: 'areaId',-->
<!--                        jsonName: 'areaName',-->
<!--                        data: result.data-->
<!--                    });-->
<!--                } else {-->
<!--                    $.modal.msgError("数据加载错误，请重试！")-->
<!--                }-->
<!--            }-->
<!--        })-->
<!--    }-->


    function changeConsultOrder(e){
        if ($(e).is(':checked')) {
            $('#consultOrder').prop("value", '01');
        } else {
            $('#consultOrder').prop("value", '02');
        }
    }

    function changePayOnDoorMode(e) {
        if ($(e).is(':checked')) {
            $('#payOnDoorMode').prop("value", '01');
        } else {
            $('#payOnDoorMode').prop("value", '02');
        }
    }

    function validSpecialComponent() {
        // 类目
        let categoryIds = categoryCascader.getCheckedByID();
        if (!categoryIds || categoryIds.length === 0) {
            $.modal.msgError("服务类目不能为空")
            return false;
        }

        // 图片是否上传
        if (!$('input[name=imageUrl]').val()) {
            $.modal.msgError("图片未上传")
            return false;
        }

        // 地区
        let checkedAreaPathList = areaCascader.getCheckedPaths();
        if (!checkedAreaPathList || checkedAreaPathList.length === 0) {
            $.modal.msgError("服务地址不能为空")
            return false;
        }

        // 下单模式
        if (!$('#orderModeRadioGroup input[name=orderMode]').is(':checked')) {
            $.modal.msgError("请录入完整必填信息")
            return false;
        }

        return true;
    }

    function translateForm(data) {
        var params = {};
        data.forEach(function (item){
            params[item.name] = item.value;
        });

        let categoryIds = categoryCascader.getCheckedByID();
        let orderGoodsStandards = [];
        categoryIds.forEach(function (item){
            orderGoodsStandards.push({
                deptCategoryId: item,
                goodsStandardNum: $(".goodsNum[name=goodsNum" + item + "]").val()
            });
        });
        params.orderGoodsStandards = orderGoodsStandards;
        params.categoryId1 = categoryCascader.getCheckedPaths()[0][0];
        params.categoryId2 = categoryCascader.getCheckedPaths()[0][1];
        params.categoryId3 = categoryCascader.getCheckedPaths()[0][2];
        params.provinceId = areaCascader.getCheckedPaths()[0][0];
        params.cityId = areaCascader.getCheckedPaths()[0][1];
        params.districtId = areaCascader.getCheckedPaths()[0][2];
        params.streetId = areaCascader.getCheckedPaths()[0][3];
        params.payMode = $('#payOnDoorMode').val();
        params.consultMode = $('#consultOrder').val();

        return params;
    }

    // 营业执照上传
    $('#imageUrlStr').fileinput({
        language: 'zh',     //设置语言
        dropZoneEnabled: false,      //是否显示拖拽区域
        showPreview: false,
        uploadExtraData: {
            "name": "imageUrlStr"
        },
        dropZoneTitle: "可以将图片拖放到这里",    //拖拽区域显示文字
        uploadUrl: ctx + 'tool/qiniu/dept/upload',  //上传路径
        allowedFileExtensions: ['jpg', 'png', 'gif', 'jpeg'],   //指定上传文件类型
        maxFileSize: 0,
        maxFileSize: 2048,   //上传文件最大值，单位kb
        uploadAsync: true,  //异步上传
        maxFileCount: 2    //上传文件最大个数。
    }).on("fileuploaded", function(event,data) { //异步上传成功后回调
        if(data.response.code === 0){
            $("input[name='imageUrl']").val(data.response.url)
        }else {
            alert("上传失败!");
        }
    });

    function submitOrder() {
        if (!validSpecialComponent()) return;
        if ($.validate.form()) {
            var data = $("#addTemplateForm").serializeArray();
            var params= translateForm(data);

            $.ajax({
                type: "POST",
                dataType:"json",
                url: ctx + "order/sys/order",
                data: JSON.stringify(params),
                contentType: 'application/json',
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        layer.open({
                            type: 0,
                            area: ['250px', '180px'],
                            fix: false,
                            //不固定
                            maxmin: true,
                            shade: 0.3,
                            title: '系统通知',
                            content: '发单成功，是否前往发单管理？',
                            btn: ['确定','继续下单'],
                            // 弹层外区域关闭
                            shadeClose: true,
                            yes: function(index) {
                                $.modal.parentTab('发单管理', 'order/master/pc');
                            }
                        });
                    } else {
                        $.modal.msgError(result.msg)
                    }
                }
            })
        } else {
            $.modal.msgError("请录入完整必填信息")
        }
    }

    function addTemplate() {
        if (!validSpecialComponent()) return;
        if ($.validate.form()) {
            var data = $("#addTemplateForm").serializeArray();
            var params= translateForm(data);

            $.ajax({
                type: "POST",
                dataType:"json",
                url: ctx + "order/template/insert",
                data: JSON.stringify(params),
                contentType: 'application/json',
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("提交成功")
                    } else {
                        $.modal.msgError(result.msg)
                    }
                }
            })
        }
    }
    </script>
</body>
</html>
