<%@ 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/deliverOrderList">
                    <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="deliverId" value="${deliverId}"/>--%>
            <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="2">待分配</option>
                            <option value="9">发货打回</option>
                            <option value="a">发货审核不通过</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="type">
                            <option value="">请选择</option>
                            <option value="1">电站下单</option>
                            <option value="2">储备物料</option>
                            <option value="3">平台采购</option>
                            <option value="4">合并发货</option>

                        </select>
                    </div>
                </div>
                <div class="layui-col-lg2 layui-col-sm3">
                    <label class="layui-form-label">代理商名称：</label>
                    <div class="layui-input-block">
                        <div id="traderId"></div>
                    </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-lg4 layui-col-sm6">
                    <label class="layui-form-label">下单时间：</label>
                    <div class="layui-input-block">
                        <div class="layui-col-xs5">
                            <input type="text" name="placeTimeMin" class="layui-input" id="placeTimeMin"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="placeTimeMax" class="layui-input" id="placeTimeMax"
                                   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="auditTimeMin" class="layui-input" id="auditTimeMin"
                                   placeholder="开始日期">
                        </div>
                        <div class="layui-col-xs2 text-c lh-30">
                            —
                        </div>
                        <div class="layui-col-xs5">
                            <input type="text" name="auditTimeMax" class="layui-input" id="auditTimeMax"
                                   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>

<script type="text/html" id="toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="merge"><i class="layui-icon layui-icon-export"></i>合并订单</button>
    <button class="layui-btn layui-btn-sm" lay-event="export" id="exportBtn"><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>
    var traderId;
    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 fhBtn = ${fns:checkPagePermission(request, 'CKGL_FHDGL_FHDGL_FH_B') eq '0'};

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

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

        projectSelect = xmSelect.render({
            el: '#traderId',
            name: 'traderId',
            filterable: true,
            size: 'mini',
            model: {
                label: {
                    type: 'block',
                    block: {
                        //最大显示数量, 0:不限制
                        showCount: 2,
                        //是否显示删除图标
                        showIcon: true,
                    }
                }
            },
            toolbar: {
                show: true
            },
            height: '300px',
            data: [
                <c:forEach items="${traders}" var="trader" varStatus="vs">
                <c:if test="${vs.count > 1}">, </c:if>
                {name: '${trader.columns.name}', value: '${trader.columns.id}'}
                </c:forEach>
            ]
        });
        projectSelect.setValue('${map.traderId}'.split(","));

        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/ajaxForDeliverOrderData'
                , where: _serializeJson($("#searchForm"))
                , cols: [[
                    {type: 'numbers', fixed: 'left', title: '序号'},
                    {type: 'checkbox', fixed: 'left', title: '选择'}
                    , {field: 'id', title: '操作', fixed: 'left', minWidth: 100, align: 'center',
                        templet: function (d) {
                            var html = "<a href=\"#\" class=\"layui-table-link\" style='font-size:14px;' onclick=\"allocationOrder('" + d.id + "')\">分配</a>";
                            // if (fhBtn && (d.status === '1' || d.status === '4')) {
                            //     return html + "&nbsp;&nbsp;<a href=\"#\" class=\"layui-table-link\" style='font-size:14px;' onclick=\"deliver('" + d.id + "')\">发货</a>";
                            // }
                            if(d.purchase_order_examine_status=='2'){
                               html+='<span data-oneself = \"oneselfFlag\"></span>';
                            }
                            return html;
                        }
                    }
                    , {field: 'number', title: '订单编号', fixed: 'left', minWidth: 200, align: 'center', exportable: true,
                        templet: function (d) {
                            return "<a href=\"#\" class=\"layui-table-link\" style='font-size:14px;' onclick=\"orderDetail('" + d.id + "')\">" + d.number + "</a>";
                        }
                    }
                    , {field: 'applyOrderTrader', title: '代理商名称', minWidth: 150, align: 'center', exportable: true}
                    , {field: 'id', title: '物料清单', 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: '入库仓库', align: 'center', exportable: true, minWidth: 180}
                    , {field: 'audit_time', title: '审批时间', align: 'center', exportable: true, minWidth: 200}
                    , {field: 'status', title: '订单状态', minWidth: 150, align: 'center', exportable: true,
                        templet: function (d) {
                            return transStatus(d.status);
                        },
                        expFormat: function (d) {
                            return transStatus(d.status);
                        }
                    }
                    , {field: 'type', title: '订单来源', minWidth: 150, align: 'center', exportable: true
                        , templet: function (d) {
                            if (d.type === '1') {
                                return '电站下单';
                            } else {
                                return '储备物料';
                            }
                        }
                        , expFormat: function (d) {
                            if (d.type === '1') {
                                return '电站下单';
                            } else {
                                return '储备物料';
                            }
                        }
                    }


                    , {field: 'person_in_charge', title: '接货人', align: 'center', exportable: true, minWidth: 180}
                    , {field: 'mobile', title: '联系电话', align: 'center', exportable: true, minWidth: 200}
                    , {field: 'w_address', title: '仓库地址', align: 'center', exportable: true, minWidth: 200}
                    , {field: 'create_time', title: '下单时间', align: 'center', exportable: true, minWidth: 200}
                    , {field: 'remarks', title: '订单备注', 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"));
                    }
                },done: function(res, curr, count){
                     $('span[data-oneself="oneselfFlag"]').parent().parent().parent().css('background-color', '#E2D5D2');
                }
            });
        }


        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 '已完成';
                case '8':
                    return '已并单';
                case 'a':
                    return '发货审核不通过';
                case '9':
                    return '发货打回';
                default:
                    return '';
            }
        }


        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {

                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].status !== '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('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
                }
            });
        });

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

    });

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

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

    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 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);
                    }
                });
            }
        })
    }

    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 printOrder(id) {
        layer.open({
            title: '打印',
            type: 2,
            area: ['85%', '85%'],
            fixed: false,
            content: '${ctx}/material/order/printOrder?applyId=' + id,
            success: function (layero, index) {
                childWin = window[layero.find('iframe')[0]['name']];
            }
        })
    }

    // 分配
    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 applyOrderDetail(id) {
        layer.open({
            type: 2,
            title: "查看",
            resize: false,
            area: ['80%', '70%'],
            content: '${ctx}/material/apply/materialDetail?applyId=' + id
        });
    }

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

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

