<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>供应链仓下单</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="decorator" content="base"/>
    <link rel="stylesheet" type="text/css" href="${ctxPlugin}/static/css/reset.css"/>
    <link rel="stylesheet" type="text/css" href="${ctxPlugin}/lib/font/iconfont.css"/>
    <style>
        .layui-table-tool-temp {
            padding-right: 0
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <form class="layui-form layui-card" id="searchForm">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <a href="${ctx}/material/order/supplyOrder">
                    <li class="layui-this">供应链仓下单</li>
                </a>
                <button class="layui-btn f-r mt-10 mr-15 pl-10 pr-10 " type="reset">
                    <i class="layui-icon fs-12">&#xe9aa;</i>
                    重置
                </button>
                <button type="button" class="layui-btn f-r mt-10 mr-15 pl-10 pr-10" id="searchBtn" lay-submit
                        lay-filter="LAY-user-back-search">
                    <i class="layui-icon fs-12">&#xe615;</i>
                    查询
                </button>
            </ul>
        </div>
        <div class="layui-card-body layuiadmin-card-header-auto">
            <input type="hidden" name="supplyOrder" value="1"/>
            <input type="hidden" name="type" value="2"/>
            <div class="layui-form-item">
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">订单编号：</label>
                    <div class="layui-input-block">
                        <input type="text" name="number" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">订单状态：</label>
                    <div class="layui-input-block">
                        <select name="status">
                            <option value="">请选择</option>
                            <option value="1">待发货</option>
                            <option value="2">待入库</option>
                            <option value="3">已撤销</option>
                            <option value="4">仓库打回</option>
                            <option value="5">待审核</option>
                            <option value="6">审核驳回</option>
                            <option value="7">已完成</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">发货方式：</label>
                    <div class="layui-input-block">
                        <select name="deliverMethodId" lay-search>
                            <option value="">请选择</option>
                            <c:forEach items="${deliverMethods}" var="method">
                                <option value="${method.columns.id}">${method.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">物流单号：</label>
                    <div class="layui-input-block">
                        <input type="text" name="expressNo" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">关联单号：</label>
                    <div class="layui-input-block">
                        <input type="text" name="relateNo" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">下单人：</label>
                    <div class="layui-input-block">
                        <input type="text" name="placeName" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">订单备注：</label>
                    <div class="layui-input-block">
                        <input type="text" name="remarks" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">发货备注：</label>
                    <div class="layui-input-block">
                        <input type="text" name="deliverRemark" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">联系方式：</label>
                    <div class="layui-input-block">
                        <input type="text" name="mobile" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">收货地址：</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">供应商：</label>
                    <div class="layui-input-block">
                        <select name="deliverId" lay-search>
                            <option value="">请选择</option>
                            <c:forEach items="${supplyList}" var="supply">
                                <option value="${supply.columns.id}">${supply.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-col-lg4 layui-col-sm6">
                    <label class="layui-form-label">下单时间：</label>
                    <div class="layui-input-block">
                        <div class="layui-col-xs5">
                            <input type="text" name="createTimeMin" class="layui-input" id="repairTime"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="createTimeMax" class="layui-input" id="endTime"
                                   placeholder="结束日期">
                        </div>
                    </div>
                </div>
                <div class="layui-col-lg4 layui-col-sm6">
                    <label class="layui-form-label">发货时间：</label>
                    <div class="layui-input-block">
                        <div class="layui-col-xs5">
                            <input type="text" name="deliverTimeMin" class="layui-input" id="orderTimeMin"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="deliverTimeMax" class="layui-input" id="orderTimeMax"
                                   placeholder="结束日期">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="layui-card">
        <div class="layui-card-body">
            <table class="layui-hide" lay-skin="row" id="test" lay-filter="test"></table>
        </div>
    </div>
</div>
<div class="hide pd-10" style="padding: 10px" id="ideaDiv">
    <label class="layui-form-label"><span class="red">*</span>撤销原因：</label>
    <div class="layui-input-block ">
        <textarea id="idea" class="idea-text f-l layui-textarea"></textarea>
    </div>
</div>

<div class="hide pd-10 layui-form" style="padding: 10px" id="changeDiv">
    <div class="layui-form-item">
        <label class="layui-form-label w-130"><i class="red">*</i>出库仓库：</label>
        <div class="layui-input-block w-200">
            <select name="outWarehouseId" lay-verify="required">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label w-130"><i class="red">*</i>改派原因：</label>
        <div class="layui-input-block w-200">
            <textarea name="changeReason" class="layui-textarea"></textarea>
        </div>
    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <sfTags:pagePermission authFlag='DDGL_GYSDD_GYSDD_XZ_B' html='<button class="layui-btn layui-btn-sm" lay-event="add"><i
            class="layui-icon layui-icon-add-1"></i>新增
    </button>'/>
    <sfTags:pagePermission authFlag='DDGL_GYSDD_GYSDD_GP_B' html='<button class="layui-btn layui-btn-sm" lay-event="change"><i
            class="layui-icon layui-icon-edit"></i>改派
    </button>'/>
    <sfTags:pagePermission authFlag='DDGL_GYSDD_GYSDD_SC_B' html='<button class="layui-btn layui-btn-sm" lay-event="delete"><i
            class="layui-icon layui-icon-delete"></i>删除
    </button>'/>
    <sfTags:pagePermission authFlag='DDGL_GYSDD_GYSDD_DC_B' html='<button class="layui-btn layui-btn-sm" lay-event="export"><i
            class="layui-icon layui-icon-export"></i>导出
    </button>'/>
</script>
<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/xm-select.js"></script>
<script>
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'tableExt', 'jquery', 'layer', 'laypage', 'laydate', 'form'], function () {
        $ = layui.$;
        tableExt = layui.tableExt;
        layer = layui.layer;
        laypage = layui.laypage;
        laydate = layui.laydate;
        form = layui.form;
        table = tableExt.getLayTable();

        //编辑
        var bjBtn = ${fns:checkPagePermission(request, 'DDGL_GYSDD_GYSDD_BJ_B') eq '0'};
        //撤销
        var cxBtn = ${fns:checkPagePermission(request, 'DDGL_GYSDD_GYSDD_CX_B') eq '0'};

        //开始日期
        var insStart = laydate.render({
            elem: '#repairTime'
            , type: 'datetime'
            , done: function (value, date) {
                //更新结束日期的最小日期
                insEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                insEnd.config.elem[0].focus();
            }
        });
        //结束日期
        var insEnd = laydate.render({
            elem: '#endTime'
            , type: 'datetime'
            , done: function (value, date) {
                //更新开始日期的最大日期
                insStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });

        var orderTimeMin = laydate.render({
            elem: '#orderTimeMin'
            , type: 'datetime'
            , done: function (value, date) {
                //更新结束日期的最小日期
                orderTimeMax.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                orderTimeMax.config.elem[0].focus();
            }
        });
        //结束日期
        var orderTimeMax = laydate.render({
            elem: '#orderTimeMax'
            , type: 'datetime'
            , done: function (value, date) {
                //更新开始日期的最大日期
                orderTimeMin.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });

        window.searchOrder = function () {
            render();
        };

        render();

        function render() {
            tableExt.render({
                elem: '#test'
                , height: 'full-220'
                , toolbar: '#toolbarDemo'
                , defaultToolbar: false
                , limits: [20, 50, 100]
                , limit: 20
                , page: true //开启分页
                , url: '${ctx}/material/order/ajaxForSupplyOrder'
                , where: _serializeJson($("#searchForm"))
                , cols: [[
                    {type: 'numbers', fixed: 'left', title: '序号'},
                    {type: 'checkbox', fixed: 'left', title: '选择'}
                    , {
                        field: 'id', title: '操作', fixed: 'left', minWidth: 100, sort: false, align: 'center', templet: function (d) {
                            if (bjBtn && (d.status === '3')) {
                                return "<a href=\"#\" class=\"layui-table-opt-link   \" onclick=\"edit('" + d.id + "')\">编辑</a>&nbsp;&nbsp;";
                            }
                            if (cxBtn && d.status === '1' && d.type === '2') {
                                return "<a href=\"#\" class=\"layui-table-opt-link   \" onclick=\"cancel('" + d.id + "')\">撤销</a>&nbsp;&nbsp;";
                            }
                            return '- -';
                        }
                    }
                    , {
                        field: 'number',
                        title: '订单编号',
                        minWidth: 200,
                        sort: false,
                        align: 'center',
                        fixed: 'left',
                        exportable: true,
                        templet: function (d) {
                            return "<a href='javascript:orderDetail(\"" + d.id + "\")' class=\"layui-table-link \" style='font-size:14px;'>" + d.number + "</a>";
                        }
                    }
                    , {
                        field: 'status',
                        title: '订单状态',
                        minWidth: 150,
                        sort: false,
                        align: 'center',
                        exportable: true,
                        templet: function (d) {
                            return transStatus(d.status);
                        },
                        expFormat: function (d) {
                            return transStatus(d.status);
                        }
                    }
                    , {
                        field: 'outWarehouseName',
                        title: '出库仓库',
                        minWidth: 150,
                        sort: false,
                        align: 'center',
                        exportable: true
                    }
                    , {
                        field: 'deliver_method_name',
                        title: '发货方式',
                        minWidth: 150,
                        sort: false,
                        align: 'center'
                    }
                    , {
                        field: 'place_name',
                        title: '下单人',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 150
                    }
                    , {
                        field: 'deliver_name',
                        title: '供应商',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 150
                    }
                    , {
                        field: 'id',
                        title: '物料清单',
                        sort: false,
                        align: 'center',
                        minWidth: 150,
                        templet: function (d) {
                            return "<a href=\"#\" class=\"layui-table-link layui-icon   \" style='font-size:14px;' onclick=\"materialDetail('" + d.id + "')\">查看</a>&nbsp;&nbsp;";
                        }
                    }
                    , {
                        field: 'inWarehouseName',
                        title: '入库仓库',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 180
                    }
                    , {
                        field: 'person_in_charge',
                        title: '接货人',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 180
                    }
                    , {
                        field: 'mobile',
                        title: '联系方式',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'address',
                        title: '收货地址',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'relate_no',
                        title: '关联单号',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'deliver_remark',
                        title: '发货备注',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'remarks',
                        title: '下单备注',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'create_time',
                        title: '下单时间',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                    , {
                        field: 'deliver_time',
                        title: '发货时间',
                        sort: false,
                        align: 'center',
                        exportable: true,
                        minWidth: 200
                    }
                ]]
                , exportOpt: {                           //导出选项配置
                    ele: '#exportBtn',                   //导出的Dom元素
                    headerTitle: '供应链仓下单',             //excel表格的标题
                    pageData: false,                     //true:导出的数据为页面数据，false:最大导出maxAmount条数据
                    maxAmount: 5000,                    //当pageData为false生效
                    fileName: '供应链仓下单',
                    where: function () {                 //当pageData为false时生效，过滤的条件
                        return _serializeJson($("#searchForm"));
                    }
                }
            });
        }


        function transStatus(status) {
            switch (status) {
                case '1':
                    return '待发货';
                case '2':
                    return '待入库';
                case '3':
                    return '已撤销';
                case '4':
                    return '仓库打回';
                case '5':
                    return '待审核';
                case '6':
                    return '审核驳回';
                case '7':
                    return '已完成';
                default:
                    return '';
            }
        }


        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'add': {
                    layer.open({
                        title: '新增',
                        type: 2,
                        area: ['80%', '80%'],
                        fixed: false,
                        content: '${ctx}/material/order/toAddSupplyOrder',
                        success: function (layero, index) {
                            childWin = window[layero.find('iframe')[0]['name']];
                        }
                    })
                    break;
                }
                case 'change': {
                    //改派
                    if (checkStatus.data.length < 1) {
                        layer.msg("请先选择数据", {icon: 5, anim: 6});
                        return;
                    }
                    if (checkStatus.data.length > 1) {
                        layer.msg('只能选择一条订单改派');
                        return;
                    }
                    var data = checkStatus.data[0];
                    if (data.status !== '1' && data.status !== '3') {
                        layer.msg('仅未发货的订单可以改派');
                        return;
                    }
                    changeSupply(data.id, data.out_warehouse_id);
                    break;
                }
                case 'delete': {
                    if (checkStatus.data.length < 1) {
                        layer.msg("请先选择数据", {icon: 5, anim: 6});
                        return;
                    }
                    var ids = [];
                    for (var i = 0; i < checkStatus.data.length; i++) {
                        if (checkStatus.data[i].status !== '3') {
                            layer.msg('仅已撤销的订单可以删除');
                            return;
                        }
                        ids.push(checkStatus.data[i].id);
                    }
                    layer.confirm('确认要删除吗？', {
                        icon: 3,
                        btn: ['确定', '取消'] //按钮
                    }, function () {
                        $.ajax({
                            type: 'post',
                            url: '${ctx}/material/order/deleteSupplyOrder',
                            data: {
                                orderIds: ids.join()
                            },
                            success: function (data) {
                                afterSuccess(data);
                            }
                        })
                    });
                    break;
                }
                case 'export': {
                    location.href = '${ctx}/material/order/export/exportDeliverOrder?name=供应链仓下单&' + $('#searchForm').serialize();
                    break;
                }
            }
        });

        //监听行单击事件
        table.on('row(test)', function (obj) {
            var data = obj.data;
            var oldData = table.cache["test"];
            var checkCell = obj.tr.find(".layui-form-checkbox");
            var CHECKED;

        });
        //监听搜索
        form.on('submit(LAY-user-back-search)', function (data) {
            var field = data.field;
            //执行重载
            table.reload('test', {
                where: field,
                page: {
                    curr: 1
                }
            });
        });

    });

    window.importMaterial = function (materials) {
        childWin.importMaterial(materials);
    }

    function edit(id) {
        layer.open({
            title: '新增',
            type: 2,
            area: ['80%', '80%'],
            fixed: false,
            content: '${ctx}/material/order/toAddSupplyOrder?id=' + id,
            success: function (layero, index) {
                childWin = window[layero.find('iframe')[0]['name']];
            }
        })
    }

    function cancel(id) {
        layer.open({
            type: 1,
            area: ['450px', '280px'],
            content: $("#ideaDiv"),
            title: '撤销',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            yes: function () {
                var idea = $('#idea').val();
                if (isBlank(idea)) {
                    layer.msg('请输入撤销原因', {icon: 2});
                    return;
                }
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/order/cancelSupplyOrder',
                    data: {id: id, reason: idea},
                    dataType: 'json',
                    success: function (data) {
                        afterSuccess(data);
                    }
                });
            },
            success: function () {
                $('#idea').val('');
            }
        })
    }

    function orderDetail(id) {
        layer.open({
            title: '详情',
            type: 2,
            area: ['80%', '80%'],
            fixed: false,
            content: '${ctx}/material/order/toDeliverPage?opt=view&id=' + id,
            success: function (layero, index) {
                childWin = window[layero.find('iframe')[0]['name']];
            }
        })
    }

    function materialDetail(id) {
        layer.open({
            type: 2,
            title: "查看",
            resize: false,
            area: ['80%', '70%'],
            content: '${ctx}/material/order/materialList?id=' + id
        });
    }

    function changeSupply(orderId, outWarehouseId) {
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/findDetails',
            data: {id: orderId},
            dataType: 'json',
            success: function(data){
                var arr = [];
                for (var i = 0; i < data.length; i++) {
                    var detail = {};
                    detail.detailId = data[i].id;
                    detail.materialId = data[i].material_id;
                    detail.applyAmount = data[i].apply_amount;
                    detail.amount = data[i].apply_amount;
                    arr.push(detail);
                }
                chooseWarehouse(orderId, arr, outWarehouseId);
            }
        });
    }

    function chooseWarehouse(orderId, arr, excludeWarehouseIds) {
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/canOrderData?excludeWarehouseIds=' + excludeWarehouseIds,
            contentType: 'application/json',
            data: JSON.stringify({
                orderId: orderId,
                details: arr
            }),
            dataType: 'json',
            success: function (data) {
                var html = "<option value=''>请选择</option>";
                var k = 0;
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (item.id !== 'a') {
                        k++;
                        var warehouses = item.warehouseList;
                        html += '<optgroup label="' + item.name + '">';
                        for (var j = 0; j < warehouses.length; j++) {
                            html += '<option value ="' + warehouses[j].id + '">' + warehouses[j].name + '</option>';
                        }
                        html += '</optgroup>';
                    }
                }
                if (k === 0) {
                    layer.msg('未匹配到满足条件的出库仓库');
                    return;
                }
                $('select[name=outWarehouseId]').empty().append(html);
                openOrderWin(orderId);
            }
        });
    }

    function openOrderWin(orderId){
        layer.open({
            type: 1,
            area: ['40%', '55%'],
            content: $("#changeDiv"),
            title: '改派',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            yes: function () {
                var outWarehouseId = $('select[name=outWarehouseId]').val();
                var reason = $('textarea[name=changeReason]').val();
                if (isBlank(outWarehouseId)) {
                    layer.msg('请选择出库仓库', {icon: 2});
                    return;
                }
                if (isBlank(reason)) {
                    layer.msg('请输入改派原因', {icon: 2});
                    return;
                }
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/order/changeSupply',
                    data: {orderIds: orderId, reason: reason, outWarehouseId: outWarehouseId},
                    dataType: 'json',
                    success: function (data) {
                        afterSuccess(data);
                    }
                });
            },
            success: function () {
                form.render();
            },
            end: function(){
                $('select[name=outWarehouseId]').empty();
                $('textarea[name=changeReason]').val('');
            }
        })
    }

    function afterSuccess(data) {
        if (data.code === '200') {
            layer.closeAll();
            layer.msg('操作成功');
            searchOrder();
        } else if (data.code === '501') {
            layer.msg(data.errMsg);
        } else {
            layer.msg('操作失败');
        }
    }

    function isBlank(val) {
        if (val == null || val == '' || val == undefined) {
            return true;
        }
        return false;
    }
</script>
</body>
</html>

