<!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>
            <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 layui-form-item">

                            <div class="layui-col-md12">
                                <label class="layui-form-label"><font color='red' size="4">*</font>客户：</label>
                                <div class="layui-input-block">
                                    <div class="layui-col-xs12 layui-col-sm5">
                                        <input id='id_customer' type="text"  autocomplete="off" lay-verify="required" class="layui-input"/>
                                    </div>
                                    <div class="layui-col-xs12 layui-col-sm7" style="line-height: 37px;">
                                        <button id="btn_add" class="layui-btn layui-btn-warm" type="button" data-permission="customer.add_customer"><i class="layui-icon layui-icon-add-circle"></i>新建</button>
                                        <label  id="id_customer_name" style="margin-left: 10px;">姓名</label>
                                        <label  id="id_customer_tel" style="margin-left: 10px;">电话</label>
                                        <input id="customer_id" type="hidden" name="customer">
                                    </div>
                                    <div style="clear: both;"></div>
                                </div>
                            </div>

                            <div class="layui-col-md12">
                                <label class="layui-form-label">备注：</label>
                                <div class="layui-input-block">
                                    <div class="layui-col-sm8">
                                        <input id="id_notes" type="text" autocomplete="off" name="notes"  class="layui-input">
                                    </div>
                                </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="table-overlay">
                            <table id="part_dataTable" lay-filter="part_dataTable" class="layui-hide"></table>
                        </div>

                        <button id="submit_btn" lay-submit lay-filter="component-form-element" style="display: none">保存</button>

                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

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

  var customer_id=null;
  var _options = [];
  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');

    admin.req({
        url: '/foundation/search_options/?type=4',
        done: function(res){
            _options = res.data;
        }
    });

    autocomplete.render({
        elem:$('#id_customer'),
        url:'/customer/customer/select/',
        template_val:'{{d.name}}-{{d.mobile}}',
        template_txt:'{{d.name}} <span class=\'layui-badge layui-bg-gray\'>{{d.mobile}}</span>',
        onselect: function (resp) {
            fillData(resp);
        }
    });

    function fillData(data){
        $('#id_customer_name').html('姓名：' + data.name);
        $('#id_customer_tel').html('电话：' + data.mobile);
        $('#id_customer').val(data.name + '-' + data.mobile);
        customer_id = data.id;
    }

    var part_layTableId = "part_layTable";
	var part_tableIns = table.render({
        elem: '#part_dataTable',
        id: part_layTableId,
        data: [],
        page: false,
        limit: 1000,
        loading: true,
        even: true, //不开启隔行背景
        cols: [[
            {title: '序号', type: 'numbers'},
            {field: 'name', title: '产品名称', width: 150},
            {field: 'model', title: '产品代码', width: 150},
            {field: 'unit', title: '单位', width: 80},
            {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">';
            }},
            {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">';
            }},
            {field: 'option_type', title: '质量要求', width: 120, templet: function (d) {
                    var options = utils.renderSelectOptions(_options, {
                        valueField: "id",
                        textField: "name",
                        selectedValue: d.option_type
                    });
                    return '<select id="option_type'+d.id+'" lay-filter="type_select"><option value="">请选择</option>' + options + '</select>';
                }
            },
            {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>';
            }}
        ]],
    });

    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;
        }
    });

    var getItemsData = function () {
        var rows = table.cache[part_layTableId];
        var items = [];
        for(var k in rows){
            if (rows[k] == false) {
                continue;
            }

            var option_type = $('#option_type'+rows[k].id).val();
            var count = $('#count'+rows[k].id).val();
            var price = $('#price'+rows[k].id).val();
            var item = {
                id:rows[k].id,
                goods:rows[k].id,
                name:rows[k].name,
                model:rows[k].model,
                count:count,
                price:price,
                quality_request:option_type
            };
            items.push(item);
        }
        return items
    };
    form.on('submit(component-form-element)', function(data){
        var items = getItemsData();


        if(items.length == 0){
            layer.msg('请添加产品！', {icon: 5});
            return false;
        }

        if (!customer_id){
            layer.msg('请添加客户！', {icon: 5});
            return false;
        }

        var order_data = {'customer': customer_id, 'notes': $('#id_notes').val()};

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

      $('#part-btn-add').on('click', function () {
          layer.open({
              type: 2,
              title: '添加成品',
              shadeClose: false,
              area: ['90%', '98%'],
              btn: ['保存', '取消'],
              yes: function (index, dom) {
                  layui.onSubmitChild = function (data) {
                      var oldData = getItemsData();
                      if (data.length > 0) {
                          layer.msg('添加成功！', {icon: 6});
                      } else {
                        layer.msg('请先选择记录！');
                    }
                      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,
                              price: data[i].retail_price,
                              count: 1.00,
                              warehouse_place: data[i].warehouse_place,
                              option_type: ''
                          };
                          oldData.push(newRow);
                      }
                      part_tableIns.reload({
                          data: oldData
                      });

                  };
                  layui.submitChild();
              },
              btn2: function (index, layero) {
                  layer.close(index);
              },
              content: '../goods/search_goods_item.html'
          });
      });

    $('#btn_add').on('click', function(){
        layer.open({
          type: 2,
          title: '添加客户',
          shadeClose: false,
          area: ['95%', '95%'],
          btn: ['保存', '取消'],
          yes: function(index, dom){
              layui.onSubmitChild = function (data) {
              layer.close(index);
              fillData(data)
            };
            layui.submitChild();
          },
          btn2: function(index, layero){
            layer.close(index);//关闭当前按钮
          },
          content:'../customer/customer_edit.html?add=true'
        });
    });

    if (id) {
        admin.req({
          url: '/order/sale_order/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: item.goods_id,
                    name: item.name,
                    model:item.model,
                    unit:item.unit,
                    price: item.price,
                    count: item.count,
                    warehouse_place: '',
                    option_type: item.quality_request,
                    part_data:item
                }
                oldData.push(newRow);
            }
            part_tableIns.reload({
                data: oldData
            });

             var orderData = JSON.parse(JSON.stringify(parent.layui.table.editdata));
             fillData({
                 name:orderData.customer_name,
                 mobile:orderData.customer_tel,
                 id:orderData.customer
             });
          }
        });
    }

    parent.layui.submitChild = function () {
      $("#submit_btn").click();
    };

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