<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <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" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/static/css/reset.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/dist/viewer.css" media="all">
    <style>
        .layui-form-select dl{
            max-height:200px;
            width: 80%;
        }
        html {
            background-color: #fff;
        }
        .layui-table td, .layui-table th {
            text-align: center;
        }
        .hx_l{
            position: relative;
        }
        .hx_l>span{position: absolute; right: 10px; top: 5px}
        .hx_del{ font-size: 12px; color: #0e8ee7; position: relative; top: 4px; display: none}
        #attachFile>li{height: 26px}
        #attachFile>li:hover .hx_del{ display: inline-block}
        .hx_ts{
            font-size: 12px;
            color: red;
        }
        .layui-word-aux{
            padding: 7px 0 !important;
        }
        .totalAmount{
            color: #0099cc;
        }
        .totalDiff{
            color: #ff0000;
        }

        .layui-form-select dl{
            max-height:200px;
            width: 80%;
        }
        .w-130{width: 130px}
        .ml120 .layui-input-block{margin-left: 130px}
        .ml-130{margin-left:  130px}
        .border-grey{border: 1px solid #DDD; border-radius: 10px;}
        .table-input{width: 30px; border: none; text-align: center; height: 30px; line-height: 30px}
        .layui-elem-field legend{font-size: 16px}
        .img-80{display: flex; justify-content: center;}
        .img-80 .bj-img{margin-right: 0}
        .load-icon{background: url('${ctxPlugin}/static/img/shili_img.png') center center no-repeat; width: 12px; height: 12px; display: inline-block; border-radius: 50%;
            vertical-align: text-bottom;transform: translate(0px, -1px);margin-right: 2px;}
    </style>
</head>
<body>
<div class="layui-form" id="LAY_app">
    <div class="layui-card mt-10">

        <div class="layui-tab layui-tab-brief over pt-20 pb-40 h-350" lay-filter="docDemoTabBrief" id="detailSet">
            <ul class="layui-tab-title">
                <li class="layui-this">表单信息</li>
                <c:if test="${7 != user.userType && 6!= user.userType}">
                   <%-- <li>流程路径</li>--%>
                    <li>审批过程</li>
                </c:if>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <blockquote class="layui-elem-quote">盘点信息</blockquote>
            <div class="layui-col-xs12 ml120 mt-20">
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-130"><i class="red">*</i>盘点对象：</label>
                    <div class="layui-input-block ">
                        <select name="inventoryType" lay-verify="required" lay-filter="inventoryType">
                            <option value="">请选择</option>
                            <option value="1" ${order.inventoryType eq '1' ? 'selected' : ''}>供应链</option>
                            <option value="2" ${order.inventoryType eq '2' ? 'selected' : ''}>代理商</option>
                        </select>
                    </div>
                    <input type="text" class="layui-hide inventoryType" value="${order.inventoryType}">
                </div>
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-130"><i class="red">*</i>盘点仓库：</label>
                    <div class="layui-input-block w-200">
                        <select name="warehouseId" lay-verify="required" id="warehouseId" lay-filter="warehouseId" lay-search>
                            <option value="">请选择</option>
                            <c:forEach items="${warehouseList}" var="warehouse">
                                <option value="${warehouse.columns.id}" ${warehouse.columns.id eq order.warehouseId ? 'selected' : ''}>${warehouse.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <input type="text" class="layui-hide warehouseId" value="${order.warehouseId}">
                </div>

                <div class="layui-inline layui-col-xs12">
                    <label class="layui-form-label w-130">盘点备注：</label>
                    <div class="layui-input-block w-200 hx_l" >
                        <textarea name="remarks" class="layui-textarea">${order.remarks}</textarea>
                    </div>
                </div>
                <!-- 编辑时 显示“审核驳回原因” -->

            </div>
            <div class="layui-col-xs12 layui-form-item mt-5">
                <label class="layui-form-label">清单附件：
                    <%--<br/><a href="${commonStaticImgPath}/prohibit_delete/示例图/库单盘点表示例.png" style="font-size: 12px;color: red;margin-right: 5px;"><i class="load-icon"></i>下载示例图</a>--%>
                </label>
                <div class="layui-input-block">
                    <div id="imgsDiv">
                        <c:if test="${not empty order.img}">
                            <div class="bj-img imgSpan">
                                <c:if test="${mode eq 'edit'}"><span class="layui-icon-close layui-icon" onclick="delImg(this)"></span></c:if>
                                <img src="${commonStaticImgPath}${order.img}" height="700" width="1200" data-img="${commonStaticImgPath}${order.img}"/>
                                <input type="hidden" class="imgPicker" value="${order.img}" />
                            </div>
                        </c:if>
                    </div>
                    <div class="upload-container" id="uploader" <c:if test="${not empty order.img}">style="display: none"</c:if> >
                        <img src="" alt="img placeholder" id="imgsAdd">
                    </div>
                </div>

            </div>

            <input type="hidden" name="details" lay-verify="details">
            <input type="hidden" name="img" lay-verify="img">
            <c:if test="${mode eq 'edit'}">
                <div>
                    <input type="button" class="layui-btn layui-btn-sm" id="importPlan" value="批量导入"/>
                </div>
            </c:if>
            <div class="layui-col-xs12 mb-20 pr-30 mt-20">
                <div class="layui-tab layui-tab-brief" >
                    <blockquote class="layui-elem-quote">物料信息</blockquote>
                    <div  style=" overflow: auto">
                        <div class=" layui-show">
                            <table class="layui-table">
                                <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>物料代码</th>
                                    <th>外部代码</th>
                                    <th>物料类型</th>
                                    <th>单位</th>
                                    <th>物料描述</th>
                                    <th>当前库存</th>
                                    <th>盘点数量</th>
                                    <c:if test="${mode ne 'edit'}"><th>盘盈/盘亏</th></c:if>
<%--                                    <c:if test="${user.userType ne '6' && user.userType ne '7'}">--%>
<%--                                        <th>成本价</th>--%>
<%--                                    </c:if>--%>
                                    <%--<th>销售价</th>--%>
                                </tr>
                                </thead>
                                <tbody id="materialTable">
                                <c:forEach items="${details}" varStatus="vs" var="material">
                                    <tr data-id="${material.columns.material_id}">
                                        <td>${vs.count}</td>
                                        <td>${material.columns.material_code}</td>
                                        <td>${material.columns.qq_code}</td>
                                        <td>${material.columns.material_type}</td>
                                        <td>${material.columns.material_unit}</td>
                                        <td>${material.columns.material_remarks}</td>
                                        <td><fmt:formatNumber value="${material.columns.stock}" pattern="#" /></td>
                                        <c:if test="${mode eq 'edit'}"><td><input type="text" class="layui-input amount" value="<fmt:formatNumber value="${material.columns.amount}" pattern="#" />"></td></c:if>
                                        <c:if test="${mode ne 'edit'}"><td><fmt:formatNumber value="${material.columns.amount}" pattern="#" /></td></c:if>
                                        <c:set value="${material.columns.amount - material.columns.stock}" var="diff"></c:set>
                                        <c:if test="${mode ne 'edit'}">
                                            <td>
                                                <c:if test="${diff > 0}">+</c:if>
                                                <fmt:formatNumber value="${diff}" pattern="#"/>
                                            </td>
                                        </c:if>
<%--                                        <c:if test="${user.userType ne '6' && user.userType ne '7'}">--%>
<%--                                            <td>${material.columns.cost_price}</td>--%>
<%--                                        </c:if>--%>
                                        <%--<td>${material.columns.bd_sale_price}</td>--%>
                                    </tr>
                                </c:forEach>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-inline layui-col-xs2">
                <label class="layui-form-label w-130">本次盘点数量：</label>
                <div class="layui-input-block "><div class="layui-form-mid layui-word-aux"><b class="totalAmount"><fmt:formatNumber value="${order.amount}" pattern="#"/></b></div></div>
            </div>
            <div class="layui-inline layui-col-xs2">
                <label class="layui-form-label w-130">盘亏/盘盈：</label>
                <div class="layui-input-block "><div class="layui-form-mid layui-word-aux"><b class="totalDiff">${order.differenceAmount > 0 ? '+' : ''}<fmt:formatNumber value="${order.differenceAmount}" pattern="#"/></b></div></div>
            </div>
                    <%--<div class="operate-footer" style="padding: 40px 0;">
                     </div>--%>
                    <c:if test="${mode eq 'edit' || mode eq 'audit'}" >
                        <div class="layui-inline layui-col-xs12 mt-5">
                            <label class="layui-form-label w-130">备注：</label>
                            <div class="layui-input-inline" style="width: 70%" >
                                <textarea name="reasonsForFailure" class="layui-textarea reasonsForFailure">${order.reasonsForFailure}</textarea>
                            </div>
                        </div>
                    </c:if>
           </div>
                <%--<div class="layui-tab-item licheng">
                    <ul class="layui-timeline" id="licheng">
                    </ul>
                </div>--%>

                <div class="layui-tab-item guocheng">
                    <ul>
                        <c:forEach var="msg" items="${msgs}">
                            <li><fmt:formatDate value="${msg.columns.operate_time}" pattern="yyy-MM-dd HH:mm:ss"/>&nbsp;&nbsp;&nbsp;

                                    ${msg.columns.operator} &nbsp;&nbsp;&nbsp;
                                <c:choose>
                                    <c:when test="${msg.columns.type eq '1'}">新增盘点单</c:when>
                                    <c:when test="${msg.columns.type eq '2'}">审批同意</c:when>
                                    <c:when test="${msg.columns.type eq '3'}">审批驳回</c:when>
                                    <c:when test="${msg.columns.type eq '4'}">重新提交审批</c:when>
                                    <c:when test="${msg.columns.type eq '5'}">删除盘点单</c:when>
                                </c:choose>${msg.columns.content}
                            </li>
                        </c:forEach>

                    </ul>
                </div>
            </div>
        </div>
        <div  class="openDivBottom">
            <c:if test="${7 != user.userType && 6!= user.userType}">
                <div class="layui-col-xs4">
                    提交人：${order.inventoryName}
                </div>
                <div class="layui-col-xs4">
                    所属部门：${order.departmentName}
                </div>
            </c:if>
            <div class="layui-col-xs4">
                申请时间：<fmt:formatDate value="${order.inventoryTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </div>
        </div>
        <div style="height: 20px"></div>
        <input type="hidden" name="taskId" id="taskId" value="${order.taskId}">
        <input type="hidden" id="processInstanceId" value="${order.processInstanceId}">
        <input type="hidden" id="status" value="${order.status}">

        <div class="layui-col-xs12 mb-20 pr-30 mt-20">
        </div>
        <div class="layui-form-item operate-footer" style="text-align: center;">
            <c:if test="${mode eq 'edit'}">
                <input type="button" lay-submit lay-filter="confirm" id="confirm" class="layui-btn " value="确认">
            </c:if>
            <c:if test="${mode eq 'audit'}">
                <button type="button" class="layui-btn" onclick="auditOrder('${order.id}')">同意</button>
                <button type="button" class="layui-btn" value="驳回" onclick="rejectOrder('${order.id}');">驳回</button>
            </c:if>
            <button type="button" class="layui-btn layui-btn-primary " onclick="closeDiv();">取消</button>
        </div>

    </div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/dist/viewer.js"></script>
<script type="text/javascript">
    var viewer = new Viewer(document.getElementById('LAY_app'));
    //初始数据
    var $form;
    var form;
    var upload;
    var $;

    var element;

    layui.use(['form', 'table', 'upload', 'jquery', 'element'], function () {
        $ = layui.jquery;
        form = layui.form;
        upload = layui.upload;
        $form = $('form');
        element = layui.element;
        var element = layui.element;
        element.on('tab(docDemoTabBrief)', function (data) {
            console.log(data);
            $('.layui-tab-content').eq(data.index).removeClass('layui-hide').siblings('.layui-tab-content').addClass('layui-hide');
           /* if(data.index==1){
                var htsks = $("#licheng").html();
                var len=$("#licheng li").length;

                if(len==0){
                    var processInstanceId=$("#processInstanceId").val();
                    var status=$("#status").val();
                    $.ajax({
                        type:"POST",
                        url:"${ctx}/set/process/getBpmnModel",
                        data:{
                            processInstanceId:processInstanceId,
                            status:status,
                        },
                        success:function(res){
                            console.log(res)
                            if(res.code=="200"){
                                var str=res.data;
                                var ht='';
                                for(var i=0;i<str.length;i++){
                                    var taski = str[i];
                                    console.log(taski);
                                    ht+='<li class="layui-timeline-item">';
                                    ht+='<i class="layui-icon layui-timeline-axis">&#xe63f;</i>';
                                    ht+='<div class="layui-timeline-content layui-text">';
                                    if(taski.status=='3'){
                                        ht+='<h3 class="layui-timeline-title fontColor1">'+taski.taskName+'</h3>'
                                        ht+='<p class="fontColor1">'+taski.approveUserName+'</p>';
                                    }else{
                                        ht+='<h3 class="layui-timeline-title">'+taski.taskName+'</h3>'
                                        ht+='<p>'+taski.approveUserName+'</p>';
                                    }
                                    ht+='</div>'
                                    ht+='</li>';
                                }

                                $("#licheng").html(ht);
                            }
                        },
                    }) ;
                }

            }*/

        });

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploader' //绑定元素
            , url: '${ctx}/common/uploadFile' //上传接口
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {

                });
            }
            , done: function (res) {
                console.log(res.path);
                //上传完毕回调
                addImg(res.path);
            }
            , error: function () {
                //请求异常回调
            }
        });

        function addImg(data){
            $("#uploader").hide();
            var html = '<div class="bj-img imgSpan"><span class="layui-icon-close layui-icon" onclick="delImg(this)"></span>';
            html += '<img src="${commonStaticImgPath}'+data+'" height="700" width="1200"/>';
            html += '<input type="hidden" class="imgPicker" value="'+data+'" /> </div>';
            $("#imgsDiv").append(html);
        }

        window.delImg = function(that){
            $("#uploader").show();
            $(that).parent().remove();
        }

        if ('${mode}' !== 'edit') {
            $('select').prop('disabled', true);
            form.render();
            $('input').prop('disabled', true).addClass('layui-bg-gray');
            $('textarea').prop('disabled', true).addClass('layui-bg-gray');
            $('textarea[name=reasonsForFailure]').prop('disabled', false).removeClass('layui-bg-gray');
        }

        // 监听盘点对象下拉选
        form.on('select(inventoryType)', function (data) {
            var old = $('.inventoryType').val();
            var inventoryType = data.value;
            if (parseInt(old) !== parseInt(inventoryType)) {
                $('#materialTable').empty();
                $('.totalAmount').text(0);
                $('.totalDiff').text(0);
            }
            $.ajaxSettings.async = false;
            $.post('${ctx}/warehouseSetting/findByType', {type: inventoryType}, function (result) {
                if (result.code === '200') {
                    var html = '<option value="">请选择</option>'
                    if (!isBlank(result.data)) {
                        for (var i = 0; i < result.data.length; i++) {
                            var selected = result.data.length == 1 ? 'selected' : '';
                            var warehouse = result.data[i];
                            html += '<option value="' + warehouse.id + '"' + selected + '>' + warehouse.name + '</option>';
                        }
                    }
                    $('#warehouseId').empty().append(html);
                    form.render('select');

                }
            });
            $.ajaxSettings.async = true;
            $('.inventoryType').val(data.value);
            var oldWarehouseId = $('.warehouseId').val();
            var currentWarehouseId = $('select[name=warehouseId]').val();
            if (oldWarehouseId.toString() !== currentWarehouseId.toString()) {
                $('#materialTable').empty();
                $('.totalAmount').text(0);
                $('.totalDiff').text(0);
            }
            $('.warehouseId').val(currentWarehouseId);
        });

        // 监听盘点仓库下拉选
        form.on('select(warehouseId)', function (data) {
            var old = $('.warehouseId').val();
            var warehouseId = data.value;
            if (old.toString() !== warehouseId.toString()) {
                $('#materialTable').empty();
                $('.totalAmount').text(0);
                $('.totalDiff').text(0);
            }
            $('.warehouseId').val(warehouseId);
        });


        form.verify({
            details: function(){
                if($('#materialTable>tr').length === 0){
                    return "请导入物料信息";
                }
            },
        });

        $(document).on('mouseenter', '#materialTable td', function(){
            var that = this;
            $(that).attr('title', $(that).text());
        });

        window.importMaterial = function(data){

            var html = "";
            for(var i=0; i<data.materialList.length; i++){
                html += "<tr data-id="+data.materialList[i].materialId+">";
                html += '<td>' + (i+1) + '</td>';
                html += '<td>' + data.materialList[i].code + '</td>';
                html += '<td>' + data.materialList[i].type + '</td>';
                // html += '<td>' + data.materialList[i].materialGroup + '</td>';
                html += '<td>' + data.materialList[i].unit + '</td>';
                html += '<td>' + data.materialList[i].description + '</td>';
                html += '<td>' + data.materialList[i].stocks + '</td>';
                html += '<td><input type="text" class="layui-input amount" value="' + data.materialList[i].amount + '"></td>';
                html += '</tr>';
            }

            $('#materialTable').empty().append(html);
            $('.totalAmount').text(data.totalAmount);
            $('.totalDiff').text(data.totalDiff);
        };

        $(document).on('change keyup', '.amount', function () {
            var val = $(this).val();
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(val)) {
                //layer.msg("数量必须是整数", {icon:2});
                return;
            }
            if (parseFloat(val).toFixed(2) < 0.00) {
                //layer.msg('数量不能小于0', {icon: 2});
                return;
            }
            var totalAmount = 0;
            var totalStocks = 0;
            $('#materialTable>tr').each(function(){
                var stocks = $(this).find('td').eq(5).text();
                var amount = $(this).find('td').eq(6).find('.amount').val();
                totalAmount = totalAmount + parseInt(amount);
                totalStocks = totalStocks + parseInt(stocks);
            });
            $('.totalAmount').text(totalAmount);
            var diff = totalAmount-totalStocks;
            if (diff > 0) {
                $('.totalDiff').text("+"+diff);
            } else {
                $('.totalDiff').text(diff);
            }
        });


        $('#importPlan').click(function(){
            var warehouseId = $('select[name=warehouseId]').val();
            if (isBlank(warehouseId)) {
                layer.msg('请先选择盘点仓库');
                return;
            }
            parent.layer.open({
                title: '导入物料',
                type: 2,
                area: ['550px', '300px'],
                content: '${ctx}/inventory/toImportMaterialForm?warehouseId=' + warehouseId
            });
        });

        var saveFlag = true;
        form.on('submit(confirm)', function(data){
            if(!saveFlag){
                return;
            }
            var order = {};
            order.id = '${order.id}';
            order.inventoryType = data.field.inventoryType;
            order.warehouseId = data.field.warehouseId;
            order.remarks = data.field.remarks;
            order.img = $('.imgPicker').val();

            var arr = [];
            var checkFlag = false;
            $('#materialTable>tr').each(function(){
                var material = {};
                material.materialId = $(this).attr("data-id");
                var amount = $(this).find('td').eq(6).find('.amount').val();
                if (!/^[0-9]+(.[0-9]{1,2})?$/.test(amount)) {
                    layer.msg("数量格式不正确", {icon:2});
                    checkFlag = true;
                    return;
                }
                if (parseFloat(amount).toFixed(2) < 0.00) {
                    layer.msg('数量不能小于0', {icon: 2});
                    checkFlag = true;
                    return;
                }
                material.costPrice = $(this).find('td').eq(7).text();;
                material.bdSalePrice = $(this).find('td').eq(8).text();;
                material.amount = amount;
                arr.push(material);
            });
            if (checkFlag) {
                return;
            }
            order.details = arr;
            console.log(order);
            saveFlag = false;
            $.ajax({
                url:'${ctx}/inventory/saveInventOrder',
                method:'post',
                contentType: 'application/json',
                data:JSON.stringify(order),
                dataType:'JSON',
                success:function(res){
                    if(res.code=="200"){
                        parent.layer.msg("保存成功",{time:1000});
                        closeDiv();
                        parent.table.reload('test');
                    } else if(res.code=="501") {
                        layer.msg(res.errMsg,{time:1500},function (){
                            saveFlag = true;
                        });
                    } else if(res.code == '422'){
                        layer.msg(res.msg,{time:1500},function(){
                            saveFlag = true;
                        });
                    } else{
                        layer.msg("保存失败",{time:1000});
                        saveFlag = true;
                    }
                },
                complete: function(){

                }
            }) ;
        });



        $(document).on('click','.hx_del',function(){
            $(this).parent('li').remove();
        });

    })

    var fg=false;
    function auditOrder(id) {
        if(fg){
            return false;
        }
        var content = $('textarea[name=reasonsForFailure]').val();
        fg=true;
        $.post('${ctx}/inventory/firstAudit', {id: id,content:content}, function(result) {
            if (result.code === '200') {
                parent.layer.msg("操作成功",{time:1000});
                closeDiv();
                parent.table.reload('test');
            } else {
                layer.msg('操作失败！' + result.errMsg, {time: 1000});
                fg=false;
            }
        });
    }

    function rejectOrder(id) {
        var reason = $('textarea[name=reasonsForFailure]').val();
        if (isBlank(reason)) {
            layer.msg('请输入备注', {icon: 5, anim: 6});
            return;
        }
        $.post('${ctx}/inventory/reject', {id: id, reason: reason}, function (result) {
            if (result.code === '200') {
                parent.layer.msg("操作成功",{time:1000});
                closeDiv();
                parent.table.reload('test');
            } else {
                layer.msg('操作失败！' + result.errMsg, {time: 1000});
            }
        });
    }

    function  closeDiv() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);
    }

    function isBlank(val) {
        if (val == null || val == '' || val == undefined) {
            return true;
        }
        return false;
    }

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