<%@ 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">
    <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}
        .layui-textarea {
            min-height: 50px;
        }
        .hx_td{
            width: 100px;
        }
        .w-160{
            width: 160px;
        }
    </style>
</head>
<body>
<div class="aaa">
    <div class="layui-form">
        <div class="layui-card-body pt-20 pb-40 h-350" action="" id="detailSet">
            <input hidden name="id" value="${order.columns.id}">

            <div class="layui-col-xs12 pr-30 mt-10">

                <div class="layui-col-xs4 pr-30">
                    <label class="layui-form-label w-130"><i class="red">*</i>供应商：</label>
                    <div class="layui-input-block">
                        <select name="supplierId" id="supplierId" lay-filter="supplierId" lay-verify="required" lay-search>
                            <option value="">请选择</option>
                            <c:forEach var="supply" items="${supplyList}">
                                <option value="${supply.columns.id}" <c:if test="${order.columns.supply_id == supply.columns.id}">selected</c:if> >${supply.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-col-xs4 pr-30">
                    <label class="layui-form-label w-130"><i class="red">*</i>入库仓库：</label>
                    <div class="layui-input-block" >
                        <select name="inWarehouseId" lay-verify="required" lay-filter="inWarehouseId" lay-search>
                            <option value="">请选择</option>
                            <c:forEach var="warehouse" items="${warehouseList}">
                                <option value="${warehouse.columns.id}" data-address="${warehouse.columns.warehouseAddress}" data-charge="${warehouse.columns.person_in_charge}"
                                        data-mobile="${warehouse.columns.mobile}" <c:if test="${order.columns.in_warehouse_id == warehouse.columns.id}">selected</c:if> >${warehouse.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>

                <div class="layui-col-xs4 pr-30">
                    <label class="layui-form-label w-130">接货人：</label>
                    <div class="layui-input-block">
                        <input type="text" id="personInCharge" value="${order.columns.person_in_charge}" lay-verify="required" autocomplete="off" readonly class="layui-input layui-bg-gray">
                    </div>
                </div>

            </div>

            <div class="layui-col-xs12 pr-30 mt-10">

                <div class="layui-col-xs4">
                    <label class="layui-form-label  w-130">联系电话：</label>
                    <div class="layui-input-block" >
                        <input type="text" id="mobile" value="${order.columns.deliverMobile}" lay-verify="required" autocomplete="off" readonly class="layui-input layui-bg-gray">
                    </div>
                </div>
                <div class="layui-col-xs8">
                    <label class="layui-form-label w-130">仓库地址：</label>
                    <div class="layui-input-block" >
                        <input type="text" id="address" value="${order.columns.warehouseAddress}" lay-verify="required" autocomplete="off" readonly class="layui-input layui-bg-gray">
                    </div>
                </div>
            </div>
            <div class="layui-col-xs12 pr-30 mt-10">
                <div class="ayui-col-xs12">
                    <label class="layui-form-label w-130">订单备注：</label>
                    <div class="layui-input-block hx_l" >
                        <textarea name="remarks" class="layui-textarea" value="">${order.columns.remarks}</textarea>
                    </div>
                </div>


            </div>

            <input type="hidden" name="details" lay-verify="details">


            <div class="layui-col-xs12 pr-30 mt-20 mb-10">

                <div class="layui-inline layui-col-xs5">
                    <label class="layui-form-label">物料代码：</label>
                    <div class="layui-input-block">
                        <div id="code"></div>
                    </div>
                </div>
                    <div class="layui-inline layui-col-xs2">
                        <label class="layui-form-label w-80"></label>
                    <input type="button" class="layui-btn layui-btn-sm" id="importPlan" value="批量导入"/>
                    </div>
                </div>

            <div class="layui-col-xs12 mb-20 pr-30">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th class="w-160">物料代码</th>
                        <th>物料名称</th>
                        <th>物料类型</th>
                        <th>物料品牌</th>
                        <th>物料规格</th>
                        <th class="hx_td">采购数量</th>
                        <th class="hx_td">采购单价</th>
                        <th class="hx_td">销售价</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="materialTable">
                    <c:forEach items="${details}" var="detail" varStatus="vs">
                        <tr data-id="${detail.columns.material_id}">
                            <td>${vs.count}</td>
                            <td>${detail.columns.code}</td>
                            <td>${detail.columns.material_name}</td>
                            <td>${detail.columns.material_type}</td>
                            <td>${detail.columns.material_brand}</td>
                            <td>${detail.columns.material_spec}</td>
                            <td><input class="layui-input changeInput" name="applyAmount" onchange="appendTotal()"
                                       value="${detail.columns.apply_amount}"></td>
                            <td><input class="layui-input changeInput" name="purchasePrice"
                                       lay-data="${detail.columns.coefficient}" onchange="appendTotal()"
                                       onkeyup="getSalesPrice(this)" value="${detail.columns.purchase_price}"></td>
                            <td class="salesPrice">${detail.columns.sales_price}</td>
                            <td>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger"
                                        onclick="del(this)">删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>

                    </tbody>
                </table>
            </div>
        </div>
        <div class="layui-row">
            <div class="layui-form-mid layui-word-aux" style="color: #D9B589 !important;margin-left: 20px"><span>采购总额：</span><span class="red totalAmount">${total}</span>元</div>
        </div>
        <div class="layui-form-item operate-footer" style="text-align: center;">
            <input type="button" lay-submit lay-filter="confirm" id="confirm" class="layui-btn " value="确认">
            <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/xm-select.js"></script>
<script type="text/javascript">
    //初始数据
    var $form;
    var form;
    var upload;
    var $;
    var imgs='';
    var myreg=/^\d+(\.\d{1,2})?$/;
    var type='${type}';
    layui.use(['form', 'table', 'upload', 'jquery'], function () {
        $ = layui.jquery;
        form = layui.form;
        upload = layui.upload;
        $form = $('form');

     /*   form.on('select(supplyId)', function (d) {
            var $select = $('select[name=inWarehouseId]');
            $select.empty();
            if (!isBlank(d.value)) {
                $.ajax({
                    type: 'post',
                    url: '${ctx}/warehouseSetting/findWarehouseByAscriptionId',
                    async: false,
                    data: {
                        id: d.value
                    },
                    dataType: 'json',
                    success: function(data){
                        var html = '<option value="">请选择</option>';
                        for (var i = 0; i < data.length; i++) {
                            html += '<option value="' + data[i].columns.id + '" data-address="'+data[i].columns.warehouseAddress+'"' +
                                ' data-charge="'+data[i].columns.person_in_charge+'" data-mobile="'+data[i].columns.mobile+'">' + data[i].columns.name + '</option>';
                        }
                        $select.append(html);
                    }
                });
            }
            form.render();
        });*/

        form.on('select(inWarehouseId)',function(data){
            var obj = $(data.elem).find("option:selected")
            if(!isBlank(obj)){
               var personInCharge=obj.attr("data-charge");
                $("#personInCharge").val(personInCharge);
                var mobile=obj.attr("data-mobile");
                $("#mobile").val(mobile);
                var address=obj.attr("data-address");
                $("#address").val(address);
            }
        })


        form.on('select(supplierId)',function(data){
              $("#materialTable").html("");
        })


        var codeXm = xmSelect.render({
            el: '#code',
            name: 'code',
            radio: true,
            tips: '请输入查询',
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                searchVal(val, cb, {
                    code: val,
                    supplierId: $('#supplierId').val()
                }, 'code');
            },
            on: function (data) {
                if (data.isAdd && data.arr.length > 0) {
                    appendTr(data);
                }
            }
        });

        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(result){
            var data=result.materialList;
            var html = "";
            var allAmount=0;
            for(var i=0; i<data.length; i++){
                html += "<tr data-id="+data[i].materialId+">";
                html += '<td>' + (i+1) + '</td>';
                html += '<td>' + data[i].code + '</td>';
                html += '<td>' + data[i].materialName + '</td>';
                html += '<td>' + data[i].materialType + '</td>';
                html += '<td>' + data[i].materialBrand + '</td>';
                html += '<td>' + data[i].materialSpec + '</td>';
                html += '<td>' + data[i].applyAmount + '</td>';
                html += '<td>' + data[i].purchasePrice + '</td>';
                html += '<td>' + data[i].salesPrice + '</td>';
                html += '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>';
                html += "</tr>";
                allAmount=allAmount+data[i].applyAmount*data[i].purchasePrice;
            }

            $('#materialTable').empty().append(html);
            appendTotal();
        }


        $('#importPlan').click(function(){
            parent.layer.open({
                title: '导入物料',
                type: 2,
                area: ['550px', '300px'],
                content: '${ctx}/supplyOrder/purchaseAudit/toImportMaterialForm'
            });

        });


        function appendTr(data) {
            var d = data.arr[0].origin;
            var html = '<tr data-id="' + d.id + '" >'
                + '<td ></td>'
                + '<td>' + d.code + '</td>'
                + '<td>' + d.material_name + '</td>'
                + '<td>' + d.material_type + '</td>'
                + '<td>' + d.material_brand + '</td>'
                + '<td>' + d.material_specs + '</td>';
            html += `<td> <input type="text" class="layui-input changeInput" onchange="appendTotal()"  name="applyAmount" lay-verify="required" width="80px;" /></td>
               <td><input type="text" class="layui-input changeInput" lay-data="` + d.coefficient + `" onchange="appendTotal()" onkeyup="getSalesPrice(this)" name="purchasePrice" lay-verify="required" width="80px;" /></td>
               <td class="salesPrice"></td>
    <td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td> `
            html += '</tr>';
            var $trs = $('#materialTable>tr');
            var exist = false;
            for (var i = 0; i < $trs.length; i++) {
                var $tr = $trs.eq(i);
                var id = $tr.find('td:first').data('id');
                if (id === d.id) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                $('#materialTable').append(html);
            } else {
                layer.msg('物料/BOM已存在');
            }
            appendSort();
            data.arr.length = 0;
            codeXm.reset();

        }

        window.del = function(obj){
            $(obj).closest('tr').remove();
            appendTotal();
        }


        function searchVal(val, cb, searchData, filed) {
            if (!isBlank(val)) {
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/findMaterialByCode?materialProperties=1',
                    data: searchData,
                    async: false,
                    dataType: 'json',
                    success: function (d) {
                        console.log(d)
                        var arr = [];
                        for (var i = 0; i < d.length; i++) {
                            var data = {};
                            data.name = d[i].columns[filed];
                            data.value = d[i].columns.id;
                            data.origin = d[i].columns;
                            data.xs = d[i].columns.coefficient;
                            arr.push(data);
                        }
                        cb(arr);
                    }
                });
            } else {
                cb([]);
            }
        }


        function appendSort() {
            $('#materialTable>tr').each(function (i) {
                $(this).find('td:first').html(i + 1);
            });
        }

        var saveFlag = true;
        form.on('submit(confirm)', function(data){
            if(!saveFlag){
                return;
            }
            var bom = {};
            bom.id=data.field.id;
            bom.supplierId = data.field.supplierId;
            bom.inWarehouseId = data.field.inWarehouseId;
            bom.remark = data.field.remarks;
          /*  bom.id=data.field.id;
            bom.updateReason=data.field.updateReason;
            bom.model=data.field.model;*/
            var arr = [];
            var checkFlag = false;
            $('#materialTable>tr').each(function(index){
                var material = {};
                material.materialId = $(this).attr("data-id");
                if(isBlank(material.materialId)){
                    layer.msg("第"+(index+1)+"行，物料不能为空!", {icon:2});
                    checkFlag = true;
                    return;
                }
                material.applyAmount = $(this).find('td').eq(6).find("input").val();
                if(isBlank(material.applyAmount)){
                    material.applyAmount = $(this).find('td').eq(6).text();
                }
                if (!myreg.test(material.applyAmount)) {
                    layer.msg("第"+(index+1)+"行，采购数量格式不正确", {icon:2});
                    checkFlag = true;
                    return;
                }
                material.materialCode=$(this).find('td').eq(1).text();
                material.materialType=$(this).find('td').eq(3).text();

                material.purchasePrice = $(this).find('td').eq(7).text();
                if(isBlank(material.purchasePrice)){
                    material.purchasePrice = $(this).find('td').eq(7).find("input").val();
                }
                if(isBlank(material.purchasePrice)){
                    layer.msg("第"+(index+1)+"行，采购单价不能为空!", {icon:2});
                    checkFlag = true;
                    return;
                }
                if (!myreg.test(material.purchasePrice)) {
                    layer.msg("第"+(index+1)+"行，采购单价格式不正确", {icon:2});
                    checkFlag = true;
                    return;
                }
                material.salesPrice = $(this).find('td').eq(8).text();
               /* if(isBlank(material.salesPrice)){
                    material.salesPrice = $(this).find('td').eq(8).find("input").val();
                }*/
                if(isBlank(material.salesPrice)){
                    layer.msg("第"+(index+1)+"行，销售单价不能为空!", {icon:2});
                    checkFlag = true;
                    return;
                }
                if (!myreg.test(material.salesPrice)) {
                    layer.msg("第"+(index+1)+"行，销售单价格式不正确", {icon:2});
                    checkFlag = true;
                    return;
                }
                material.materialSpec=$(this).find('td').eq(5).text();
                arr.push(material);
            });
            if(checkFlag){
                return;
            }
            bom.details = arr;
            saveFlag = false;
            $.ajax({
                url:'${ctx}/supplyOrder/purchaseAudit/savePurchaseOrder',
                method:'post',
                contentType: 'application/json',
                data:JSON.stringify(bom),
                dataType:'JSON',
                success:function(res){
                    if(res.code=="200"){
                        parent.layer.msg("保存成功",{time:2000});
                        closeDiv();
                        parent.reload();
                    } else if(res.code=="501") {
                        layer.msg(res.errMsg,{time:2400},function (){
                            saveFlag = true;
                        });
                    } else if(res.code == '422'){
                        layer.msg(res.errMsg,{time:2500},function(){
                            saveFlag = true;
                        });
                    } else{
                        layer.msg("保存失败",{time:2000});
                        saveFlag = true;
                    }
                },
                complete: function(){

                }
            }) ;
        });



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

    })


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

    function appendTotal(){
        var totalAmount=0;
        $('#materialTable>tr').each(function (i) {
            var price = $(this).find("input[name='purchasePrice']").val();
            if(isBlank(price)){
                price=$(this).find("td").eq(7).text();
            }else{
                if(!myreg.test(price)){
                    layer.msg("第"+(i+1)+"行，单价格式不正确，保留2位小数", {icon:2});
                    return;
                }

            }
            var num =  $(this).find("input[name='applyAmount']").val();
            if(isBlank(num)){
                num=$(this).find("td").eq(6).text();
            }else{
                if(!myreg.test(num)){
                    layer.msg("第"+(i+1)+"行，数量格式不正确，保留2位小数", {icon:2});
                    return;
                }
            }
            if (!isNaN(price) && !isNaN(num)) {
                totalAmount = totalAmount + (price * num);
            }
        });
        var tem = parseFloat(totalAmount).toFixed(2)
        $(".totalAmount").text(tem);
    }

    function getSalesPrice(that) {
        var total = 0.00;
        var xs = $(that).attr("lay-data");
        if (isBlank(xs)) {
            layer.msg("请设置零售价系数！", {icon: 3});
            return;
        }
        var purchasePrice = $(that).val();
        if (purchasePrice.endsWith(".")) {
            return;
        }
        if (!isBlank(purchasePrice) && !myreg.test(purchasePrice)) {
            layer.msg("请输入有效的采购单价！", {icon: 3});
            return;
        }
        total = purchasePrice * xs;
        console.log('*****' + total);
        $(that).parent("td").next("td").text(total.toFixed(2));
    }


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

