<!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' name="customer_text" 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_customer" 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="customer_name" style="margin-left: 10px;">姓名</label>
                                        <label  id="mobile" style="margin-left: 10px;">电话</label>
                                    </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="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="goods-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="goods_data_table" lay-filter="goods_data_table" class="layui-hide"></table>
                        </div>

                        <button class="layui-btn" id="sale-plan-submit" 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 _Quality_request = [];
var _customer_id = '';
layui.link('../../../layuiadmin/style/autocomplete.css');
layui.config({
    base: '../../../layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index', //主入口模块
     utils:'utils'
}).use(['index', 'form', 'table', 'autocomplete','utils', 'laydate'], function() {
    var $ = layui.$;
    var admin = layui.admin;
    var form = layui.form;
    var table = layui.table;
    var id = layui.view.getParameterByName('id');
    var utils = layui.utils;
    var autocomplete = layui.autocomplete;
    var laydate = layui.laydate;


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

    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){
        $('#customer_name').html('姓名：' + data.name);
        $('#mobile').html('电话：' + data.mobile);
        $('#id_customer').val(data.name + '-' + data.mobile);
        _customer_id = data.id
    }

    var goods_data_table = "goods_data_table";
    var goods_tableIns = table.render({
        elem: '#goods_data_table',
        id: goods_data_table,
        data: [],
        page: false,
        limit: 1000,
        loading: true,
        even: true, //不开启隔行背景
        cols: [[
            {title: '序号', type: 'numbers'},
            {field: 'name', title: '产品名称', width: 100},
            {field: 'model', title: '产品代码', width: 100},
            {
                field: 'quality_request', title: '质量要求', width: 150, templet: function (d) {
                    console.log(_Quality_request)
                    var options = utils.renderSelectOptions(_Quality_request, {
                        valueField: "id",
                        textField: "name",
                        selectedValue: d.quality_request
                    });
                    return '<select product_id="'+d.id+'" id="quality_request' + d.id + '" lay-filter="type_select"><option value="">请选择</option>' + options + '</select>';
                }
            },
            {
                field: 'require_count', title: '数量', width: 100, templet: function (d) {

                    return '<input id="require_count' + d.id + '" value="' + d.require_count + '" type="text" lay-verify="required|numberGtZ" autocomplete="off" class="layui-input">';

                }
            },
            {field: 'unit', title:'单位', width: 70},
            {
                field: 'price', title: '单价', width: 100, templet: function (d) {
                    return '<input id="price' + d.id + '" value="' + d.price + '" type="text" lay-verify="numberGeZ" autocomplete="off" class="layui-input">';
                }
            },
            {
                field: 'require_time', title: '需求时间', width: 180, event: 'chooseDate', templet: function (d) {
                    return '<input id="require_time' + d.id + '" value="' + d.require_time + '" type="text" lay-verify="datetime" 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>';
                }
            }
        ]],
        done: function (res, curr, count) {
            //viewObj.tbData = res.data;
        }
    });
    table.on('tool(goods_data_table)', function (obj) {
        var data = obj.data;
        var event = obj.event;
        switch (event) {
            case "chooseDate":
                laydate.render({
                    elem: '#require_time' + data.id,
                    trigger: "click",
                    show: true,
                    closeStop: '#require_time' + data.id,
                    type: 'datetime',
                    done: function (value, date, endDate) {
                        var oldData = getgoodsData();
                        if (oldData[0].id === data.id) {
                            for (var i in oldData) {
                                if (oldData[i].require_time == ''){
                                    oldData[i].require_time = value
                                }
                            }
                            goods_tableIns.reload({
                                data: oldData
                            })
                        }
                    }
                });
                break;
            case "del":
                obj.del();
                layer.msg('删除成功', {icon: 6});
                break;
        }
    });

    if (id) {
        var data = JSON.parse(JSON.stringify(parent.layui.table.editdata));
        form.val("component-form-element", data);
        admin.req({
            url: '/plan/sale/detail/?id='+id,
            done: function (res) {
                var sale_data = {
                    'name':res.data.sale_data.name,
                    'id':res.data.sale_data.customer_id,
                    'mobile':res.data.sale_data.mobile
                };
                fillData(sale_data);
                var goods_data = res.data.goods_items;
                var roldData = table.cache[goods_data_table];

                for (var i in goods_data) {
                    var newRow = {
                        id: goods_data[i].goods_id,
                        name: goods_data[i].name,
                        model: goods_data[i].model,
                        price: goods_data[i].price,
                        unit: goods_data[i].unit,
                        quality_request: goods_data[i].quality_request,
                        quality_request_text: goods_data[i].quality_request_text,
                        require_count: goods_data[i].require_count,
                        require_time: goods_data[i].require_time
                    };
                    roldData.push(newRow);
                }
                goods_tableIns.reload({
                    data: roldData
                })
            }
        })
    }

    var getgoodsData = function () {
        var data = [];
        var rows = table.cache[goods_data_table];

        for (var n in rows) {
            if (rows[n] == false) {
                continue;
            }
            var quality_request = $('#quality_request'+rows[n].id).val();
            var require_count = $('#require_count'+rows[n].id).val();
            var price = $('#price'+rows[n].id).val();
            var require_time = $('#require_time'+rows[n].id).val();

            var item = {
                id: rows[n].id,
                name: rows[n].name,
                model: rows[n].model,
                unit: rows[n].unit,
                require_count: require_count,
                price: price,
                require_time: require_time,
                quality_request: quality_request,
                goods: rows[n].id
            };
            data.push(item);
        }
        return data;
    };
    form.on('submit(component-form-element)', function (data) {
        var items = getgoodsData();
        var notes = $('#notes').val();
        var sale_data = {
            'notes': notes,
            'customer': _customer_id
        };
        if (!_customer_id){
            layer.msg('请添加客户！', {icon: 5});
            return false;
        }
        if (items.length == 0) {
            layer.msg('请添加产品！', {icon: 5});
            return false;
        }
        admin.req({
            url: '/plan/sale/save/?id=' + id
            , data: {sale: JSON.stringify(sale_data), goods: JSON.stringify(items)}
            , type: 'post'
            , done: function (res) {
                _customer_id = null;
                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) {
                    var oldData = getgoodsData();
                    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,
                            quality_request: '',
                            require_count: '',
                            require_time: '',
                            price:''
                        };
                        oldData.push(newRow);
                    }

                    goods_tableIns.reload({
                        data: oldData
                    });

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

    $('#btn_add_customer').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'
        });
    });
    parent.layui.submitChild = function () {
      $("#sale-plan-submit").click();
    };

    form.on('select(type_select)', function (data) {
        var product_id = $(data.elem).attr('product_id');
        synQualityRequest(product_id, data.value)
    });

    function synQualityRequest(product_id, value) {
        var oldData = getgoodsData();
        if (oldData.length === 0) {
            return
        }
        if (oldData[0].id == product_id) {
            for (var i in oldData) {
                if (oldData[i].quality_request == '') {
                    oldData[i].quality_request = value
                }
            }
            goods_tableIns.reload({
                data: oldData
            });
        }

    }


})
  </script>

</body>
</html>