<!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">
  <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="../../layuiadmin/style/admin.css" media="all">
  <link rel="stylesheet" href="../../jquery-easyui-1.5.2/themes/icon.css" type="text/css">
   <style type="text/css">
        .table-overlay .layui-table-view,
        .table-overlay .layui-table-header,
        .table-overlay .layui-table-box,
        .table-overlay .layui-table-body{overflow: visible;}
        .table-overlay .layui-table-cell{height: auto; overflow: visible;}
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body" pad15>
            <form class="layui-form" action="" lay-filter="component-form-element">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-xs6 layui-col-sm4">
                        <label class="layui-form-label"><font color='red' size="4">*</font>仓别：</label>
                        <div class="layui-input-block">
                            <select id="id_warehouse" name="warehouse" lay-verify="required">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-xs6 layui-col-sm4">
                        <label class="layui-form-label"><font color='red' size="4">*</font>供应商：</label>
                        <div class="layui-input-block">
                            <select id="id_supplier" name="supplier" lay-verify="required" lay-search>
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-xs6 layui-col-sm4">
                        <label class="layui-form-label">备注：</label>
                        <div class="layui-input-block">
                            <input id="notes" name="notes" class="layui-input" autocomplete="off"/>
                        </div>
                    </div>
                </div>
            <fieldset class="layui-elem-field layui-field-title">
                <legend>原料明细&nbsp;&nbsp;<button type="button" id="material-btn-add" class="layui-btn layui-btn-primary layui-btn-sm"><i class="layui-icon"></i></button></legend>
            </fieldset>

            <div class="layui-row layui-col-space10">
                <div id="materialDataTable" class="table-overlay">
				    <table id="material_layTable" lay-filter="material_layTable" class="layui-hide"></table>
			    </div>
            </div>
                <button class="layui-btn" id="material-godownentry-submit" lay-submit lay-filter="component-form-element" style="display: none">确定</button>
        </form>
        </div>
    </div>
</div>

<script src="../../jquery-easyui-1.5.2/jquery.min.js"></script>
<script src="../../layuiadmin/layui/layui.js"></script>
<script>
layui.config({
    base: '../../../layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'form', 'utils', 'table', 'laydate'], function() {
    var $ = layui.$;
    var utils = layui.utils;
    var admin = layui.admin;
    var form = layui.form;
    var table = layui.table;
    var id = layui.view.getParameterByName('id');
    var order_id = layui.view.getParameterByName('order_id');

    var supplier_isload = false;
    var warehouse_isload = false;
    var data_isload = false;

    admin.req({
        url: '/supplier/supplier/select/?type=0',
        done: function (res) {
            var data = res.data;
            var supplier_node = $('#id_supplier');
            for (var i in data) {
                var pid = data[i].id;
                var value = data[i].value;
                supplier_node.append("<option value='" + pid + "'>" + value + "</option>");
            }
            form.render();
            supplier_isload = true;
            loadData(); // 赋值完成后调用传值
        }
    });


    admin.req({
      url: '/warehouse/select/?type=0',
      done: function(res){
        var data = res.data;
        var warehouse_node = $('#id_warehouse');
        for (var i in data) {
            var pid = data[i].id;
            var value = data[i].value;
            warehouse_node.append("<option value='"+pid+"'>"+value+"</option>");
        }
        form.render();
        warehouse_isload = true;
        loadData();// 赋值完成后调用传值
     }
    });

       var loadData = function () {
        if (!(warehouse_isload && supplier_isload)) { // 要等下拉框渲染完成后才能赋值
            return;
        }
        if (data_isload) {
            return;
        }
        data_isload = true;

        if (id) {
            var data = JSON.parse(JSON.stringify(parent.layui.table.editdata));
            form.val("component-form-element", data);
            admin.req({
                url: '/purchase/godownentry/detail/?id=' + id,
                done: function (res) {
                    var items_data = res.data.items_data;
                    var roldData = table.cache[material_layTable];

                    for (var i in items_data) {
                        var newRow = {
                            id: items_data[i].product_base_id,
                            name: items_data[i].product_base_name,
                            model: items_data[i].product_base_model,
                            price: items_data[i].price,
                            count: items_data[i].count,
                            amount: items_data[i].invoice_amount,
                            unit: items_data[i].unit,
                            notes: items_data[i].notes
                        };
                        roldData.push(newRow);
                    }
                    material_tableIns.reload({
                        data: roldData
                    })
                }
            })

        }

        if (order_id) {
            var data = JSON.parse(JSON.stringify(parent.layui.table.editdata));
            form.val("component-form-element", data);
            admin.req({
                url: '/purchase/purchase_order/detail/?id=' + order_id,
                done: function (res) {
                    var items_data = res.data.items_data;
                    var roldData = table.cache[material_layTable];

                    for (var i in items_data) {
                        var newRow = {
                            id: items_data[i].product_id,
                            name: items_data[i].name,
                            model: items_data[i].model,
                            price: items_data[i].price,
                            count: items_data[i].count,
                            amount: items_data[i].amount,
                            unit: items_data[i].unit,
                            notes: ''
                        };
                        roldData.push(newRow);
                    }
                    material_tableIns.reload({
                        data: roldData
                    })
                }
            })

        }

    };

    var material_tbWidth = $("#materialDataTable").width();
    var material_layTable = "material_layTable";
    var material_tableIns = table.render({
        elem: '#material_layTable',
        id: material_layTable,
        data: [],
        width: material_tbWidth,
        page: false,
        limit: 1000,
        loading: true,
        even: true, //不开启隔行背景
        cols: [[
            {title: '序号', type: 'numbers'},
            {field: 'name', title: '原料名称', width: 100},
            {field: 'model', title: '原料代码', width: 100},
            {field: 'count', title: '数量', width: 100, templet: function (d) {

                    return '<input id="count' + d.id + '" value="' + d.count + '" type="text" lay-event="onNumberChange" lay-verify="required|numberGtZ" autocomplete="off" class="layui-input">';

                }},
            {field: 'unit', title: '单位', width: 120},
            {field: 'price', title: '单价', width: 100, templet: function (d) {

                    return '<input id="price' + d.id + '" value="' + d.price + '" type="text" lay-event="onNumberChange" lay-verify="required|numberGeZ" autocomplete="off" class="layui-input">';

                }},
           {field: 'amount', title: '发票金额', width: 120, templet: function (d) {

                    return '<input id="amount' + d.id + '" value="' + d.amount + '" type="text" lay-event="onAmountChange" lay-verify="required|numberGeZ" autocomplete="off" class="layui-input">';

                }},
            {field: 'notes', title: '备注', width: 200, templet: function (d) {

                    return '<input id="notes' + d.id + '" value="' + d.notes + '" type="text"  autocomplete="off" class="layui-input">';

                }},
            {
                field: 'id', title: '操作', minWidth: 120, templet: function (d) {
                    return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="' + d.id + '"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                }
            }
        ]],
        done: function (res, curr, count) {
            //viewObj.tbData = res.data;
        }
    });


//定义事件集合
		var active = {
            numberChange: function(obj){
			    var oldData = table.cache[material_layTable];
			    for (var i in oldData){
			        var count = $('#count'+oldData[i].id).val();
			        var price = $('#price'+oldData[i].id).val();
			        var amount = $('#amount'+oldData[i].id).val();
			        price = isNaN(price) ? 0 : price
			        count = isNaN(count) ? 0 : count
			        amount = isNaN(amount) ? 0 : amount

                    oldData[i].amount = amount > 0 ? amount : (price * count).toFixed(2)
                    oldData[i].count = count
                    oldData[i].price = price
                    //$.extend(oldData[i], obj);
                }
                if(oldData[i].amount < 0){
                    oldData[i].amount  = ''
                    layer.msg('总金额小于0，请重新操作');
                }

                material_tableIns.reload({
					data : oldData
				});
            },
            amountChange: function(obj){
			    var oldData = table.cache[material_layTable];
			    for (var i in oldData){
			        var count = $('#count'+oldData[i].id).val();
			        var amount = $('#amount'+oldData[i].id).val();

			        count = isNaN(count) ? 1 : count
			        amount = isNaN(amount) ? 0 : amount

                    oldData[i].amount = amount
                    oldData[i].price = (amount / count).toFixed(2)
                    //$.extend(oldData[i], obj);
                }
                if(oldData[i].amount < 0){
                    oldData[i].amount   = ''
                    layer.msg('总金额小于0，请重新操作');
                }

                material_tableIns.reload({
					data : oldData
				});
            }
		}
		//激活事件
		var activeByType = function (type, arg) {
			if(arguments.length === 2){
				active[type] ? active[type].call(this, arg) : '';
			}else{
				active[type] ? active[type].call(this) : '';
			}
		}


    table.on('tool(material_layTable)', function (obj) {
        var data = obj.data;
        var event = obj.event;
        var tr = obj.tr;
        switch (event) {
            case "del":
                obj.del();
                layer.msg('删除成功', {icon: 6});
                break;
            case "onNumberChange":
                tr.find('.layui-input').focusout(function () {
                    activeByType('numberChange',obj.data);	//更新行记录对象
                })
                break;
            case "onAmountChange":
                tr.find('.layui-input').focusout(function () {
                    activeByType('amountChange',obj.data);	//更新行记录对象
                })
                break;
        }
    });


    var getMaterialData = function () {
        var rows = table.cache[material_layTable];
        var data = [];
        for (var n in rows) {
            if (rows[n] == false) {
                continue;
            }
            var count = $('#count'+rows[n].id).val();
            var price = $('#price'+rows[n].id).val();
            var notes = $('#notes'+rows[n].id).val();
            var amount = $('#amount'+rows[n].id).val();

            var item = {
                product_base: rows[n].id,
                id: rows[n].id,
                name: rows[n].name,
                model: rows[n].model,
                count: count,
                price: price,
                invoice_amount: amount,
                notes: notes
            };
            data.push(item);
        }
        return data;
    };
    form.on('submit(component-form-element)', function (data) {
        var items = getMaterialData();
        if (items.length == 0) {
            layer.msg('请添加原料！', {icon: 5});
            return false;
        }
        if(order_id){
            data.field.purchase_order = order_id
        }
        admin.req({
            url: '/purchase/godownentry/save/?type=0&id=' + id
            , data: {main: JSON.stringify(data.field), item: JSON.stringify(items)}
            , type: 'post'
            , done: function (res) {
                parent.layui.onSubmitChild(res.data);
            }
        });
        return false;
    });

    $('#material-btn-add').on('click', function () {
        layer.open({
            type: 2,
            title: '添加原料',
            area: ['90%', '98%'],
            btn: ['确定', '取消'],
            yes: function (index, dom) {
                layui.onSubmitChild = function (data) {
                    if(data.length > 0) {
                    layer.msg('添加成功！', {icon: 6});
                } else {
                        layer.msg('请先选择记录！');
                    }
                    // layer.close(index);
                    var oldData = getMaterialData();
                    for (var i in data) {
                        var is_exit = false;
                        for (var m in oldData) {
                            if (oldData[m].id == data[i].product_id) {
                                is_exit = true;
                                break;
                            }
                        }

                        if (is_exit) {
                            continue;
                        }
                        var newRow = {
                            id: data[i].product_id,
                            name: data[i].name,
                            model: data[i].model,
                            unit: data[i].unit,
                            count:'',
                            price:'',
                            amount:'',
                            notes:''
                        };
                        oldData.push(newRow);
                    }

                    material_tableIns.reload({
                        data: oldData
                    });

                };
                layui.submitChild();
            },
            btn2: function (index, layero) {
                layer.close(index);//关闭当前按钮
            },
            content: '../material/search_material_item.html'
        });
    });

    parent.layui.submitChild = function () {
      $("#material-godownentry-submit").click();
    };

})
  </script>
</body>
</html>