<%@ 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"/>
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/style/formSelects-v4.css" media="all">
    <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/findZjApplyOrder">
                    <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="waitAuditQuery" value="1"/>
            <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>
                            <c:if test="${userType ne '1' && user.userType ne '4'}">
                                <option value="10">暂存</option>
                            </c:if>
                            <option value="1">审批中</option>
                            <option value="-1">审批驳回</option>
                            <option value="2">待分配</option>
                            <option value="5,6">已分配</option>
                            <option value="3">分配驳回</option>
                            <option value="7">已完成</option>
                        </select>
                    </div>
                </div>

                <c:if test="${userType ne '6' && userType ne '7' }">
                <div class="layui-col-lg4 layui-col-sm6">
                    <label class="layui-form-label">代理商名称：</label>
                    <div class="layui-input-block">
                        <select name="traderId" id="traderId" xm-select="status" xm-select-type="1" xm-select-height="25px" xm-select-show-count="6" >
                            <option value="">请选择</option>
                            <c:forEach items="${traderList}" var="trader">
                                <option value="${trader.columns.id}">${trader.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">
                        <select name="qqProjectCode" id="qqProjectCode" lay-search>
                            <option value="">请选择</option>
                            <c:forEach items="${qqProjectList}" var="qqProject">
                                <option value="${qqProject.columns.code}">${qqProject.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="receiveTimeMin" class="layui-input" id="receiveTime"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="receiveTimeMax" class="layui-input" id="receiveEndTime"
                                   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>
            <script type="text/html" id="toolbarDemo">
                <sfTags:flowableAddPermission formId="17" 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='DDGL_ZJXD_XD_B' html='<button class="layui-btn layui-btn-sm" lay-event="add" id="add"><i class="layui-icon layui-icon-add-1"></i>下单</button>'/>--%>
                <sfTags:pagePermission authFlag='JXSDDGL_ZJXD_ZJXDP_HBDD_B' html='<button class="layui-btn layui-btn-sm" lay-event="merge"><i class="layui-icon layui-icon-ok-circle"></i>合并订单</button>'/>
                <c:if test="${userType ne '6' && userType ne '7'}">
                    <sfTags:pagePermission authFlag='JXSDDGL_ZJXD_ZJXDP_DC_B' html='<button class="layui-btn layui-btn-sm" lay-event="export" id="exportBtn"><i class="layui-icon layui-icon-export"></i>导出</button>'/>
                </c:if>
                <c:if test="${userType eq '6' || userType eq '7'}">
                    <sfTags:pagePermission authFlag='JXSDDGL_ZJXD_ZJXD_DC_B' html='<button class="layui-btn layui-btn-sm" lay-event="export" id="exportBtn"><i class="layui-icon layui-icon-export"></i>导出</button>'/>
                </c:if>
                <sfTags:pagePermission authFlag="JXSDDGL_ZJXD_ZJXD_DCPDF_B" html='<button class="layui-btn layui-btn-sm" lay-event="exportPdf"><i class="layui-icon"></i>导出pdf</button>'/>
            </script>
        </div>
    </div>
</div>

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

        //开始日期
        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 inqsStart = laydate.render({
            elem: '#receiveTime'
            , type: 'datetime'
            , done: function (value, date) {
                //更新结束日期的最小日期
                inqssEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                inqssEnd.config.elem[0].focus();
            }
        });
        //结束日期
        var inqssEnd = laydate.render({
            elem: '#receiveEndTime'
            , type: 'datetime'
            , done: function (value, date) {
                //更新开始日期的最大日期
                inqsStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });
        window.searchOrder = function () {
            render();
        };

        render();
        var fpBtn = ${fns:checkPagePermission(request, 'JXSDDGL_ZJXD_ZJXD_FP_B') eq '0'};
        function render() {
            tableExt.render({
                elem: '#test'
                , height: 'full-180'
                , toolbar: '#toolbarDemo'
                , defaultToolbar: false
                , limits: [20, 50, 100]
                , limit: 20
                , page: true //开启分页
                , url: '${ctx}/material/order/ZjauditOderList?types=5'
                , 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) {
                            var htm="";
                            var fg=d.audit;
                            if(d.orderStatus == '3'){  //分配打回
                                if(d.create_by == '${userId}'){
                                    htm+='<a class="layui-table-opt-link" lay-event="edit2">编辑</a>';
                                    htm+='<a class="layui-table-opt-link ml-10" lay-event="delete">删除</a>';
                                }
                            }else if(d.orderStatus == '1' && d.order_examine_status =='0'){
                                if(d.create_by == '${userId}' && d.type !='1'){
                                    htm+='<a class="layui-table-opt-link" lay-event="edit2">编辑</a>';
                                    htm+='<a class="layui-table-opt-link ml-10" lay-event="delete">删除</a>';
                                }
                            }else if(d.orderStatus == '10'  && d.type !='1' && d.create_by == '${userId}'){
                                htm+='<a class="layui-table-opt-link" lay-event="edit2">编辑</a>';
                                htm+='<a class="layui-table-opt-link ml-10" lay-event="delete">删除</a>';

                            }else if(d.order_examine_status == '1' || d.order_examine_status == '2'){
                                if("1"==fg){
                                    htm+= '<a class="layui-table-opt-link" lay-event="audit">审批</a>';
                                }
                            }else if(d.orderStatus =='2' || d.orderStatus =='9' || d.orderStatus =='a'){
                                if(fpBtn){
                                    htm = "<a href=\"#\" class=\"layui-table-link\" style='font-size:14px;' onclick=\"allocationOrder('" + d.id + "')\">分配</a>";
                                }
                            }
                            return htm;
                        }
                    }
                    , {field: 'number',title: '订单编号',minWidth: 180,sort: false,align: 'center',fixed: 'left',exportable: true,
                        templet: function (d) {
                           /* if(d.lookAuth=='1' || d.audit=='1'){*/
                                return "<a href=\"#\" class=\"layui-table-link \" style='font-size:14px;' onclick=\"orderDetail('" + d.id + "')\">" + d.number + "</a>";
                         /*   }else {
                                return d.number;
                            }
*/
                        }

                    }
                    ,{field: 'traderName',title: '代理商名称',minWidth: 150,sort: false,align: 'center',exportable: true}
                    ,{field: 'qqProjectName',title: '企企项目',minWidth: 350,sort: false,align: 'center',exportable: true}
                    // ,{field: 'traderName',title: '物料清单',minWidth: 100,sort: false,align: 'center',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: 150}
                    , {field: 'orderStatus',title: '订单状态',minWidth: 100,sort: false,align: 'center',exportable: true,
                        templet: function (d) {
                            if('1'==d.orderStatus &&  d.order_examine_status =='1'){
                                return "审批中";
                            }else if('1'==d.orderStatus &&  d.order_examine_status =='0'){
                                return "驳回";
                            }else if('10'==d.orderStatus){
                                return "暂存";
                            }else if('3'==d.orderStatus){
                                return "分配打回";
                            }
                            else if('2'==d.orderStatus){
                                return "待分配";
                            }else if('9'==d.orderStatus){
                                return "发货驳回";
                            }else if('7'==d.orderStatus){
                                return "已完成";
                            }else if('c'==d.orderStatus){
                                return "已拆单";
                            }else if('a'==d.orderStatus){
                                return "发货审核驳回";
                            }
                            return "已分配";
                        },
                        expFormat: function (d) {
                            if('1'==d.orderStatus &&  d.order_examine_status =='1'){
                                return "审批中";
                            }else if('1'==d.orderStatus &&  d.order_examine_status =='0'){
                                return "驳回";
                            }else if('2'==d.order_examine_status){
                                return "审批中";
                            }else if('10'==d.orderStatus){
                                return "暂存";
                            }else if('3'==d.orderStatus){
                                return "分配打回";
                            }
                            else if('2'==d.orderStatus){
                                return "待分配";
                            }else if('7'==d.orderStatus){
                                return "已完成";
                            }else if('c'==d.orderStatus){
                                return "已拆单";
                            }else if('a'==d.orderStatus){
                                return "发货审核驳回";
                            }
                            return "已分配";
                        }
                    } , {field: 'orderStatus',title: '发货状态',minWidth: 100,sort: false,align: 'center',exportable: true,
                        templet: function (d) {
                            if('5'==d.orderStatus ){
                                return "待发货";
                            }else if('6'==d.orderStatus){
                                return "已发货";
                            }else if('7'==d.orderStatus){
                                return "已发货";
                            }
                            return "";
                        },
                        expFormat: function (d) {
                            if('5'==d.orderStatus ){
                                return "待发货";
                            }else if('6'==d.orderStatus){
                                return "已发货";
                            }else if('7'==d.orderStatus){
                                return "已发货";
                            }
                            return "";
                        }
                    } , {field: 'orderStatus',title: '签收状态',minWidth: 100,sort: false,align: 'center',exportable: true,
                        templet: function (d) {
                             if('6'==d.orderStatus){
                                return "待签收";
                            }else if('7'==d.orderStatus){
                                return "已签收";
                            }
                            return "";
                        },
                        expFormat: function (d) {
                            if('6'==d.orderStatus){
                                return "待签收";
                            }else if('7'==d.orderStatus){
                                return "已签收";
                            }
                            return "";
                        }
                    }, {field: 'person_in_charge',title: '接货人',sort: false,align: 'center',exportable: true,minWidth: 120}
                    , {field: 'deliverMobile',title: '联系电话',sort: false,align: 'center',exportable: true,minWidth: 120}
                    , {field: 'warehouseAddress',title: '仓库地址',sort: false,align: 'center',exportable: true,minWidth: 150}
                    , {field: 'createTime',title: '下单时间',sort: false,align: 'center',exportable: true,minWidth: 200}
                    , {field: 'receiveTime',title: '签收时间',sort: false,align: 'center',exportable: true,minWidth: 200}
                    , {field: 'audit_remark',title: '审批意见',sort: false,align: 'center',exportable: true,minWidth: 200}
                    , {field: 'remarks',title: '订单备注',sort: false,align: 'center',exportable: true,minWidth: 180}

                ]]
                , exportOpt: {                           //导出选项配置
                    ele: '#exportBtn',                   //导出的Dom元素
                    headerTitle: '现金下单',             //excel表格的标题
                    pageData: false,                     //true:导出的数据为页面数据，false:最大导出maxAmount条数据
                    maxAmount: 5000,                    //当pageData为false生效
                    fileName: '现金下单',
                    where: function () {                 //当pageData为false时生效，过滤的条件
                        return _serializeJson($("#searchForm"));
                    }
                }
            });
        }
        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%', '90%'],
                        content: '${ctx}/material/apply/createZjOrder'
                    })
                    break;
                }
                case 'exportPdf':{
                    if (checkStatus.data.length < 1) {
                        layer.msg("请先选择数据", {icon: 5, anim: 6});
                        return;
                    }
                    if (checkStatus.data.length > 1) {
                        layer.msg("只能选择数据一条数据", {icon: 5, anim: 6});
                        return;
                    }
                    var orderType=checkStatus.data[0].type;
                    if(orderType!='1' && orderType !='2' && orderType !='5'){
                        layer.msg("非赊销下单和现金下单不可导出pdf!", {icon: 5, anim: 6});
                        return;
                    }
                    var orderExamineStatus=checkStatus.data[0].order_examine_status;
                    if(orderExamineStatus!=3){
                        layer.msg("订单审批通过的才可导出pdf!", {icon: 5, anim: 6});
                        return;
                    }
                    var id=checkStatus.data[0].id;
                    var hideSubmitForm = document.createElement("form");
                    hideSubmitForm.id = "tempForm1";
                    hideSubmitForm.method = "post";
                    hideSubmitForm.action = "${ctx}/material/order/exportOrderPdfDocument";
                    hideSubmitForm.target = "_blank";
                    hideSubmitForm.appendChild(createHideInput("id", id));
                    hideSubmitForm.addEventListener('onsubmit', function(){
                        // this.openDownloadWindow(name);
                    });
                    document.body.appendChild(hideSubmitForm);
                    hideSubmitForm.submit();
                    document.body.removeChild(hideSubmitForm);
                    break;
                }
                case 'merge':
                    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].orderStatus !== '2') {
                            layer.msg('仅待分配的订单可以合并');
                            return;
                        }
                        ids.push(checkStatus.data[i].id);
                    }
                    if (ids.length < 2) {
                        layer.msg('合并订单数不少于2条');
                        return;
                    }
                    layer.confirm('确认要合并吗？', {
                        icon: 3,
                        btn: ['确定', '取消'] //按钮
                    }, function () {
                        $.ajax({
                            type: 'post',
                            url: '${ctx}/material/order/mergeDeliverOrder',
                            data: {
                                ids: ids.join()
                            },
                            success: function (data) {
                                if (data.code === '200') {
                                    layer.msg('操作成功', {time: 1000});
                                    render();
                                } else if (data.code === '501') {
                                    layer.msg(data.errMsg, {time: 1000});
                                } else {
                                    layer.msg('操作失败', {time: 1000});
                                }
                            }
                        })
                    });
                    break;
            }
        })

        //头工具栏事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            var id = data.id;
            var formKey = "17";
            switch (obj.event) {
                case 'audit':{
                    layer.open({
                        title:'审批',
                        type: 2,
                        area: ['100%', '100%'],
                        content: '${ctx}/material/order/supplyMaterialOrderAudit?id='+id+'&from=audit&formKey=17'
                    })
                    break;
                }     case 'edit2':{
                    layer.open({
                        title:'编辑',
                        type: 2,
                        area: ['80%', '90%'],
                        content: '${ctx}/material/apply/supplyOrderZjEdit?orderId='+id
                    })
                    break;
                }
                case 'delete':{
                    layer.confirm('确认删除当前数据',{
                        btn: ['确定', '取消'],
                        success: function (layero, index) {
                            this.enterEsc = function (event) {
                                if (event.keyCode == 13 ) {
                                    //确认  执行的代码
                                    deleteInventory(id,formKey);
                                    //关闭弹窗
                                    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 () {
                            //确认执行的代码
                            deleteInventory(id,formKey);
                        },
                        no: function () {

                        }
                    });

                    break;
                }
                case 'edit':{
                    layer.open({
                        title:'编辑',
                        type: 2,
                        area: ['80%', '90%'],
                        content: '${ctx}/material/order/supplyMaterialOrderAudit?id='+id+'&from=edit'
                    })
                    break;
                }
            }
        });


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


        $('input').on('keydown', function(event){
            if(event.keyCode == 13){
                //执行相关操作
                $("#searchBtn").click();
            }
        });

    });

    /**
     * 审批
     */
    function audit(id) {
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/canOperate',
            data: {
                orderId: id
            },
            dataType: 'json',
            success: function (data) {
                if (data.code === '200') {
                    if (data.data) {
                        layer.open({
                            type: 2,
                            title: "审批",
                            resize: false,
                            area: ['80%', '70%'],
                            content: '${ctx}/material/order/toAudit?applyId=' + id
                        });
                    } else {
                        layer.msg('当前角色无操作权限');
                    }
                } else {
                    layer.msg('操作失败，请联系管理员');
                }
            }
        });
    }

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

    /**
     * 删除订单
     */
    function deleteInventory(ids,formKey){
        $.post('${ctx}/material/order/deleteAuditOrder', {orderId: ids, formKey:formKey}, function (result) {
            if (result.code === '200') {
                layer.msg('操作成功', {time: 1000}, function () {
                    $(".layui-laypage-btn").click();
                });
            } else {
                layer.msg('操作失败！' + result.errMsg);
            }
        });
    }

    function orderDetail(id) {
        layer.open({
            type: 2,
            title: "查看",
            resize: false,
            area: ['80%', '90%'],
            content: '${ctx}/material/order/auditOderDetailPage?id=' + id
        });
    }
    function  createHideInput(name, value){
        var hideInput = document.createElement("input");
        hideInput.type = "hidden";
        hideInput.name = name;
        hideInput.value = value;
        return hideInput;
    }

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

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

