<!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">
      <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">备注：</label>
                        <div class="layui-input-block">
                            <input id="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="part-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="partDataTable" class="table-overlay">
                    <table id="part_dataTable" lay-filter="part_dataTable" class="layui-hide"></table>
                </div>
                </div>
                <button class="layui-btn" id="purchase-order-submit" lay-submit lay-filter="component-form-element" style="display: none">保存</button>
            </form>
        </div>
    </div>
</div>

  <script src="../../layuiadmin/layui/layui.js"></script>
  <script>

  layui.link('../../../layuiadmin/style/autocomplete.css');
  layui.config({
    base: '../../../layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index',
    autocomplete: 'autocomplete'
  }).use(['index', 'form', 'autocomplete', 'table', 'utils'], function(){
    var $ = layui.$
    ,admin = layui.admin
    ,element = layui.element
    ,form = layui.form
    ,table = layui.table
    ,utils = layui.utils
    ,autocomplete = layui.autocomplete;

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

    window.viewObj = {
		renderSelectOptions: function(data, settings){
			settings =  settings || {};
			var valueField = settings.valueField || 'value',
				textField = settings.textField || 'text',
				selectedValue = settings.selectedValue || "";
			var html = [];
			for(var i=0, item; i < data.length; i++){
			    item = data[i];
				html.push('<option value="');
				html.push(item[valueField]);
				html.push('"');
				if(selectedValue && item[valueField] == selectedValue ){
					html.push(' selected="selected"');
				}
				html.push('>');
				html.push(item[textField]);
				html.push('</option>');
			}
			return html.join('');
		}
	};

    var part_width = $("#partDataTable").width();
    var cols = [];
        cols.push({title: '序号', type: 'numbers'});
        cols.push({field: 'name', title: '产品名称', width: 100});
        cols.push({field: 'model', title: '产品代码', width: 100});
        cols.push({field: 'type_text', title: '产品类别', width: 100});
        cols.push({field: 'option_text', title: '类型', width: 100});
        cols.push({field: 'unit', title: '单位', width: 80});
        cols.push({field: 'count', title: '数量', width: 100, templet: function (d){
                        return '<input id="count'+d.id+'" type="text" value="'+d.count+'" lay-verify="required|numberGtZ" autocomplete="off" class="layui-input">';
                    }});
        cols.push({field: 'price', title: '单价', width: 100, templet: function (d){
                            return '<input id="price' + d.id + '" type="text" value="' + d.price + '" lay-verify="required|numberGeZ" autocomplete="off" class="layui-input">';
                    }});

        cols.push({field: 'notes', title: '备注', width: 200, templet: function (d){
                        return '<input id="notes'+d.id+'" type="text" value="'+d.notes+'" autocomplete="off" class="layui-input">';
                    }});

        cols.push({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 +'">删除</a>';
                    }});
    var part_layTableId = "part_layTable";
	var part_tableIns = table.render({
        elem: '#part_dataTable',
        id: part_layTableId,
        data: [],
        width: part_width,
        page: false,
        limit: 1000,
        loading: true,
        even: true, //不开启隔行背景
        cols: [cols],
    });

    //监听工具条
    table.on('tool(part_dataTable)', function (obj) {
        var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
        switch(event){
             case "del":
                obj.del();
                layer.msg('删除成功', {icon: 6});
                break;
        }
    });

    form.render(null, 'component-form-element');
    element.render('breadcrumb', 'breadcrumb');

    var getProductData = function () {
        var rows = table.cache[part_layTableId];
        var items = [];

        for(var k in rows){
            if (rows[k] == false) {
                continue;
            }

            var count = $('#count'+rows[k].id).val();
            var notes = $('#notes'+rows[k].id).val();
            var price = $('#price'+rows[k].id).val();
            var loss_stock_record = $('#loss_stock_record'+rows[k].id).val();
            var item = {
                id:rows[k].id,
                product:rows[k].product,
                name:rows[k].name,
                model:rows[k].model,
                type_text: rows[k].type_text,
                option_text: rows[k].option_type_text,
                record_data: rows[k].record_data,
                loss_stock_record: loss_stock_record,
                count:count,
                price:price,
                notes:notes
            };
            items.push(item);
        }
        return items
    };
    form.on('submit(component-form-element)', function(data){
        var items = getProductData();

        if(items.length == 0){
            layer.msg('请添加产品！', {icon: 5});
            return false;
        }
        var warehouse = $('#id_warehouse').val();
        if (!warehouse) {
            layer.msg('请选择仓别！', {icon: 5});
            return false;
        }

        var order_data = {'warehouse': warehouse, 'notes': $('#id_notes').val(), 'product_type': type, 'type': 0};

        data.field.order_data = order_data;
        data.field.items = items;
        admin.req({
            url: '/material/inventory/save/?id='+id
            ,data: JSON.stringify(data.field)
            ,type: 'post'
            , done: function (res) {
                parent.layui.onSubmitChild();
            }
        });
        return false;
    });

    $('#btn_close').on('click', function() {
        parent.layer.closeAll('iframe');
    });

    $('#part-btn-add').on('click', function(){
        var warehouse = $('#id_warehouse').val();
        layer.open({
          type: 2,
          title: '添加产品',
          shadeClose: false,
          area: ['90%', '98%'],
          btn: ['保存', '取消'],
          yes: function (index, layero) {
               layui.onSubmitChild = function (data) {
                   if(data.length > 0) {
                    layer.msg('添加成功！', {icon: 6});
                } else {
                        layer.msg('请先选择记录！');
                    }
                  // layer.close(index);
                  var oldData = getProductData();
                  var k = 0;
                  if (oldData.length > 0) {
                      k = oldData[oldData.length-1].id;
                  }
                  for (var i in data){
                      k = k + 1;
                      var is_exit = false;
                       for (var m in oldData){
                          if(oldData[m].product == data[i].product_id){
                              is_exit = true;
                              break;
                          }
                      }
                      if(is_exit){
                          continue;
                      }

                      var newRow = {
                        id:k,
                        product:data[i].product_id,
                        name:data[i].name,
                        model:data[i].model,
                        unit:data[i].unit,
                        type_text: data[i].type_text,
                        option_text: data[i].option_type,
                        record_data: data[i].record_data,
                        count: 1.00,
                        price: '',
                        notes: ''
                      }
                      oldData.push(newRow);
                  }
                    part_tableIns.reload({
                        data: oldData
                    });
                };
                layui.submitChild();
            },
          btn2: function(index, layero){
            layer.close(index);
          },
          content: 'search_goods_item.html?warehouse=' + warehouse
        });
    });

    var loadData = function () {
        if (!warehouse_isload) { // 要等下拉框渲染完成后才能赋值
            return;
        }
        if (data_isload) {
            return;
        }
        data_isload = true;
        if (id) {
            var orderData = JSON.parse(JSON.stringify(parent.layui.table.editdata));
            form.val("component-form-element", orderData);
            admin.req({
              url: '/material/inventory/detail/?id='+id,
              done: function(res){
                var data = res.data.items_data;
                var oldData = [];
                for (var i in data) {
                    var item = data[i];
                    var newRow = {
                        id: i,
                        product: item.product_id,
                        name: item.product_name,
                        model:item.product_name,
                        unit:item.unit,
                        price: item.price,
                        count: item.count,
                        amount: item.amount,
                        type_text: item.type_text,
                        option_text: item.option_type_text,
                        loss_stock_record: item.loss_stock_record,
                        notes: item.notes,
                        record_data: item.record_data
                    };
                    oldData.push(newRow);
                }
                part_tableIns.reload({
                    data: oldData
                });
              }
            });
        }
    };

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

  });

  function onCountChange(id) {
      var $ = layui.$;
      var count = $("#count" + id).val();
      var warehouse = $("#id_warehouse").val();
      var admin = layui.admin;

      count = parseFloat(count);
      if (isNaN(count) || count <= 0 || !warehouse) {
          $("#price" + id).val('');
          return;
      }
  }
  </script>
</body>
</html>