<%@ page contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="webkit">
    <!-- 移动设备 viewport -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <jsp:include page="../../common.jsp"/>

    <style>
        .layui-table-cell.laytable-cell-1-0-2,
        .layui-table-cell.laytable-cell-1-0-3,
        .layui-table-cell.laytable-cell-1-0-5,
        .layui-table-cell.laytable-cell-1-0-6,
        .layui-table-cell.laytable-cell-1-0-7,
        .layui-table-cell.laytable-cell-1-0-8,
        .layui-table-cell.laytable-cell-1-0-9,
        .layui-table-cell.laytable-cell-1-0-13 {
            vertical-align: middle;
            height: auto;
            overflow: hidden;
            text-overflow: inherit;
            white-space: nowrap;
        }

        hr {
            margin: 3px 0 !important;
        }
    </style>
</head>
<body>

<div class="row animated fadeInRight" style="margin: 0;">
    <div class="wrapper wrapper-content mt5 right-content ml5 mr5">
        <div class="toolbar-panel bdd">
            <div class="toolbar-box">
                <div class="toolbar-head clearfix lgraybg pt5 pb10 pl10 bdbd">
                    <!-- 顶部按钮 -->
                    <div class="fl">
                        查询条件
                    </div>
                    <div class="tools fr">
                        <a href="javascript:void(0);" class="collapse dblock f14 dgray mr5">
                            <i class="fa-2x fa fa-angle-double-up"></i>
                        </a>
                    </div>
                </div>
            </div>
            <!--搜索条件 -->
            <div class="toolbar-body">
                <form class="layui-form" id="form1" action="" style="margin-top: 10px;">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">设备编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="snNo" placeholder="请输入设备编号" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">厂家编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="deviceNo" placeholder="请输入厂家编号" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">设备类型</label>
                            <div class="layui-input-inline">
                                <select class="layui-select" name="code" data-dom="queryType" lay-filter="deviceType"
                                        lay-verify="required">
                                    <option value="">请选择</option>
                                    <c:forEach items="${deviceTypeDict}" var="dict">
                                        <option value="${dict.code}" ${dict.code == entity.code ? 'selected' : ''}>${dict.name}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">设备版本</label>
                            <div class="layui-input-inline">
                                <select class="layui-select" name="type" id="queryType" lay-verify="required">
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">购买商家</label>
                            <div class="layui-input-inline">
                                <input type="text" name="buyMercName" id="buyMercName" placeholder="请输入购买商家名称"
                                       autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">激活用户id</label>
                            <div class="layui-input-inline">
                                <input type="text" name="actUserId" id="actUserId" placeholder="请输入购买激活用户id"
                                       autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">激活商家</label>
                            <div class="layui-input-inline">
                                <input type="text" name="actMercName" id="actMercName" placeholder="请输入激活商家名称"
                                       autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select class="layui-select" name="bindStatus">
                                    <option value="">请选择</option>
                                    <option value="-1">未激活</option>
                                    <option value="1">已激活</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">提货人</label>
                            <div class="layui-input-inline">
                                <input type="number" name="extractUserId" placeholder="提货人用户ID" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">归属人</label>
                            <div class="layui-input-inline">
                                <input type="text" name="belongUserId" placeholder="归属人用户ID" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 100px;padding: 0 15px">
                                <select class="layui-select" id="noType">
                                    <option value="1" selected>设备编号</option>
                                    <option value="2">厂家编号</option>
                                </select>
                            </label>
                            <div class="layui-input-inline" style="width: 150px;">
                                <input type="text" name="startDeviceNo" placeholder="开始编号" autocomplete="off"
                                       class="layui-input">
                            </div>
                            <span style="float: left;padding-right: 10px;line-height: 36px;">-</span>
                            <div class="layui-input-inline" style="width: 150px;">
                                <input type="text" name="endDeviceNo" placeholder="结束编号" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- 表单数据 -->
    <div class="mb50 mt10">
        <div class="whitebg pl10 pr10">
            <table class="layui-hide" id="deviceStockTab" lay-filter="deviceStockTab"></table>
        </div>
    </div>
</div>

<script type="text/template" id="add">
    <form class="layui-form" id="form2" style="margin-top: 2rem;">
        <input name="id" id="id" hidden>
        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备类型</label>
            <div class="layui-input-block">
                <select class="layui-select" name="code" id="code" data-dom="addType" lay-filter="deviceType"
                        lay-verify="required">
                    <option value="">请选择</option>
                    <c:forEach items="${deviceTypeDict}" var="dict">
                        <option value="${dict.code}" ${dict.code == entity.code ? 'selected' : ''}>${dict.name}</option>
                    </c:forEach>
                </select>
            </div>
        </div>

        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备版本</label>
            <div class="layui-input-block">
                <select class="layui-select" name="type" id="addType" lay-verify="required">
                </select>
            </div>
        </div>

        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备分组</label>
            <div class="layui-input-block">
                <select class="layui-select" name="groupNo" id="groupNo" lay-verify="required">
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备编号</label>
            <div class="layui-input-block">
                <input type="text" name="snNo" id="snNo" placeholder="设备编号" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</script>

<script type="text/template" id="addBatch">
    <form class="layui-form" id="form3" style="margin-top: 2rem;">

        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备类型</label>
            <div class="layui-input-block">
                <select class="layui-select" name="code" id="addBatchCode" lay-filter="deviceType"
                        data-dom="addBatchType" lay-verify="required">
                    <option value="">请选择</option>
                    <c:forEach items="${deviceTypeDict}" var="dict">
                        <option value="${dict.code}" ${dict.code == entity.code ? 'selected' : ''}>${dict.name}</option>
                    </c:forEach>
                </select>
            </div>
        </div>

        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备版本</label>
            <div class="layui-input-block">
                <select class="layui-select" name="type" id="addBatchType" lay-verify="required">
                </select>
            </div>
        </div>

        <div class="layui-form-item" style="width: 350px;">
            <label class="layui-form-label">设备分组</label>
            <div class="layui-input-block">
                <select class="layui-select" name="groupNo" id="addBatchGroupNo" lay-verify="required">
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">编号范围</label>
                <div class="layui-input-inline" style="width: 200px;">
                    <input type="text" name="startSnNo" id="startSnNo" placeholder="开始编号" autocomplete="off"
                           class="layui-input">
                </div>
                <div class="layui-form-mid">-</div>
                <div class="layui-input-inline" style="width: 200px;">
                    <input type="text" name="endSnNo" id="endSnNo" placeholder="结束编号" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>
    </form>
</script>

<script type="text/template" id="bind">
    <form class="layui-form" id="form4" style="margin-top: 2rem;">
        <input name="id" id="bindId" hidden>
        <input name="status" id="status" value="3" hidden>
        <div class="layui-form-item" style="width: 300px;">
            <label class="layui-form-label">用户ID</label>
            <div class="layui-input-block">
                <input type="text" name="userId" id="actMercId" placeholder="请输入商户ID" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
    </form>
</script>

<script type="text/template" id="bind2">
    <form class="layui-form" id="form5" style="margin-top: 2rem;">
        <input name="id" id="bindId2" hidden>
        <div class="layui-form-item" style="width: 300px;">
            <label class="layui-form-label">厂家编号</label>
            <div class="layui-input-block">
                <input type="text" name="deviceNo" id="deviceNo" placeholder="设备厂家编号，码牌可不填" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
    </form>
</script>

<script type="text/template" id="transfer">
    <form class="layui-form" id="form6" style="margin-top: 2rem;">
        <div class="layui-form-item" style="width: 400px;">
            <label class="layui-form-label">出库用户</label>
            <div class="layui-input-block">
                <input type="number" name="accpetUserId" id="accpetUserId" placeholder="请输入出库用户ID" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="width: 400px;">
            <label class="layui-form-label">订单号</label>
            <div class="layui-input-block">
                <input type="text" name="orderNo" id="orderNo" placeholder="出库设备对应的设备商城订单号" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="leftBar">
    <button type="button" class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe608;</i>新增</button>
    <button type="button" class="layui-btn layui-btn-sm" lay-event="addBatch"><i class="layui-icon">&#xe608;</i>批量新增
    </button>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-warm" lay-event="transfer"><i class="layui-icon">&#xe609;</i>设备出库
    </button>
    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" lay-event="search"><i class="layui-icon">&#xe615;</i>查询
    </button>
</script>

<script type="text/html" id="toolBar">
    {{#  if(d.status == 3){ }}
    <div class="layui-col-md12">
        <button type="button" class="layui-btn layui-btn-xs layui-btn-warm" lay-event="unbind"><i class="layui-icon">&#xe64d;</i>解绑
        </button>
    </div>
    {{# } }}
    {{#  if(d.status == 1 || d.status == 2){ }}
    <div class="layui-col-md12">
        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-event="bind"><i class="layui-icon">&#xe64c;</i>绑定
        </button>
    </div>
    {{# } }}
    <div class="layui-col-md12">
        <button type="button" class="layui-btn layui-btn-xs" lay-event="showDeviceOperaInfo"><i
                class="layui-icon layui-icon-list"></i>详情
        </button>
    </div>
<%--    <div class="layui-col-md12">--%>
<%--        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i--%>
<%--                class="layui-icon">&#xe640;</i>删除--%>
<%--        </button>--%>
<%--    </div>--%>
</script>

<script type="text/template" id="bindDeviceNo">

</script>

<script>
    var dictGroupList;

    layui.use(['table', 'layer', 'form'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;

        var tableIns = table.render({
            elem: '#deviceStockTab'
            , url: ctx + '/deviceStock/pageData'
            , id: 'deviceStock'
            , response: {
                statusName: 'code' //数据状态的字段名称，默认：code
                , countName: 'count' //数据总数的字段名称，默认：count
                , dataName: 'data' //默数据列表的字段名称，认：data
                , statusCode: 200
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , toolbar: '#leftBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter']
            , title: '智能音箱信息表'
            , cols: [[
                {type: 'checkbox', fixed: 'left', hidden: true}
                , {field: 'numbers', title: '序号', fixed: 'left', unresize: true, minWidth: 80, type: 'numbers'}
                /*,{field:'boxName', title:'音箱名称'}*/
                , {
                    field: 'snNo', title: '设备编号&nbsp;/&nbsp;厂家编号', minWidth: 175, templet: function (d) {
                        if (d.deviceNo == '' || d.deviceNo == null) {
                            return "NO." + d.snNo + '<hr/>' + '<button type="button" class="layui-btn layui-btn-sm" onClick="toBindDeviceNo(' + d.id + ')">绑定厂家编号</button>';
                        } else {
                            return "NO." + d.snNo + '<hr/>' + "NO." + d.deviceNo;
                        }
                    }
                }
                , {
                    field: 'codeDesc',
                    title: '设备类型&nbsp;/&nbsp;版本',
                    minWidth: 100,
                    templet: "<div>{{d.codeDesc}}<hr/>{{d.typeDesc}}</div>"
                }
                , {
                    field: 'groupNoDesc', title: '库存分组', minWidth: 120
                }
                , {
                    field: 'price', title: '设备价格<hr/>购买单号', minWidth: 100, templet: function (d) {
                        if (d.price != '' && d.price != null) {
                            return d.price.toFixed(2) + "<hr/>" + d.orderNo;
                        }
                        return d.orderNo;
                    }
                }
                , {title: '购买商家名称<hr/>商家ID', minWidth: 150, templet: "<div>{{d.buyMercName}}<hr/>{{d.buyUserId}}</div>"}
                , {title: '激活商家名称<hr/>商家ID', minWidth: 150, templet: "<div>{{d.actMercName}}<hr/>{{d.actUserId}}</div>"}
                , {
                    field: 'extractUserId', title: '提货人<hr/>ID', minWidth: 100, templet: function (d) {
                        if (!d.extractUserId) {
                            return "-";
                        }
                        return d.extractName + "<hr/>" + d.extractUserId;
                    }
                }
                , {
                    field: 'belongUserId', title: '所属人<hr/>ID', minWidth: 100, templet: function (d) {
                        if (!d.belongUserId) {
                            return "-";
                        }
                        return d.belongName + "<hr/>" + d.belongUserId;
                    }
                }
                , {
                    field: 'status', title: '状态', minWidth: 80, templet: function (d) {
                        if (d.status == '1') {
                            return "<span>未出售</span>"
                        } else if (d.status == '2') {
                            return "<span style='color: blue'>已出售</span>"
                        } else if (d.status == '3') {
                            return "<span style='color: green'>已激活</span>"
                        }
                    }
                }
                , {
                    field: 'bindTime',
                    title: '激活时间',
                    minWidth: 160,
                    templet: "<div>{{layui.util.toDateString(d.bindTime,'yyyy-MM-dd HH:mm')}}</div>"
                }
                , {
                    field: 'createTime',
                    title: '创建时间',
                    minWidth: 160,
                    templet: "<div>{{layui.util.toDateString(d.createTime,'yyyy-MM-dd HH:mm')}}</div>"
                }
                , {fixed: 'right', title: '操作', minWidth: 70, toolbar: '#toolBar'}
            ]]
            , done: function (index, layero) {
                //表头部分
                //动态监听表头高度变化，冻结行跟着改变高度
                $(".layui-table-header  tr").resize(function () {
                    $(".layui-table-header  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-header table tr")[index]).height(val.getBoundingClientRect().height);
                    });
                });
                //初始化高度，使得冻结行表头高度一致
                $(".layui-table-header  tr").each(function (index, val) {
                    let initElement = $(".layui-table-fixed .layui-table-header table tr")[index]
                    if (initElement != null) {
                        $(initElement).height(val.getBoundingClientRect().height);
                        $(initElement).find("th").removeAttr("style");
                    }
                });

                //表体部分
                //动态监听表体高度变化，冻结行跟着改变高度
                $(".layui-table-body  tr").resize(function () {
                    $(".layui-table-body  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-body table tr")[index]).height(val.getBoundingClientRect().height);
                    });
                });
                //初始化高度，使得冻结行表体高度一致
                $(".layui-table-body  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-body table tr")[index]).height(val.getBoundingClientRect().height);
                });
            }
            , request: {
                pageName: 'current' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , page: true
        });

        form.on('select(deviceType)', function (data) {
            var dataType = data.value;
            var domId = $(data.elem).attr("data-dom");
            $.ajax({
                url: ctx + '/deviceDetail/getDeviceSubVersionType/' + dataType,
                method: 'get',
                dataType: 'json',
                success: function (res) {
                    if (res.code == 200) {
                        var dom = $("#" + domId);
                        var html = "<option value=''>请选择</option>";
                        dom.empty();
                        if (res.data.length > 0) {
                            $.each(res.data, function (k, v) {
                                html += "<option value='" + v.spec + "'>" + v.specName + "</option>";
                            })
                            dom.append(html);
                        }
                        form.render('select');
                    } else {
                        layer.msg(res.message, {
                            icon: 5
                        });
                    }
                }
            })
        })

        table.on('tool(deviceStockTab)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if (layEvent === 'del') { //删除
                layer.confirm('真的删除么?', {icon: 3}, function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    del(data);
                    //向服务端发送删除指令
                });
            } else if (layEvent === 'bind') {
                toBind(obj);
            } else if (layEvent === 'unbind') {
                layer.confirm('确定要解绑吗?', {icon: 3}, function (index) {
                    layer.close(index);
                    var data = obj.data;
                    toUnBindSave(data.status, data.id);
                    //向服务端发送删除指令
                });
            } else if (layEvent === 'showDeviceOperaInfo') {
                let url = ctx + '/deviceOperateInfo/index?deviceNo=' + data.snNo;
                var index = layer.open({
                    type: 2
                    , shade: 0.5
                    , title: '绑定'
                    , maxmin: true
                    , area: ['80%', '80%']
                    , content: url
                });
            }
        });

        //监听头工具栏事件
        table.on('toolbar(deviceStockTab)', function (obj) {
            switch (obj.event) {
                case 'add':
                    // 添加
                    toAdd();
                    break;
                case 'addBatch':
                    // 添加
                    toAddBatch();
                    break;
                case 'transfer':
                    // 设备出库
                    var checkStatus = table.checkStatus('deviceStock'); //idTest 即为基础参数 id 对应的值
                    if (checkStatus.data.length == 0) {
                        return layer.msg("至少选中一条记录");
                    }
                    toTrasnfer(checkStatus.data);
                    break;
                case 'search':
                    var params = serialize($('#form1'));
                    let noType = $("#noType").val();
                    params["noType"] = noType;
                    table.reload('deviceStock', {
                        where: params
                        , page: {
                            size: 10
                            , current: 1
                        }
                    });
                    break;
            }
        });

        function getDictSubText(code, value) {
            var subDictName = "";
            $.ajax({
                url: '${ctx}/deviceDetail/getDeviceSubVersionType/' + code,
                method: 'get',
                dataType: 'json',
                async: false,
                success: function (res) {
                    if (res.code == 200) {
                        if (res.data.length > 0) {
                            $.each(res.data, function (k, v) {
                                if (v.value == value) {
                                    subDictName = v.name;
                                }
                            })
                        }
                    } else {
                        layer.msg(res.message, {
                            icon: 5
                        });
                    }
                }
            })
            return subDictName;
        }

        /**
         * 获取设备版本信息
         * @param code
         */
        function initVersion() {
            $.ajax({
                url: ctx + '/deviceStock/getDeviceVersion',
                method: 'get',
                dataType: 'json',
                success: function (res) {
                    if (res.code == 200) {
                        var dataList = res.data;
                        var dom = $("[name='groupNo']");
                        var html = "<option value=''>请选择</option>";
                        dom.empty();
                        if (dataList.length > 0) {
                            $.each(dataList, function (k, v) {
                                html += "<option value='" + v.groupCode + "'>" + v.groupName + "</option>";
                            })
                            dom.append(html);
                            form.render();
                        }
                    }
                }
            })
        }

        function toBind(obj) {
            var index = layer.open({
                type: 1
                , shade: 0.5
                , title: '绑定'
                , maxmin: true
                , content: $("#bind").html()
                , area: ['400px', '300px']
                , btn: ['保存', '取消',]
                , shadeClose: true
                , btn1: function (index, layero) {
                    var actMercId = $("#actMercId").val();
                    if (!actMercId) {
                        layer.msg("商户ID不能为空!");
                        return;
                    }
                    toAddSave(index, $("#form4"), "bind");
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
                , success: function () {
                    $("#bindId").val(obj.data.id);
                }
            });
        }

        //设备划拨
        function toTrasnfer(data) {
            let ids = [];
            $.each(data, function (k, v) {
                ids.push(v.id);
            })
            var index = layer.open({
                type: 1
                , shade: 0.5
                , title: '设备出库'
                , maxmin: true
                , content: $("#transfer").html()
                , area: ['450px', '250px']
                , btn: ['确定', '取消',]
                , shadeClose: true
                , btn1: function (index, layero) {
                    var accpetUserId = $("#accpetUserId").val();
                    let orderNo = $("#orderNo").val();
                    if (!accpetUserId) {
                        layer.msg("用户ID不能为空!");
                        return;
                    }
                    saveTrasnfer(ids, accpetUserId, orderNo, index);
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        }

        function saveTrasnfer(ids, accpetUserId, orderNo, index) {
            var dialog = layer.msg('正在出库中...', {icon: 16, time: 0, shade: [0.3, '#000', false]});
            $.ajax({
                url: ctx + '/deviceStock/transfer',
                method: 'post',
                data: {
                    ids: ids,
                    accpetUserId: accpetUserId,
                    orderNo: orderNo
                },
                dataType: 'JSON',
                success: function (res) {
                    layer.close(dialog);
                    if (res.code == 200) {
                        layer.close(index);
                        tableIns.reload();
                    }
                    layer.msg(res.message, {
                        icon: res.code == 200 ? 1 : 2
                    });
                }
            })
        }

        function toAddBatch() {
            var index = layer.open({
                type: 1
                , shade: 0.5
                , title: '批量新增'
                , maxmin: true
                , content: $("#addBatch").html()
                , area: ['650px', '450px']
                , btn: ['保存', '取消',]
                , shadeClose: true
                , btn1: function (index, layero) {
                    var addBatchGroupNo = $("#addBatchGroupNo").val();
                    if (!addBatchGroupNo) {
                        layer.msg("设备分组不能为空!", {icon: 2});
                        return;
                    }
                    var addBatchCode = $("#addBatchCode").val();
                    if (!addBatchCode) {
                        layer.msg("设备类型不能为空!", {icon: 2});
                        return;
                    }
                    var addBatchType = $("#addBatchType").val();
                    if (!addBatchType) {
                        layer.msg("设备版本不能为空!", {icon: 2});
                        return;
                    }
                    var startSnNo = $("#startSnNo").val();
                    if (!startSnNo) {
                        layer.msg("开始设备编号不能为空!", {icon: 2});
                        return;
                    }
                    var endSnNo = $("#endSnNo").val();
                    if (!endSnNo) {
                        layer.msg("结束设备编号不能为空!", {icon: 2});
                        return;
                    }
                    var reg = /^[0-9]+$/;
                    if (!reg.test(startSnNo)) {
                        layer.msg("开始设备编号格式不正确!", {icon: 2});
                        return;
                    }
                    if (!reg.test(endSnNo)) {
                        layer.msg("结束设备编号格式不正确!", {icon: 2});
                        return;
                    }
                    if (parseInt(endSnNo) - parseInt(startSnNo) < 0) {
                        layer.msg("编号范围输入有误!", {icon: 2});
                        return;
                    }
                    toAddBatchSave(index, startSnNo, endSnNo, addBatchGroupNo, addBatchCode, addBatchType);
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
                , success: function () {
                    initVersion();
                    form.render('select');
                }
            });
        }

        function toAdd(obj) {
            var index = layer.open({
                type: 1
                , shade: 0.5
                , title: '新增'
                , maxmin: true
                , content: $("#add").html()
                , area: ['500px', '450px']
                , btn: ['保存', '取消',]
                , shadeClose: true
                , btn1: function (index, layero) {
                   /* if (!$("#groupNo").val()) {
                        layer.msg("设备分组不能为空!", {icon: 2});
                        return;
                    }*/
                    if (!$("#code").val()) {
                        layer.msg("设备类型不能为空!", {icon: 2});
                        return;
                    }
                    if (!$("#addType").val()) {
                        layer.msg("设备本版不能为空!", {icon: 2});
                        return;
                    }
                    if (!$("#snNo").val()) {
                        layer.msg("设备编号不能为空!", {icon: 2});
                        return;
                    }
                    toAddSave(index, $("#form2"), "add");
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
                , success: function () {
                    initVersion();
                    form.render('select');
                }
            });
        }

        function toAddBatchSave(index, start, end, groupNo, code, type) {
            var dialog = layer.msg('正在保存...', {icon: 16, time: 0, shade: [0.3, '#000', false]});
            var data = {};
            data.startSnNo = start;
            data.endSnNo = end;
            data.groupNo = groupNo;
            data.code = code;
            data.type = type;
            $.ajax({
                url: ctx + '/deviceStock/batchSaveNo',
                method: 'post',
                data: JSON.stringify(data),
                dataType: 'JSON',
                contentType: "application/json",
                success: function (res) {
                    layer.close(dialog);
                    if (res.code == 200) {
                        layer.close(index);
                        layer.msg(res.message, {
                            icon: 1
                        });
                        tableIns.reload();
                    } else {
                        layer.msg(res.message, {
                            icon: 2
                        });
                    }
                }
            })
        }

        function toAddSave(index, dom, type) {
            var data = dom.serializeObject();
            let url = ctx + '/deviceStock/bindSave'
            if (type === "add") {
                url = ctx + '/deviceStock/save'
            }
            $.ajax({
                url: url,
                method: 'post',
                data: JSON.stringify(data),
                dataType: 'JSON',
                contentType: "application/json",
                success: function (res) {
                    if (res.code == 200) {
                        layer.close(index);
                        layer.msg(res.message, {
                            icon: 1
                        });
                        tableIns.reload();
                    } else {
                        layer.msg(res.message, {
                            icon: 2
                        });
                    }
                }
            })
        }

        function toUnBindSave(status, id) {
            var data = {};
            data.status = status;
            data.id = id;
            $.ajax({
                url: ctx + '/deviceStock/unBindSave',
                method: 'post',
                data: JSON.stringify(data),
                dataType: 'JSON',
                contentType: "application/json",
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.message, {
                            icon: 1
                        });
                        tableIns.reload();
                    } else {
                        layer.msg(res.message, {
                            icon: 2
                        });
                    }
                }
            })
        }

        function del(obj) {
            $.ajax({
                url: '${ctx}/deviceStock/del/' + obj.id,
                method: 'DELETE',
                dataType: 'JSON',
                contentType: "application/json",
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.message, {
                            icon: 1
                        });
                    } else {
                        layer.msg(res.message, {
                            icon: 2
                        });
                    }
                }
            })
        }
    });
    jQuery.prototype.serializeObject = function () {
        var obj = new Object();
        $.each(this.serializeArray(), function (index, param) {
            if (!(param.name in obj)) {
                obj[param.name] = param.value;
            }
        });
        return obj;
    };

    function toBindDeviceNo(id) {
        var index = layer.open({
            type: 1
            , shade: 0.5
            , title: '绑定厂家编号'
            , maxmin: true
            , content: $("#bind2").html()
            , area: ['400px', '300px']
            , btn: ['保存', '取消',]
            , shadeClose: true
            , btn1: function (index, layero) {
                var deviceNo = $("#deviceNo").val();
                if (!deviceNo) {
                    layer.msg("厂家编号不能为空!");
                    return;
                }
                bindDeviceNo(index, $("#form5"));
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
            , success: function () {
                $("#bindId2").val(id);
            }
        });
    }

    function bindDeviceNo(index, dom) {
        var data = dom.serializeObject();
        $.ajax({
            url: '${ctx}/deviceStock/bindDeviceNo',
            method: 'post',
            data: JSON.stringify(data),
            dataType: 'JSON',
            contentType: "application/json",
            success: function (res) {
                if (res.code == 200) {
                    layer.close(index);
                    layer.msg(res.message, {
                        icon: 1
                    });
                    tableIns.reload();
                } else {
                    layer.msg(res.message, {
                        icon: 2
                    });
                }
            }
        })
    }
</script>
</body>
</html>
