<!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">
  <link rel="stylesheet" type="text/css" href="../../layuiadmin/style/formSelects-v4.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;}
        #department_employee_selecter dl{max-height: 250px;}
    </style>
</head>
<body>

  <div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body" pad15>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
            <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-filter="onWarehouseChange" lay-verify="required">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-xs6 layui-col-sm8">
                        <label class="layui-form-label"><font color='red' size="4">*</font>领用人：</label>
                        <div class="layui-input-block"  id="department_employee_selecter">
                            <select name="receiver" xm-select="selectDepartment" xm-select-radio lay-verify="required">
                            </select>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space10">
                    <div class="layui-col-xs6 layui-col-sm4">
                        <label class="layui-form-label">成品：</label>
                        <div class="layui-input-block">
                            <select id="id_goods" name="goods">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-xs6 layui-col-sm8">
                        <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>耗材明细<button type="button" id="consumable-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="consumableDataTable" class="table-overlay">
				    <table id="consumable_layTable" lay-filter="consumable_layTable" class="layui-hide"></table>
			    </div>
            </div>
                <button class="layui-btn" id="consumable-deliver-submit" lay-submit lay-filter="component-form-element" style="display: none">确定</button>
        </form>
        </div>
        </div>
        </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' //主入口模块
    ,formSelects: 'formSelects-v4'
}).use(['index', 'form', 'table', 'laydate', 'utils','formSelects'], function() {
    var $ = layui.$;
    var admin = layui.admin;
    var form = layui.form;
    var table = layui.table;
    var utils = layui.utils;
    var formSelects = layui.formSelects;
    var id = layui.view.getParameterByName('id');

    var receiver_isload = false;
    var warehouse_isload = false;
    var goods_isload = false;
    var data_isload = false;

    formSelects.render('selectDepartment',{
      template:function(id, item) {
        if (item.value.split('_')[0] == 'employee') {
          return "<span style='color:red;'>"+item.name+"</span>";
        }
        return item.name;
      }
    });

    formSelects.value('selectDepartment', []);
    admin.req({
        url: '/account/employee/tree/'
        ,done: function(res){
            formSelects.data('selectDepartment', 'local', {
            arr: res.data,
            tree: {
                //在点击节点的时候, 如果没有子级数据, 会触发此事件
                nextClick: function(id, item, callback){
                    return false;
                    },
                }
            });
            receiver_isload = true;
            loadData();
        }
    });

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


    admin.req({
      url: '/warehouse/select/?type=1',
      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 && goods_isload && receiver_isload)) { // 要等下拉框渲染完成后才能赋值
            return;
        }
        if (data_isload) {
            return;
        }
        data_isload = true;

        var receiver = '';
        if (id) {
            var data = JSON.parse(JSON.stringify(parent.layui.table.editdata));
            receiver = data.receiver;
            form.val("component-form-element", data);
            admin.req({
                url: '/material/deliver/detail/?id=' + id,
                done: function (res) {
                    var items_data = res.data.items_data;
                    var roldData = table.cache[consumable_layTable];
                    var k=0;
                    if (roldData.length > 0){
                        k = roldData[roldData.length-1].num;
                    }
                    for (var i in items_data) {
                        k = k + 1;
                        var newRow = {
                            id: items_data[i].id,
                            name: items_data[i].name,
                            model: items_data[i].model,
                            total_cost: items_data[i].total_cost,
                            count: items_data[i].count,
                            record_data: items_data[i].record_data,
                            unit: items_data[i].unit,
                            entry_no: items_data[i].entry_no,
                            notes: items_data[i].notes,
                            num: k
                        };
                        roldData.push(newRow);
                    }
                    consumable_tableIns.reload({
                        data: roldData
                    });
                    updateCost();

                }
            })

        }
        if (receiver) {
            receiver = 'employee_'+receiver;
        }
        formSelects.value('selectDepartment', [receiver]);
    };

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

                    return '<input id="count' + d.num + '" value="' + d.count + '" type="text" onchange="onCountChange('+ d.num +','+d.id+')" lay-verify="required|numberGtZ" autocomplete="off" class="layui-input">';

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

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

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

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

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

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

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

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

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

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

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


    table.on('tool(consumable_layTable)', function (obj) {
        var data = obj.data;
        var event = obj.event;
        switch (event) {
            case "del":
                obj.del();
                layer.msg('删除成功', {icon: 6});
                break;
        }
    });


    form.on('select(entryno)', function (data) {
        var num = data.elem.id;
        num = num.match(/\d+/g)[0];
        var stock_id = data.value;
        updateTotalCost(num, stock_id);
        updateEntry(num, stock_id)
    });

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

    function updateTotalCost(num, stock_id){
        if(!stock_id || !num || isNaN(num) || isNaN(stock_id) ){
           $("#total_cost" + num).html('');
            return;
        }
        var items = getconsumableData();
        for (var n in items){
            if (items[n].num == num){
                num = items[n].num;
                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].stock_id == stock_id){
                        var total_cost = record_data[i].entry_price * count;
                        $('#total_cost' + num).html(total_cost.toFixed(4));
                        break;
                    }
                }
                break;
            }
        }
    }

    var getconsumableData = function () {
        var rows = table.cache[consumable_layTable];
        var data = [];
        for (var n in rows) {
            if (rows[n] == false) {
                continue;
            }
            var count = $('#count'+rows[n].num).val();
            var notes = $('#notes'+rows[n].num).val();
            var warehouse_stockrecord = $('#no'+rows[n].num).val();
            var total_cost = $('#total_cost'+rows[n].num).html();

            var item = {
                product_base: rows[n].id,
                num: rows[n].num,
                id: rows[n].id,
                name: rows[n].name,
                model: rows[n].model,
                unit: rows[n].unit,
                warehouse_stockrecord: warehouse_stockrecord,
                record_data: rows[n].record_data,
                entry_no: warehouse_stockrecord,
                count: count,
                total_cost: total_cost,
                notes: notes
            };
            data.push(item);
        }
        return data;
    };
    form.on('submit(component-form-element)', function (data) {
        var items = getconsumableData();
        if (items.length == 0) {
            layer.msg('请添加耗材！', {icon: 5});
            return false;
        }

        var receiver = formSelects.value('selectDepartment', 'val')[0];
        if (receiver.split('_')[0] == 'employee') {
            receiver = receiver.split('_')[1];
        } else {
            layer.msg('领用人只能选择红色的人员项！', {icon: 5});
            return false;
        }
        data.field.receiver = receiver;
        admin.req({
            url: '/material/deliver/save/?type=1&id=' + id
            , data: {main: JSON.stringify(data.field), item: JSON.stringify(items)}
            , type: 'post'
            , done: function (res) {
                parent.layui.onSubmitChild(res.data);
            }
        });
        return false;
    });
    $('#consumable-btn-add').on('click', function () {
        var warehouse = $('#id_warehouse').val();
        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 = getconsumableData();
                    var k=0;
                    if (oldData.length > 0){
                        k = oldData[oldData.length-1].num;
                    }
                    for (var i in data) {
                        k = k + 1;
                        var newRow = {
                            id: data[i].id,
                            name: data[i].name,
                            model: data[i].model,
                            unit: data[i].unit,
                            record_data: data[i].record_data,
                            num: k,
                            count:'',
                            total_cost:'',
                            notes:''
                        };
                        oldData.push(newRow);
                    }

                    consumable_tableIns.reload({
                        data: oldData
                    });
                    updateCost();

                };
                layui.submitChild();
            },
            btn2: function (index, layero) {
                layer.close(index);//关闭当前按钮
            },
            content: '../purchase/search_purchase_product.html?type=' + 1 + '&warehouse=' + warehouse
        });
    });
    form.on('select(onWarehouseChange)',function(){
        updateCost();
        updateEnryno();
    });
    function updateEnryno(){
            var warehouse = $("#id_warehouse").val();
            var products = [];
            var data = getconsumableData();
            for(var i in data) {
                    data[i].record_data = [];
                }
            consumable_tableIns.reload({data: data});
            if (data.length == 0){
                return;
            }
            for(var i in data){
                $('#total_cost' + data[i].num).html('');
                var product_id = data[i].id;
                var num = data[i].num;

                var item = {
                product_id: product_id,
                index: num
                };
                products.push(item);
            }
            if(!warehouse){
                return;
            }
            admin.req({
                    url: '/warehouse/select/stocks/?warehouse=' + warehouse
                    , data: {products:JSON.stringify(products)}
                    , type: 'post'
                    ,done: function(res){
                        var result_data = res.data;
                        var table_data = getconsumableData();
                        for (var i in table_data) {
                            var record_data = [];
                            for (var m in result_data){
                                if (table_data[i].num == 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;
                                }
                            }
                        }
                         consumable_tableIns.reload({
                            data: table_data
                        });
                    }
                });
        }
    function updateCost() {
        var data = getconsumableData();
        if (data.length == 0){
            return;
        }
        for(var i in data){
            var num = data[i].num;
            var stock_id = data[i].warehouse_stockrecord;
            updateTotalCost(num, stock_id);
            updateEntry(num, stock_id)
        }
    }

    parent.layui.submitChild = function () {
      $("#consumable-deliver-submit").click();
    };
});
function onCountChange(num, id){
        var $ = layui.$;
        var warehouse = $("#id_warehouse").val();
        var stock_id = $("#no" + num).val();
        var count = $("#count" + num).val();
        count = parseFloat(count);
        if(!warehouse){
        $("#total_cost" + num).html('');
        return;
        }
        if(!stock_id || !num || isNaN(num) || isNaN(stock_id) ){
            $("#total_cost" + num).html('');
            return;
        }
        if(!count || isNaN(count)){
            $("#total_cost" + num).html('');
            return;
        }
        var admin = layui.admin;
        admin.req({
        url: '/warehouse/select/stock/?warehouse=' + warehouse + '&product=' + id
        ,done: function(res){
            var result_data = res.data;
            for (var i in result_data) {
                if (result_data[i].stock_id == stock_id){
                    var total_cost = count * result_data[i].entry_price;
                    $('#total_cost' + num).html(total_cost.toFixed(4))
                }
            }
        }
    })
    }

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