<!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-sm6">
                        <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-sm6">
                        <label class="layui-form-label">备注：</label>
                        <div class="layui-input-block">
                            <input id="notes" type="text" name="notes" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            <fieldset class="layui-elem-field layui-field-title">
                <legend>成品明细&nbsp;&nbsp;<button type="button" id="goods-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="goodsDataTable" class="table-overlay">
				    <table id="goods_layTable" lay-filter="goods_layTable" class="layui-hide"></table>
			    </div>
            </div>
                <button class="layui-btn" id="goods-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', 'table', 'laydate', 'utils'], function() {
    var $ = layui.$;
    var admin = layui.admin;
    var form = layui.form;
    var utils = layui.utils;
    var table = layui.table;
    var id = layui.view.getParameterByName('id');

    var warehouse_isload = false;
    var data_isload = false;

    admin.req({
      url: '/warehouse/select/?type=2',
      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)) { // 要等下拉框渲染完成后才能赋值
            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: '/goods/godownentry/detail/?id=' + id,
                done: function (res) {
                    var items_data = res.data.items_data;
                    var roldData = table.cache[goods_layTable];

                    for (var i in items_data) {
                        var newRow = {
                            id: items_data[i].goods_id,
                            name: items_data[i].goods_name,
                            model: items_data[i].goods_model,
                            unit: items_data[i].unit,
                            price: items_data[i].price,
                            count: items_data[i].count,
                            amount: items_data[i].invoice_amount,
                            notes: items_data[i].notes
                        };
                        roldData.push(newRow);
                    }
                    goods_tableIns.reload({
                        data: roldData
                    })
                }
            })

        }
    }

    var goods_tbWidth = $("#goodsDataTable").width();
    var goods_layTable = "goods_layTable";
    var goods_tableIns = table.render({
        elem: '#goods_layTable',
        id: goods_layTable,
        data: [],
        width: goods_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: 130, 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: 100, 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>';
                }
            }
        ]]
        , height: 'full-210'
        ,done: function (res, curr, count) {
            //viewObj.tbData = res.data;
        }
    });

		//定义事件集合
		var active = {
            numberChange: function(obj){
			    var oldData = table.cache[goods_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，请重新操作');
                }

                goods_tableIns.reload({
					data : oldData
				});
            },
            amountChange: function(obj){
			    var oldData = table.cache[goods_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，请重新操作');
                }

                goods_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(goods_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 getGoodsData = function () {
        var rows = table.cache[goods_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 = {
                goods: rows[n].id,
                id: rows[n].id,
                name: rows[n].name,
                model: rows[n].model,
                unit: rows[n].unit,
                count: count,
                price: price,
                invoice_amount: amount,
                notes: notes
            };
            data.push(item);
        }
        return data;
    };
    form.on('submit(component-form-element)', function (data) {
        var items = getGoodsData();
        if (items.length == 0) {
            layer.msg('请添加成品！', {icon: 5});
            return false;
        }
        admin.req({
            url: '/goods/godownentry/save/?id=' + id
            , data: {main: JSON.stringify(data.field), item: JSON.stringify(items)}
            , type: 'post'
            , done: function (res) {
                parent.layui.onSubmitChild(res.data);
            }
        });
        return false;
    });

    $('#goods-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 = getGoodsData();
                    for (var i in data) {
                        var is_exit = false;
                        for (var m in oldData) {
                            if (oldData[m].id == data[i].id) {
                                is_exit = true;
                                break;
                            }
                        }

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

                    goods_tableIns.reload({
                        data: oldData
                    });

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

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

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