<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE HTML>
<html>
<head>
    <title>能辉</title>
    <meta name="decorator" content="base" />
    <link rel="stylesheet" href="${ctxPlugin}/static/css/reset.css" media="all">
    <style>
        .layui-card{box-shadow: none;}
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-form layui-card">
        <div class="layui-tab  layui-tab-brief">
            <ul class="layui-tab-title">
                <sfTags:pagePermission authFlag="CKGL_CGDGL_CGDGL_T" html='<li class="layui-this sf-tab"><a href="${ctx}/purchaseManage/purchasePage">采购单管理</a></li>'/>
                <button class="layui-btn f-r mt-10 mr-15 pl-10 pr-10 " type="reset"  onclick="reset()" >
                    <i class="layui-icon fs-12">&#xe9aa;</i>
                    重置
                </button>
                <button class="layui-btn f-r mt-10 mr-15 pl-10 pr-10 " lay-submit lay-filter="LAY-user-back-search" data-type="reload">
                    <i class="layui-icon fs-12">&#xe615;</i>
                    查询
                </button>
            </ul>
        </div>
        <div class="layui-card-body" id="searchForm">
            <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"  autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">SAP采购号：</label>
                    <div class="layui-input-block">
                        <input type="text" name="spaNumber"  autocomplete="off" 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="creator"  autocomplete="off" 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="a">待报检</option>
                            <option value="2">待检验</option>
                            <option value="3">部分检验</option>
                            <option value="4">已完成</option>
                            <option value="5">已撤销</option>
                        </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="remark"  autocomplete="off" class="layui-input">
                    </div>
                </div>
                <c:if test="${userType eq '1'}">
                    <div class="layui-col-lg2 layui-col-sm3">
                        <label class="layui-form-label">供应商：</label>
                        <div class="layui-input-block">
                            <input type="text" name="supplierName"  autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </c:if>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">检验备注：</label>
                    <div class="layui-input-block">
                        <input type="text" name="examineRemark"  autocomplete="off" class="layui-input">
                    </div>
                </div>
                <c:if test="${userType eq '2'}">
                    <div class="layui-col-lg2 layui-col-sm3">
                        <label class="layui-form-label">入库仓库：</label>
                        <div class="layui-input-block">
                            <select name="warehouseId" lay-search>
                                <option value="">请选择</option>
                                <c:forEach var="warehouse" items="${warehouse}">
                                    <option value="${warehouse.columns.id}">${warehouse.columns.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </c:if>

                <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="createTimeSta" id="createTimeSta" class="layui-input"  placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="createTimeEnd" id="createTimeEnd" class="layui-input"  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="confirmTimeSta" id="confirmTimeSta" class="layui-input"  placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="confirmTimeEnd" id="confirmTimeEnd" class="layui-input"  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="examineTimeSta" id="examineTimeSta" class="layui-input"  placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="examineTimeEnd" id="examineTimeEnd" class="layui-input"  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="finishTimeSta" id="finishTimeSta" class="layui-input"  placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="finishTimeEnd" id="finishTimeEnd" class="layui-input"  placeholder="结束日期">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class='layui-card'>
        <div class="layui-card-body">
            <table class="layui-hide" lay-skin="row" id="test-table-reload" lay-filter="table-toolbar"></table>
                <script type="text/html" id="toolbarDemo">
                        <c:if test="${userType =='1'}">
                            <sfTags:pagePermission authFlag="CKGL_CGDGL_XZ_T" html='<button class="layui-btn layui-btn-sm" id="add" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>新增</button>'/>
                            <sfTags:pagePermission authFlag="CKGL_CGDGL_SC_T" html='<button class="layui-btn layui-btn-sm" id="delete" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</button>'/>
                            <sfTags:pagePermission authFlag="CKGL_CGDGL_GGDD_T" html='<button class="layui-btn layui-btn-sm" id="update" lay-event="update" ><i class="layui-icon layui-icon-add-1"></i>更改订单</button>'/>
                        </c:if>
                         <button class="layui-btn layui-btn-sm" id="export" lay-event="export" ><i class="layui-icon layui-icon-export"></i>导出</button>
                </script>

        </div>
    </div>

</div>


<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script type="text/html" id="table-toolbar">
<c:if test="${userType eq 1}">
    {{# if(d.status == '5'){ }}
    <sfTags:pagePermission authFlag="CKGL_CGDGL_BJ_T" html='<a class="layui-table-opt-link" lay-event="edit">编辑</a>'/>
    {{# }else if(d.status == '1'){ }}
    <sfTags:pagePermission authFlag="CKGL_CGDGL_CX_T" html='<a class="layui-table-opt-link" lay-event="cancel">撤销</a>'/>
    {{# } }}
</c:if>
<c:if test="${userType eq 2}">
    {{# if(d.status == '1'){ }}
    <a class="layui-table-opt-link" lay-event="confirm">确认</a>
    {{# }else if(d.status == '2' || d.status == '3' || d.status == 'a'){ }}
    <a class="layui-table-opt-link" lay-event="inspection">报检</a>
    {{# } }}
</c:if>
</script>

<script type="text/javascript">
    var table;
    var $;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'tableExt', 'jquery', 'layer','laydate','form'], function(){
        var tableExt = layui.tableExt;
        var layer = layui.layer;
        $ = layui.jquery;
        var laydate = layui.laydate;
        var  form = layui.form;

        table = tableExt.getLayTable();

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

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

        var confirmEnd = laydate.render({
            elem: '#confirmTimeEnd'
            ,type: 'date'
            ,done: function(value, date){
                //更新开始日期的最大日期
                confirmStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });
        //开始检验时间
        var examineStart = laydate.render({
            elem: '#examineTimeSta'
            ,type: 'date'
            ,done: function(value, date){
                //更新结束日期的最小日期
                examineEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                examineEnd.config.elem[0].focus();
            }
        });
        //结束日期
        var examineEnd = laydate.render({
            elem: '#examineTimeEnd'
            ,type: 'date'
            ,done: function(value, date){
                //更新开始日期的最大日期
                examineStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });

        //完成时间
        var finishStart = laydate.render({
            elem: '#finishTimeSta'
            ,type: 'date'
            ,done: function(value, date){
                //更新结束日期的最小日期
                finishEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                finishEnd.config.elem[0].focus();
            }
        });

        var finishEnd = laydate.render({
            elem: '#finishTimeEnd'
            ,type: 'date'
            ,done: function(value, date){
                //更新开始日期的最大日期
                finishStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });

        tableExt.render({
            elem: '#test-table-reload'
            ,toolbar : '#toolbarDemo'
            , height: 'full-218'
            ,defaultToolbar : false
            , limits : [ 20, 50, 100 ]
            , limit:20
            , page : true //开启分页
            ,url: '${ctx}/purchaseManage/purchaseOrderList'
            ,cols: [[
                {type: 'numbers', title: '序号' ,fixed: 'left'}
                ,{field : 'id', checkbox : true,fixed: 'left' }
                ,{field:'id', title: '操作',toolbar: '#table-toolbar',align: 'center',minWidth: 90,fixed: 'left' }
                ,{field:'number', title: '订单编号',align: 'center',width: 180,fixed: 'left'
                ,templet:function(d){
                    return '<a href="#" class="layui-table-link" onclick="orderDetail(\''+d.id+'\')">'+d.number+'</a>'
                    }
                }
                ,{field:'spa_number', title: 'SAP采购订单号',align: 'center',width: 180}
                ,{field:'status', title: '订单状态',align: 'center' ,width: 90
                    ,templet:function(d){
                        if(d.status=='1'){
                            return "待确认";
                        }else if(d.status=='2'){
                            return "待检验";
                        }else if(d.status=='3'){
                            return "部分检验";
                        }else if(d.status=='4'){
                            return "已完成";
                        }else if(d.status=='5'){
                            return "已撤销";
                        }else if(d.status=='a'){
                            return "待报检";
                        }else{
                            return "";
                        }
                    }
                }

                ,{field:'supplierName', title: '供应商',align: 'center',width: 120}
                ,{field:'creator', title: '下单人',align: 'center',width: 90}
                ,{field:'address', title: '物料清单',align: 'center',minWidth: 90
                    ,templet:function(d){
                       return '<a href="#" class="layui-table-link" onclick="materialDetail(\''+d.id+'\')">查看</a>';
                    }
                    }
                ,{field:'remark', title: '订单备注',align: 'center',width: 110}
                ,{field:'warehouseName', title: '入库仓库',align: 'center',width:110}
                ,{field:'examine_remark', title: '检验备注',align: 'center',width:110}
                ,{field:'create_time', title: '下单时间',align: 'center',width: 180}
                ,{field:'confirm_time', title: '确认时间',align: 'center',width: 180 }
                ,{field:'inspection_time', title: '开始报检时间',align: 'center',width: 180}
                ,{field:'finish_time', title: '完成时间',align: 'center',width: 180}
            ]]
            ,done: function(res, curr, count){

            },exportOpt:{                           //导出选项配置
                ele:'#exportBtn',                   //导出的Dom元素
                headerTitle: '员工列表',             //excel表格的标题
                pageData:false,                     //true:导出的数据为页面数据，false:最大导出maxAmount条数据
                maxAmount: 1000,                    //当pageData为false生效
                fileName: '员工导出',
                where: function (){                 //当pageData为false时生效，过滤的条件
                    return _serializeJson($("#searchForm"));
                }
            }
        });

        table.on('toolbar(table-toolbar)',function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            switch (obj.event){
                case 'add':
                    layer.open({
                        title:'新增',
                        type: 2,
                        area: ['80%', '80%'],
                        fixed: false,
                        content: '${ctx}/purchaseManage/addPurchaseOrderPage?model=add',
                        success: function (layero, index) {
                            childWin = window[layero.find('iframe')[0]['name']];
                        }
                    })

                    break;
                case 'delete':
                    if (data.length < 1) {
                        layer.msg("请至少选择一条数据",{icon:5,anim:6});
                        return;
                    }
                    var orderId="";
                    for(var i=0;i<data.length;i++){
                        if(data[i].status != 5){
                            layer.msg("您选择的采购单中有不可操作删除的订单，请重新选择！",{icon:5,anim:6});
                            return;
                        }
                        orderId+=data[i].id+",";
                    }
                    layer.confirm('您确定要删除采购单吗？',{
                        btn: ['确定', '取消'],
                        success: function (layero, index) {
                            this.enterEsc = function (event) {
                                if (event.keyCode == 13 ) {
                                    //确认  执行的代码
                                    deletePurchaseOrder(orderId);
                                    //关闭弹窗
                                    layer.close(index);
                                    console.log("回车确认时事件")
                                    //取消连续回车键，导致不断弹出询问框
                                    $(':focus').blur();
                                }
                            };
                            //监听键盘事件
                            $(document).on('keydown', this.enterEsc);
                            //esc键触发取消
                            this.escQuit = (ev) => {
                                let code_val = ev.which;
                                if(code_val == 0x1B){
                                    $('.layui-layer-btn1').click();
                                    return false;
                                }
                            };
                            $(document).on('keydown', this.escQuit);
                        },
                        end: function () {
                            //取消键盘监听事件
                            $(document).off('keydown', this.enterEsc);
                            $(document).off('keydown', this.escQuit);
                        },
                        yes: function () {
                            //确认执行的代码
                            deletePurchaseOrder(orderId);
                        },
                        no: function () {

                        }
                    });

                    break;
                case 'update':
                    if (data.length != 1) {
                        layer.msg("请选择一条数据",{icon:5,anim:6});
                        return;
                    }
                    var orderId = data[0].id;
                    var status = data[0].status;
                    if(status ==4){
                        layer.msg("当前状态不可更改订单!",{icon:5,anim:6});
                        return;
                    }
                    layer.open({
                        type: 2,
                        title: '更改订单',
                        content: '${ctx}/purchaseManage/addPurchaseOrderPage?model=update&id=' + orderId,
                        area: ['80%','80%'],
                        success: function (layero, index) {
                            childWin = window[layero.find('iframe')[0]['name']];
                        }
                    });
                    break;
                case 'export':
                    location.href='${ctx}/purchaseManage/exportPurchaseOrder?name=采购单&' + $('#searchForm').serialize();
                    break;
            }
        })

        //监听行工具事件
        table.on('tool(table-toolbar)', function(obj){
            var data = obj.data;
            var id = data.id;
            if(obj.event === 'cancel'){
                layer.prompt({
                    formType: 2,
                    title: '撤销原因',
                    area: ['380px', '160px'],
                    btnAlign: 'c',
                    id: 'prompt',
                    yes: function (index, layero) {
                        // 获取文本框输入的值
                        var value = layero.find(".layui-layer-input").val();
                        $.ajax({
                            type:"POST",
                            url:"${ctx}/purchaseManage/cancelPurchaseOrder",
                            async:false,
                            data:{
                                id:id,
                                remark:value
                            },
                            success:function(result){
                                if(result.code =='200'){
                                    layer.msg("保存成功！")
                                    reload();
                                }else{
                                    layer.msg("保存失败！")
                                }
                                layer.close(index);//关闭弹框
                            }
                        })

                    }
                });
            } else if(obj.event === 'edit'){
                layer.open({
                    title:'编辑',
                    type: 2,
                    area: ['80%', '80%'],
                    fixed: false,
                    content: '${ctx}/purchaseManage/addPurchaseOrderPage?model=edit&id='+id,
                })
            }else if(obj.event === 'confirm'){
                var indexla = layer.confirm('已确认？', {
                    icon: 3,
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.ajax({
                        type: "POST",
                        url: "${ctx}/purchaseManage/confirmPurchaseOrder",
                        data: {
                            orderId: id
                        },
                        success: function (result) {
                            if (result.code == "200") {
                                layer.msg('操作成功！', {icon: 1, time: 1000}, function () {
                                    reload();
                                });
                            } else if (result.code == "501") {
                                layer.msg(result.errMsg , {icon: 2})
                            }else{
                                layer.msg('操作失败！', {icon: 2})
                            }
                        }
                    });

                }, function () {
                    layer.close(indexla)
                });
            }else if(obj.event === 'examine'){
                layer.open({
                    type: 2,
                    title: '检验',
                    content: '${ctx}/purchaseManage/examinePurchaseOrderPage?id=' + id,
                    area: ['80%','80%']
                });
            }else if(obj.event === 'inspection'){
                layer.open({
                    type: 2,
                    title: '报检',
                    content: '${ctx}/purchaseManage/purchaseOrderInspectionPage?id=' + id,
                    area: ['80%','80%']
                });
            }
        });

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

    });

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

    function deletePurchaseOrder(orderId){
        $.ajax({
            type: "POST",
            url: "${ctx}/purchaseManage/deletePurchaseOrder",
            data: {
                orderIds: orderId
            },
            success: function (result) {
                if (result.code == "200") {
                    layer.msg('操作成功！', {icon: 1, time: 1000}, function () {
                        reload();
                    });
                } else if (result.code == "501") {
                    layer.msg(result.errMsg , {icon: 2})
                }else{
                    layer.msg('操作失败！'+result.errMsg, {icon: 2})
                }
            }
        });
    }

    function orderDetail(orderId){
        layer.open({
            type: 2,
            title: '详情',
            content: '${ctx}/purchaseManage/orderDetail?id=' + orderId,
            area: ['80%','80%']
        });
    }

    function materialDetail(orderId){
        layer.open({
            type: 2,
            title: '查看',
            content: '${ctx}/purchaseManage/orderMaterialList?id=' + orderId,
            area: ['80%','80%']
        });
    }

    function reload(){
        table.reload('test-table-reload', {
            page:{
                curr:1
            }
        });
    }

    function reset(){
        layui.form.render();
        $("#searchForm").find("select").val("");
        $("#searchForm").find("input").val("");
    }

</script>
</body>
</html>
