<!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" lay-filter="onWarehouseChange">
                                <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-filter="onSupplierChange" 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 godownentry_detail_id = layui.view.getParameterByName('godownentry_detail_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_return/detail/?id=' + id,
                done: function (res) {
                    var items_data = res.data.items_data;
                    var roldData = getMaterialData();
                    var k = 0;
                    if (roldData.length > 0){
                        var k = roldData[roldData.length-1].id;
                    }
                    for (var i in items_data) {
                        k = k + 1;
                        var newRow = {
                            id: k,
                            product_base: items_data[i].product_base_id,
                            name: items_data[i].product_base_name,
                            model: items_data[i].product_base_model,
                            unit: items_data[i].unit,
                            total_cost: 0,
                            count: items_data[i].count,
                            amount: items_data[i].amount,
                            godownentry_detail: items_data[i].godownentry_detail,
                            notes: items_data[i].notes,
                            record_data: items_data[i].record_data
                        };
                        roldData.push(newRow);
                    }
                    material_tableIns.reload({
                        data: roldData
                    });
                    batchUpdateCost()
                }
            })

        }

        if(godownentry_detail_id){
            admin.req({
                url:'/purchase/get_godownentry_detail_data/?id='+godownentry_detail_id,
                done: function (res) {
                    var main_data = res.data.main;
                    var items_data = res.data.items;
                    form.val("component-form-element", JSON.parse(JSON.stringify(main_data)));
                    var roldData = getMaterialData();
                    var k = 0;
                    if (roldData.length > 0){
                        var k = roldData[roldData.length-1].id;
                    }
                    for (var i in items_data) {
                        k = k + 1;
                        var newRow = {
                            id: k,
                            product_base: items_data[i].product_base_id,
                            name: items_data[i].product_base_name,
                            model: items_data[i].product_base_model,
                            unit: items_data[i].unit,
                            total_cost: 0,
                            count: items_data[i].count,
                            amount: items_data[i].amount,
                            godownentry_detail: godownentry_detail_id,
                            notes: items_data[i].notes,
                            record_data: items_data[i].record_data
                        };
                        roldData.push(newRow);
                    }
                    material_tableIns.reload({
                        data: roldData
                    });
                    batchUpdateCost()
                }
            })
        }
    };

    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" onchange="onCountChange('+ d.id +', '+d.product_base+')" lay-verify="required|numberGtZ" autocomplete="off" class="layui-input">';

                }},
            {field: 'total_cost', title: '成本合计', width: 100, templet: function (d) {

                     return '<span id="total_cost' + d.id + '">'+ d.total_cost +'</span>';

                }},
            {field: 'unit', title: '单位', width: 80},
            {field: 'notes', title: '备注', width: 150, templet: function (d) {

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

                }},
            {field: 'entry_no', title: '入库单号', width: 180, templet: function (d) {
                    var options = utils.renderSelectOptions(d.record_data, {
                        valueField: "detail_id",
                        textField: "no",
                        selectedValue: d.godownentry_detail
                    });
                    return '<select id="entry_no' + d.id + '" lay-filter="onEntryNoChange" lay-verify="required"><option value="">请选择</option>' + options + '</select>';
                }},
            {field: 'surplus_count', title: '库存数量', width: 150,templet: function (d) {

                    return '<span id="surplus_count' + d.id + '"></span>';

                }},

            {field: 'entry_price', title: '成本价', width: 150, templet: function (d) {

                    return '<span id="entry_price' + d.id + '"></span>';

                }},
            {field: 'entry_notes', title: '入库单备注', width: 150, templet: function (d) {

                    return '<span id="entry_notes' + d.id + '"></span>';

                }},

            {
                field: 'id', title: '操作', minWidth: 80, 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;
        }
    });




    table.on('tool(material_layTable)', function (obj) {
        var data = obj.data;
        var event = obj.event;
        switch (event) {
            case "del":
                obj.del();
                layer.msg('删除成功', {icon: 6});
                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 godownentry_detail = $('#entry_no'+rows[n].id).val();
            var notes = $('#notes'+rows[n].id).val();
            var total_cost = $('#total_cost'+rows[n].id).html();

            var item = {
                product_base: rows[n].product_base,
                id: rows[n].id,
                name: rows[n].name,
                model: rows[n].model,
                unit: rows[n].unit,
                record_data: rows[n].record_data,
                count: count,
                total_cost: total_cost,
                godownentry_detail:godownentry_detail,
                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;
        }
        admin.req({
            url: '/purchase/godownentry_return/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%', '100%'],
            btn: ['确定', '取消'],
            yes: function (index, dom) {
                layui.onSubmitChild = function (data) {
                    if(data.length > 0) {
                    layer.msg('添加成功！', {icon: 6});
                } else {
                        layer.msg('请先选择记录！');
                    }
                    var oldData = getMaterialData();
                    var k = 0;
                    if (oldData.length > 0){
                        var k = oldData[oldData.length-1].id;
                    }
                    for (var i in data) {
                        k = k + 1;
                        var newRow = {
                            id: k,
                            product_base: data[i].product_id,
                            name: data[i].name,
                            model: data[i].model,
                            unit: data[i].unit,
                            count: '',
                            total_cost: '',
                            godownentry_detail: '',
                            notes: '',
                            record_data: data[i].record_data
                        };
                        oldData.push(newRow);
                    }
                    material_tableIns.reload({
                        data: oldData
                    });

                };
                layui.submitChild();
            },
            btn2: function (index, layero) {
                layer.close(index);//关闭当前按钮
            },
            content: '../material/search_material_item.html?warehouse='+$("#id_warehouse").val() + '&supplier='+$("#id_supplier").val()
        });
    });

    form.on('select(onWarehouseChange)',function(){
        updateEnryno();
        batchUpdateCost();
    });
    form.on('select(onSupplierChange)',function(){
        updateEnryno();
        batchUpdateCost();
    });
    form.on('select(onEntryNoChange)', function (data) {
        var total_id = data.elem.id;
        var id = total_id.match(/\d+/g)[0];
        var detail_id = data.value;
        updateTotalCost(id, detail_id);
        updateEntry(id, detail_id);
    });

    function updateTotalCost(id, detail_id){
        if(!detail_id || !id || isNaN(id) || isNaN(detail_id) ){
            $("#total_cost" + id).html('');
            return;
        }
        var items = getMaterialData();
        for (var n in items){
            if (items[n].id == id){
                var count = items[n].count;
                if(!count || isNaN(count)){
                    return;
                }
                var record_data = items[n].record_data;
                for (var i in record_data){
                    if(record_data[i].detail_id == detail_id){
                        var total_cost = record_data[i].entry_price * count;
                        $('#total_cost' + id).html(total_cost.toFixed(4));
                        break;
                    }
                }
                break;
            }
        }
    }

    function updateEntry(id, detail_id){
        if(!detail_id || !id || isNaN(id) || isNaN(detail_id) ){
            $('#entry_notes' + id).html('');
            $('#surplus_count' + id).html('');
            $('#entry_price' + id).html('');
            return;
        }
        var items = getMaterialData();
        for (var n in items){
            if (items[n].id == id){
                var record_data = items[n].record_data;
                for (var i in record_data){
                    if(record_data[i].detail_id == detail_id){
                        $('#entry_notes' + id).html(record_data[i].notes);
                        $('#surplus_count' + id).html(record_data[i].surplus_count);
                        $('#entry_price' + id).html(record_data[i].entry_price);
                        break;
                    }
                }
                break;
            }
        }
    }

    function updateEnryno() {

        var warehouse = $("#id_warehouse").val();
        var supplier = $("#id_supplier").val();
        var data = getMaterialData();
        var edit_data = [];
        for(var i in data) {
                    data[i].record_data = [];
                }
            material_tableIns.reload({data: data});
        if (data.length == 0 || !warehouse || !supplier){
            return;
        }
        for(var i in data){
            var row = {
                product_id: data[i].product_base,
                index: data[i].id
            };
            edit_data.push(row)
        }

        admin.req({
            url: '/warehouse/select/stocks/?warehouse=' + warehouse + '&supplier=' + supplier
            , data: {products: JSON.stringify(edit_data)}
            , type: 'post'
            , done: function (res) {
                var result_data = res.data;
                var table_data = getMaterialData();
                for (var i in table_data) {
                    var record_data = [];
                    for (var m in result_data) {
                        if (table_data[i].id == result_data[m].index && table_data[i].product_base == result_data[m].product_id) {
                            record_data = result_data[m].items;
                            table_data[i].record_data = record_data;
                            break;
                        }
                    }
                }
                material_tableIns.reload({
                    data: table_data
                });
            }
        });
    }

    function batchUpdateCost() {
        var data = getMaterialData();
        if (data.length == 0){
            return;
        }
        for(var i in data){
            var id = data[i].id;
            var detail_id = data[i].godownentry_detail;
            updateTotalCost(id, detail_id);
            updateEntry(id, detail_id)
        }
    }

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

    function onCountChange(id, product_base){
    var $ = layui.$;
    var warehouse = $("#id_warehouse").val();
    var supplier = $("#id_supplier").val();
    var detail_id = $("#entry_no" + id).val();
    var count = $("#count" + id).val();
    count = parseFloat(count);
    if(!warehouse || !supplier){
        $("#total_cost" + id).html('');
        return;
    }
    if(!detail_id || !id || isNaN(id) || isNaN(detail_id) ){
        $("#total_cost" + id).html('');
        return;
    }
    if(!count || isNaN(count)){
        $("#total_cost" + id).html('');
        return;
    }
    var admin = layui.admin;
    admin.req({
        url: '/warehouse/select/stock/?warehouse=' + warehouse + '&product=' + product_base+'&supplier='+ supplier
        ,done: function(res){
            var result_data = res.data;
            for (var i in result_data) {
                if (result_data[i].detail_id == detail_id){
                    var total_cost = count * result_data[i].entry_price;
                    $('#total_cost' + id).html(total_cost.toFixed(4))
                }
            }
        }
    })
}

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