@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_LayoutTable.cshtml";
}
<body>
    <div class="container-fluid">
        <div class="row-fluid" style="margin-top:5px">
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>搭赠名称：</lable>
                        <input type="text" class="form-control" name="address" maxlength="18" id="txtbfullname" />
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>单据编号：</lable>
                        <input type="text" class="form-control" id="billNid" disabled="disabled"/>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>简单摘要：</lable>
                        <input type="text" class="form-control" maxlength="18" id="rsRemark" value="" />
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>录单时间：</lable>
                        <input type="text" class="form-control" id="rsDate" disabled="disabled" />
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>开始时间：</lable>
                        <input type="text" class="form-control" onfocus="WdatePicker({isShowClear:false,readOnly:true,dateFmt:'HH:mm:ss'})" name="strdatename" id="strdatename" value="" />
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>结束时间：</lable>
                        <input type="text" class="form-control" onfocus="WdatePicker({isShowClear:false,readOnly:true,dateFmt:'HH:mm:ss'})" name="enddatename" id="enddatename" value="" />
                    </div>
                </div>
            </div>
            <div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>促销时间：</lable>
                        <input type="text" class="form-control" onfocus="WdatePicker({ isShowClear: false, readOnly: true})" id="pmStartDate" value="" />
                        <input type="text" class="form-control" onfocus="WdatePicker({ isShowClear: false, readOnly: true})" id="pmEndDate" value="" />
                    </div>
                </div>
            </div>
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div class="form-group">
                    <div class="form-inline">
                        <lable>促销周期：</lable>
                        <div class="radio i-checks inline">
                            <input type="checkbox" value="周一" name="cbradios" id="checkbox" />周一
                            <input type="checkbox" value="周二" name="cbradios" />周二
                            <input type="checkbox" value="周三" name="cbradios" />周三
                            <input type="checkbox" value="周四" name="cbradios" />周四
                            <input type="checkbox" value="周五" name="cbradios" />周五
                            <input type="checkbox" value="周六" name="cbradios" />周六
                            <input type="checkbox" value="周日" name="cbradios" />周日
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row-fluid">
            <div class="col-lg-1 col-lg-offset-11 col-md-1 col-md-offset-11 col-sm-1 col-sm-offset-11 col-xs-1 col-xs-offset-11">
                <span type="submit" class="button-glow btn btn-default" onclick="SavePeriod()"><i class="layui-icon">&#x1005;</i> 保 存</span>
            </div>
        </div>
        <div class="row-fluid" style="margin-top:10px">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <!-- Nav tabs -->
                <ul class="nav nav-tabs" role="tablist">
                    <li role="presentation" id="promotion" class="active"><a href="#PromoRule" id="period" role="tab" data-toggle="tab" style="font-size:14px;"><i class="glyphicon glyphicon-shopping-cart"></i> 促销商品</a></li>
                    <li role="presentation" id="period"><a href="#Give" id="give" role="tab" data-toggle="tab" style="font-size:14px;"><i class="glyphicon glyphicon-shopping-cart"></i> 买够商品送赠品</a></li>
                    <li role="presentation"><a href="#NoClient" id="client" role="tab" data-toggle="tab" style="font-size:14px;"><i class="layui-icon">&#xe613;</i> 适用客户</a></li>
                    <li role="presentation"><a href="#NoStor" id="storc" role="tab" data-toggle="tab" style="font-size:14px;"><i class="glyphicon glyphicon-home"></i> 适用仓库</a></li>
                    <li role="presentation"><a href="#NoSalesman" id="salesman" role="tab" data-toggle="tab" style="font-size:14px;"><i class="glyphicon glyphicon-user"></i> 适用业务员</a></li>
                </ul>
                <!-- Tab panes -->
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="PromoRule">
                        <div id="toolbar1">
                            <button id="btnBatchSettingPqty" class="btn btn-default"><i class="fa fa-plus"></i> 批量设置数量</button>
                            <button id="btnSelectPromotionalItems" class="btn btn-default"><i class="fa fa-plus"></i> 选择促销商品</button>
                        </div>
                        <div class="alert alert-info alert-dismissable">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <strong>注意! </strong>单击【促销数量,单位，备注】列可单独进行设置
                        </div>
                        <table id="periodPromotionTable"></table>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="Give">
                        <div id="toolbar2">
                            <button id="btnSetCounts" class="btn btn-default"><i class="fa fa-plus"></i> 批量设置数量</button>
                            <button id="btnSelectGive" class="btn btn-default"><i class="fa fa-plus"></i> 选择赠送商品</button>
                        </div>
                        <div class="alert alert-info alert-dismissable">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <strong>注意! </strong>单击【赠送数量,单位，备注】列可单独进行设置
                        </div>        
                        <table id="periodGivetionTable"></table>
                    </div>

                    <div role="tabpanel" class="tab-pane" id="NoClient">
                        <button id="btnChooseNotToApplyCustomer" class="btn btn-default"><i class="fa fa-plus"></i> 选择适用客户</button>
                        <table id="NotToApplyCustomerTable"></table>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="NoStor">
                        <button id="btnChooseNotToApplyTheWarehouse" class="btn btn-default"><i class="fa fa-plus"></i> 选择适用仓库</button>
                        <table id="NotToApplyTheWarehouseTable"></table>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="NoSalesman">
                        <button id="btnChooseNotToApplyToTheClerk" class="btn btn-default"><i class="fa fa-plus"></i> 选择适用业务员</button>
                        <table id="NotToApplyToTheClerkTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <input type="hidden" id="CommodityBtypeid" />
    <input type="hidden" id="ClientBtypeid" />
    <input type="hidden" id="Stockbtypeid" />
    <input type="hidden" id="Employeebtypeid" />
    <input type="hidden" id="billnumberId" />
    <script type="text/javascript">
    var pagetype = "Add";/*记录页面状态 默认新增*/
    /*绑定赠送商品信息*/
    function PromoGiveBind(billNumberID) {
        $('#periodGivetionTable').bootstrapTable({
            url: "../WLTManage/SavePromoGive",
            method: 'post',                      //请求方式（*）
            toolbar: '#toolbar2',
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            //height: "400",
            minimumCountColumns: 2,  //最少允许的列数
            uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
            clickToSelect: true,              //是否启用点击选中行
            sortable: true,                     //是否启用排序
            silentSort: true,
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            paginationFirstText: '首页',
            paginationLastText: '末页',
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showColumns: false,            //是否显示所有的列
            showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
             cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                return {
                    pagesize: params.limit,//页面大小
                    page: params.offset, //页码
                    billNumberID: $("#billnumberId").val(),
                    billNid: $("#billnumberId").val()
                };
            }, columns: [
                {
                    field: "index", title: "序号", align: "center", width: 50, edit: false, formatter: function (value, row, index) {
                        return row.index = index + 1; //返回行号
                    }
                },
                { field: 'UserCode', title: '赠品编号' },
                { field: 'FullName', title: '赠品名称' },
                { field: 'unitname', title: '单位' },
                { field: 'qty', title: '赠送数量' },
                { field: 'comment', title: '备注' },
                {
                    field: 'del', title: '删除', formatter: function (value, row, index) {
                        return "<button class='btn'><i class='glyphicon glyphicon-trash'></i> 删除</button>"
                    }
                }
            ], onClickCell: function (field, value, row, td) {
                if (field == "comment") { /*编辑搭赠商品行 备注*/
                    layer.confirm("<input id=\"comment\" type=\"text\" value='" + row["comment"] + "' />", { title: "单据备注", closeBtn: 2, }, function (idx) {
                        var comment = $("#comment").val().trim();
                        if (comment == row["comment"].trim()) {
                            layer.close(idx);
                        } else {
                            $.ajax({
                                url: "../WLTManage/SetPromoptype_List",
                                data: {
                                    typeid: row["TypeId_"],
                                    fieldValue: comment,
                                    fieldName: "comment",
                                    type: pagetype
                                },
                                datatype: "text",
                                type: "post",
                                success: function (data) {
                                    if (data == "ok") {
                                        row["comment"] = comment;
                                        $('#periodGivetionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row }); /*更行行数据*/
                                    }
                                    layer.close(idx);
                                }
                            })
                        }
                    });
                } else if (field == "qty") {/*编辑搭赠商品行 数量*/
                    layer.confirm("<input id=\"qty\" type=\"text\" value='" + row["qty"] + "' />", { title: "搭赠数量", closeBtn: 2, }, function (idx) {
                        var qty = $("#qty").val().trim();
                        if (!/^([1-9][0-9]*)$/.test(qty)) {
                            return;
                        }
                        if (qty == row["qty"].trim()) {
                            layer.close(idx);
                        } else {
                            $.ajax({
                                url: "../WLTManage/SetPromoptype_List",
                                data: {
                                    typeid: row["TypeId_"],
                                    fieldValue: qty,
                                    fieldName: "qty",
                                    type: pagetype
                                },
                                datatype: "text",
                                type: "post",
                                success: function (data) {
                                    if (data == "ok") {
                                        row["qty"] = qty;
                                        $('#periodGivetionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row });/*更行行数据*/
                                    }
                                    layer.close(idx);
                                }
                            })
                        }
                    });
                } else if (field == "unitname") {
                    var typeid = row["TypeId_"]
                    var select;
                    $.ajax({
                        async: false,
                        url: "../WLTManage/GetUnitName",
                        data: {
                            typeid: typeid
                        }, datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "err") {
                                return;
                            }
                            select = data;
                        }
                    })
                    layer.confirm(select,
                        {
                            title: "单位",
                            success: function () { /*弹框成功回调*/
                                $("#UnitName").val(row["unitid"]);
                            }
                        },
                        function (idx) { /*确定按钮 点击事件*/
                            if ($("#UnitName").find("option:selected").text().trim() == row["unitname"].trim()) {
                                layer.close(idx);
                            } else {
                                var unitName = $("#UnitName").find("option:selected").text();
                                var unitId = $("#UnitName").val();
                                $.ajax({
                                    url: "../WLTManage/SetPromoptype_List",
                                    data: {
                                        typeid: row["TypeId_"],
                                        fieldValue: unitName,
                                        fieldName: "unitname",
                                        fieldValue2: unitId,
                                        fieldName2: "unitid",
                                        type: pagetype
                                    },
                                    datatype: "text",
                                    type: "post",
                                    success: function (data) {
                                        if (data == "ok") {
                                            row["unitname"] = unitName;
                                            row["unitid"] = unitId;
                                            $('#periodGivetionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row });/*更行行数据*/
                                        }
                                        layer.close(idx);
                                    }
                                })
                            }
                        });
                } else if (field == "del") {
                    $.ajax({
                        url: "../WLTManage/delPromoPtype_List",
                        data: {
                            typeid: row["TypeId_"],
                            billnumberid: $("#billnumberId").val()
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "ok") {
                                layer.msg("删除成功！", { time: 2000 });
                                $('#periodGivetionTable').bootstrapTable("refreshOptions", {
                                    url: "../WLTManage/SavePromoGive?billNid=" + $("#billnumberId").val() + "&" + new Date().getTime(),
                                    pageNumber: $('#periodGivetionTable').bootstrapTable('getOptions').pageNumber
                                })
                            }
                        }
                    })
                }
            }
        });
    }
    /*绑定促销商品信息*/
    function PromoRuleBind(billNumberID) {
        $('#periodPromotionTable').bootstrapTable({
            url: "../WLTManage/GetPeriodPromotion",
            method: 'post',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            toolbar: '#toolbar1',
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            minimumCountColumns: 2,  //最少允许的列数
            uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
            clickToSelect: true,              //是否启用点击选中行
            sortable: true,                     //是否启用排序
            silentSort: true,
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            paginationFirstText: '首页',
            paginationLastText: '末页',
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showColumns: false,            //是否显示所有的列
            showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
             cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                return {
                    pagesize: params.limit,//页面大小
                    page: params.offset, //页码
                    billNid: billNumberID,
                };
            }, columns: [
                {
                    field: "index", title: "序号", align: "center", width: 50, edit: false, formatter: function (value, row, index) {
                        return row.index = index + 1; //返回行号
                    }
                },
                { field: 'UserCode', title: '商品编号' },
                { field: 'FullName', title: '商品全名' },
                { field: 'unitname', title: '单位' },
                 { field: 'qty', title: '促销数量' },
                { field: 'comment', title: '单据备注' },
                {
                    field: 'del', title: '删除', formatter: function (value, row, index) {
                        return "<button class='btn'><i class='glyphicon glyphicon-trash'></i> 删除</button>"
                    }
                }
            ], onClickCell: function (field, value, row, td) {
                if (field == "comment") { /*编辑商品行 备注*/
                    layer.confirm("<input id=\"comment\" type=\"text\" value='" + row["comment"] + "' />", { title: "单据备注", closeBtn: 2, }, function (idx) {
                        var comment = $("#comment").val().trim();
                        if (comment == row["comment"].trim()) {
                            layer.close(idx);
                        } else {
                            $.ajax({
                                url: "../WLTManage/SetPromoptype",
                                data: {
                                    typeid: row["TypeId_"],
                                    fieldValue: comment,
                                    fieldName: "comment",
                                    type: pagetype,
                                    billnumberid: $("#billnumberId").val()
                                },
                                datatype: "text",
                                type: "post",
                                success: function (data) {
                                    if (data == "ok") {
                                        row["comment"] = comment;
                                        $('#periodPromotionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row }); /*更行行数据*/
                                    }
                                    layer.close(idx);
                                }
                            })
                        }
                    });
                } else if (field == "price") {/*编辑商品行 价格*/
                    layer.confirm("<input id=\"price\" type=\"text\" value='" + row["price"] + "' />", { title: "促销价格", closeBtn: 2, }, function (idx) {
                        var price = $("#price").val().trim();
                        var reg = /^\d{1,}\.{0,1}\d{0,}$/;
                        if (!reg.test(price)) {
                            return;
                        };
                        if (price == row["price"].trim()) {
                            layer.close(idx);
                        } else {
                            price = $.NumberBzQz(price, 8);
                            $.ajax({
                                url: "../WLTManage/SetPromoptype",
                                data: {
                                    typeid: row["TypeId_"],
                                    fieldValue: price,
                                    fieldName: "price",
                                    type: pagetype,
                                    billnumberid: $("#billnumberId").val(),
                                },
                                datatype: "text",
                                type: "post",
                                success: function (data) {
                                    if (data == "ok") {
                                        row["price"] = price;
                                        $('#periodPromotionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row });/*更行行数据*/
                                    }
                                    layer.close(idx);
                                }
                            })
                        }
                    });
                } else if (field == "unitname") {
                    var typeid = row["TypeId_"]
                    var select;
                    $.ajax({
                        async: false,
                        url: "../WLTManage/GetUnitName",
                        data: {
                            typeid: typeid,
                            billnumberid: $("#billnumberId").val(),
                        }, datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "err") {
                                return;
                            }
                            select = data;
                        }
                    })
                    layer.confirm(select,
                        {
                            title: "单位",
                            success: function () { /*弹框成功回调*/
                                $("#UnitName").val(row["unitid"]);
                            }
                        },
                        function (idx) { /*确定按钮 点击事件*/
                            if ($("#UnitName").find("option:selected").text().trim() == row["unitname"].trim()) {
                                layer.close(idx);
                            } else {
                                var unitName = $("#UnitName").find("option:selected").text();
                                var unitId = $("#UnitName").val();
                                $.ajax({
                                    url: "../WLTManage/SetPromoptype",
                                    data: {
                                        typeid: row["TypeId_"],
                                        fieldValue: unitName,
                                        fieldName: "unitname",
                                        fieldValue2: unitId,
                                        fieldName2: "unitid",
                                        type: pagetype,
                                        billnumberid: $("#billnumberId").val(),
                                    },
                                    datatype: "text",
                                    type: "post",
                                    success: function (data) {
                                        if (data == "ok") {
                                            row["unitname"] = unitName;
                                            row["unitid"] = unitId;
                                            $('#periodPromotionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row });/*更行行数据*/
                                        }
                                        layer.close(idx);
                                    }
                                })
                            }
                        });
                } else if (field == "del") {
                    $.ajax({
                        url: "../WLTManage/DelPromoPtypeByID",
                        data: {
                            billnumberid: $("#billnumberId").val(),
                            typeid: row["TypeId_"]
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "ok") {
                                $('#periodPromotionTable').bootstrapTable("refreshOptions", {
                                    url: "../WLTManage/GetPeriodPromotion?billNid=" + $("#billnumberId").val() + "&" + new Date().getTime(),
                                    pageNumber: $('#periodPromotionTable').bootstrapTable('getOptions').pageNumber
                                })
                            }
                        }
                    })
                } else if (field == "qty") {
                    layer.confirm("<input id=\"qtys\" type=\"text\" value='" + row["qty"] + "' />", { title: "搭赠数量", closeBtn: 2, }, function (idx) {
                        var qty = $("#qtys").val().trim();
                        if (!/^([1-9][0-9]*)$/.test(qty)) {
                            layer.tips('请输入正整数！', '#qtys', {
                                tips: [1, "red"]
                            })
                            return;
                        }
                        if (qty == row["qty"].trim() && qty!="0") {
                            layer.close(idx);
                        } else {
                            $.ajax({
                                url: "../WLTManage/SetPromoptype",
                                data: {
                                    typeid: row["TypeId_"],
                                    fieldValue: qty,
                                    fieldName: "qty",
                                    billnumberid: $("#billnumberId").val()
                                },
                                datatype: "text",
                                type: "post",
                                success: function (data) {
                                    if (data == "ok") {
                                        row["qty"] = qty;
                                        $('#periodPromotionTable').bootstrapTable('updateRow', { index: row.index - 1, row: row });/*更行行数据*/
                                    }
                                    layer.close(idx);
                                }
                            })
                        }
                    });
                }
            }
        });
    }
    /*绑定适用客户信息*/
    function NotClientBind(billNumberID) {
        $('#NotToApplyCustomerTable').bootstrapTable({
            url: "../WLTManage/GetNoClient",
            method: 'post',                      //请求方式（*）
            toolbar: '#btnChooseNotToApplyCustomer',
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            minimumCountColumns: 2,  //最少允许的列数
            //height: "400",
            uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
            clickToSelect: true,              //是否启用点击选中行
            sortable: true,                     //是否启用排序
            silentSort: true,
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            paginationFirstText: '首页',
            paginationLastText: '末页',
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showColumns: false,            //是否显示所有的列
            showRefresh: false,              //是否显示刷新按钮
            showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
             cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                return {
                    pagesize: params.limit,//页面大小
                    page: params.offset, //页码
                    billNid: billNumberID,
                };
            }, columns: [
                {
                    field: "index", title: "序号", align: "center", width: 50, edit: false, formatter: function (value, row, index) {
                        return row.index = index + 1; //返回行号
                    }
                },
                { field: 'usercode', title: '单位编号' },
                { field: 'bfullname', title: '单位全名' },
                {
                    field: 'del', title: '删除', formatter: function (value, row, index) {
                        return "<button class='btn'><i class='glyphicon glyphicon-trash'></i> 删除</button>"
                    }
                }],
            onClickCell: function (field, value, row, td) {
                if (field == "del") {
                    $.ajax({
                        url: "../WLTManage/DelPromoBtypeByID",
                        data: {
                            btypeid: row["btypeid"],
                            billnumberid: $("#billnumberId").val(),
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            layer.msg("删除成功！", { time: 2000 });
                            $('#NotToApplyCustomerTable').bootstrapTable("refreshOptions", {
                                url: "../WLTManage/GetNoClient?billNid=" + $("#billnumberId").val() + "&" + new Date().getTime(),
                                pageNumber: $('#NotToApplyCustomerTable').bootstrapTable('getOptions').pageNumber
                            })
                        }
                    })
                }
            }
        });
    }
    /*绑定适用仓库信息*/
    function NotStockBind(billNumberID) {
        $('#NotToApplyTheWarehouseTable').bootstrapTable({
            url: "../WLTManage/GetNotStock",
            method: 'post',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            toolbar: '#btnChooseNotToApplyTheWarehouse',
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            minimumCountColumns: 2,  //最少允许的列数
            //height: "400",              //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
            clickToSelect: true,              //是否启用点击选中行
            sortable: true,                     //是否启用排序
            silentSort: true,
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            paginationFirstText: '首页',
            paginationLastText: '末页',
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showColumns: false,            //是否显示所有的列
            showRefresh: false,              //是否显示刷新按钮
            showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
             cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                return {
                    pagesize: params.limit,//页面大小
                    page: params.offset, //页码
                    billNid: billNumberID,
                };
            }, columns: [
                {
                    field: "index", title: "序号", align: "center", width: 50, edit: false, formatter: function (value, row, index) {
                        return row.index = index + 1; //返回行号
                    }
                },
                { field: 'usercode', title: '仓库编号' },
                { field: 'fullname', title: '仓库全名' },
                {
                    field: 'Del', title: '删除', formatter: function (value, row, index) {
                        return "<button class='btn'><i class='glyphicon glyphicon-trash'></i> 删除</button>"
                    }
                }
            ],
            onClickCell: function (field, value, row, td) {
                if (field == "Del") {
                    $.ajax({
                        url: "../WLTManage/DelPromoStockByID",
                        data: {
                            typeid: row["typeid"],
                            billnumberid: $("#billnumberId").val()
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "ok") {
                                layer.msg("删除成功！", { time: 2000 });
                                $('#NotToApplyTheWarehouseTable').bootstrapTable("refreshOptions", {
                                    url: "../WLTManage/GetNotStock?billNid=" + $("#billnumberId").val() + "&" + new Date().getTime(),
                                    pageNumber: $('#NotToApplyTheWarehouseTable').bootstrapTable('getOptions').pageNumber
                                })
                            }
                        }
                    })
                }
            }
        });
    }
    /*绑定适用业务员信息*/
    function NotSalesmanBind(billNumberID) {
        $('#NotToApplyToTheClerkTable').bootstrapTable({
            url: "../WLTManage/GetPromoEtype",
            method: 'post',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            toolbar: '#btnChooseNotToApplyToTheClerk',
            pagination: true,                   //是否显示分页（*）
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            minimumCountColumns: 2,  //最少允许的列数
            //height: "400",               //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
            clickToSelect: true,              //是否启用点击选中行
            sortable: true,                     //是否启用排序
            silentSort: true,
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            paginationFirstText: '首页',
            paginationLastText: '末页',
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showColumns: false,            //是否显示所有的列
            showRefresh: false,              //是否显示刷新按钮
            showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
             cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            queryParams: function (params) {
                return {
                    pagesize: params.limit,//页面大小
                    page: params.offset, //页码
                    billNid: billNumberID,
                };
            },//传递参数（*）
            columns: [
                {
                    field: "index", title: "序号", align: "center", width: 50, edit: false, formatter: function (value, row, index) {
                        return row.index = index + 1; //返回行号
                    }
                },
                { field: 'usercode', title: '业务员编号' },
                { field: 'fullname', title: '业务员名称' },
                 {
                     field: 'Del', title: '删除', formatter: function (value, row, index) {
                         return "<button class='btn'><i class='glyphicon glyphicon-trash'></i> 删除</button>"
                     }
                 }
            ],
            onClickCell: function (field, value, row, td) {
                if (field == "Del") {
                    $.ajax({
                        url: "../WLTManage/DelPromoEtype",
                        data: {
                            btypeid: row["etypeID"],
                            billnumberid: $("#billnumberId").val(),
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "ok") {
                                layer.msg("删除成功！", { time: 2000 });
                                $('#NotToApplyToTheClerkTable').bootstrapTable("refreshOptions", {
                                    url: "../WLTManage/GetPromoEtype?billNid=" + $("#billnumberId").val() + "&" + new Date().getTime(),
                                    pageNumber: $('#NotToApplyToTheClerkTable').bootstrapTable('getOptions').pageNumber
                                })
                            }
                        }
                    })
                }
            }
        });
    }
    /*获取单据号*/
    function GetNewCode() {
        $.ajax({
            url: "../WLTManage/GetNewCode",
            data: {
                promotype: "1"
            },
            datatype: "text",
            type: "post",
            success: function (data) {
                if (data == "err") {
                    layer.msg("单据编号生成失败", { icon: 2, time: 2000 });
                    return;
                }
                $("#billNid").val(data.substring(0, data.indexOf(',')));
                $("#billnumberId").val(data.substring(data.indexOf(',') + 1, data.indexOf(';')));
                $("#rsDate").val(data.substring(data.indexOf(';') + 1));
            }
        });
    }
    $(function () {
        var billNumberID = "";
        pagetype = parent.$("#pagtype").val(); /*获取页面状态*/
        if (pagetype == "Add") {
            GetNewCode();
        } else if (pagetype == "Edit") {
            var datarows = parent.$('#SelectPeriodPromotionTable').bootstrapTable("getData");
            var index = parent.$("#rowIndex").val();
            var datarow = datarows[index];
            $("#rsDate").val(datarow["CreateDate"]);
            $("#billNid").val(datarow["BillCode"]);
            $("#txtbfullname").val(datarow["PromoName"]);
            $("#rsRemark").val(datarow["Commet"]);
            $("#strdatename").val(datarow["StartTime"]);
            $("#enddatename").val(datarow["EndTime"]);
            $("#pmStartDate").val(datarow["StartDate"]);
            $("#pmEndDate").val(datarow["EndDate"]);
            var promoDayDetail = datarow["PromoDayDetail"].split(",");
            $(":checkbox").val(promoDayDetail);
            $("#billnumberId").val(datarow["BillNumberID"]);
            billNumberID = datarow["BillNumberID"];
            $.ajax({
                url: "../WLTManage/InsertIntoPromo",
                data: {
                    billNumberID: datarow["BillNumberID"]
                },
                datatype: "text",
                type: "get",
                async: false  //设置同步调用
            })
        }
        $(".i-checks").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });
        PromoGiveBind(billNumberID);
        PromoRuleBind(billNumberID);
        NotClientBind(billNumberID);
        NotStockBind(billNumberID);
        NotSalesmanBind(billNumberID);
        $(window).resize(function () {
            $('#periodGivetionTable').bootstrapTable('resetView');
            $('#NotToApplyCustomerTable').bootstrapTable('resetView');
            $('#NotToApplyTheWarehouseTable').bootstrapTable('resetView');
            $('#NotToApplyToTheClerkTable').bootstrapTable('resetView');
        });
        /*批量设置数量*/
        $("#btnSetCounts").on("click", function () {
            if ($("#periodGivetionTable").bootstrapTable("getData") == "") { /*无数据时 不可批量设置数量*/
                return;
            }
            layer.confirm('<input id="qty" type="text"  />', { title: '批量设置数量', closeBtn: 2 }, function (index) {
                var qty = $("#qty").val().trim();
                if (!qty) {
                    layer.close(index);
                    return;
                }
                if (!/^([1-9][0-9]*)$/.test(qty)) {
                    return;
                }
                $.ajax({
                    url: "../WLTManage/SetQty",
                    data: {
                        qty: qty
                    },
                    datatype: "text",
                    type: "post",
                    success: function (data) {
                        if (data == "ok") {
                            $('#periodGivetionTable').bootstrapTable("refresh", {
                                url: "../WLTManage/SavePromoGive?billNid=" + $("#billnumberId").val()
                            })
                        }
                    },
                    error: function () {

                    }
                })
                layer.close(index);
            });
        })
        /*批量设置数量*/
        $("#btnBatchSettingPqty").on("click", function () {
            if ($("#periodPromotionTable").bootstrapTable("getData") == "") { /*无数据时 不可批量设置价格*/
                return;
            }
            layer.confirm('<input id="pqty" type="text"  />', { title: '批量设置数量', closeBtn: 2 }, function (idx) {
                var pqty = $("#pqty").val();
                if (!pqty) {
                    layer.close(idx);
                    return;
                }
                if (!/^([1-9][0-9]*)$/.test(pqty)) {
                    return;
                }
                $.ajax({
                    url: "../WLTManage/SetPtypeqty",
                    data: {
                        pqty: pqty,
                        billnumberid: $("#billnumberId").val()
                    },
                    datatype: "text",
                    type: "post",
                    success: function (data) {
                        if (data == "ok") {
                            $('#periodPromotionTable').bootstrapTable("refresh", {
                                url: "../WLTManage/GetPeriodPromotion?billNid=" + $("#billnumberId").val()
                            })
                        }
                    },
                    error: function () {

                    }
                })
                layer.close(idx);
            })
        });
        /*选择赠送商品*/
        $("#btnSelectGive").on("click", function () {
            $("#CommodityBtypeid").val("");
            layer.open({
                type: 2,
                title: '选择商品',
                shadeClose: false,
                shade: 0.5,
                area: ['86%', '90%'],
                content: '../CommonSelector/CommoditySelectorMore',
                end: function () {
                    var commodityBtypeid = $("#CommodityBtypeid").val();
                    var billNid = $("#billnumberId").val();
                    if (commodityBtypeid) {
                        $('#periodGivetionTable').bootstrapTable("refresh", {
                            url: "../WLTManage/SavePromoGive?btypeid=" + commodityBtypeid + "&billNid=" + billNid
                        })

                    }
                }
            });
        })
        /*选择促销商品*/
        $("#btnSelectPromotionalItems").on("click", function () {
            $("#CommodityBtypeid").val("");
            var data=$('#periodPromotionTable').bootstrapTable("getData");
            if (data.length > 0) {
                layer.msg("促销商品只能选择一个", { time: 2000 });
                return;
            }
            layer.open({
                type: 2,
                title: '选择商品',
                shadeClose: false,
                shade: 0.5,
                area: ['86%', '90%'],
                content: '../CommonSelector/CommoditySelector',
                end: function () {
                    var commodityBtypeid = $("#CommodityBtypeid").val();
                    var billNid = $("#billnumberId").val();
                    if (commodityBtypeid) {
                        $('#periodPromotionTable').bootstrapTable("refresh", {
                            url: "../WLTManage/GetPeriodPromotion?btypeid=" + commodityBtypeid + "&billNid=" + billNid
                        })
                    }
                }
            });
        });
        /*选择适用客户*/
        $("#btnChooseNotToApplyCustomer").on("click", function () {
            $("#ClientBtypeid").val("");
            layer.open({
                type: 2,
                title: '选择适用客户',
                shadeClose: false,
                shade: 0.5,
                area: ['86%', '90%'],
                content: '../CommonSelector/ClientSelectorMore',
                end: function () {
                    var clientBtypeid = $("#ClientBtypeid").val();
                    var billNid = $("#billnumberId").val();
                    if (clientBtypeid) {
                        $('#NotToApplyCustomerTable').bootstrapTable("refresh", {
                            url: "../WLTManage/GetNoClient?btypeid=" + clientBtypeid + "&billNid=" + billNid
                        })
                    }
                }
            });
        });
        /*选择适用仓库*/
        $("#btnChooseNotToApplyTheWarehouse").on("click", function () {
            $("#Stockbtypeid").val("");
            layer.open({
                type: 2,
                title: '选择适用仓库',
                shadeClose: false,
                shade: 0.5,
                area: ['80%', '90%'],
                content: '../CommonSelector/StoreSelectorMore',
                end: function () {
                    var btypeid = $("#Stockbtypeid").val();
                    var billNid = $("#billnumberId").val();
                    if (btypeid) {
                        $('#NotToApplyTheWarehouseTable').bootstrapTable("refresh", {
                            url: "../WLTManage/GetNotStock?btypeid=" + btypeid + "&billNid=" + billNid
                        })
                    }
                }
            });
        });
        /*选择适用业务员*/
        $("#btnChooseNotToApplyToTheClerk").on("click", function () {
            $("#Employeebtypeid").val("");
            layer.open({
                type: 2,
                title: '选择适用业务员',
                shadeClose: false,
                shade: 0.5,
                area: ['86%', '90%'],
                content: '../CommonSelector/EmployeeSelectorMore',
                end: function () {
                    var Employeebtypeid = $("#Employeebtypeid").val();
                    var billNid = $("#billnumberId").val();
                    if (Employeebtypeid) {
                        $('#NotToApplyToTheClerkTable').bootstrapTable("refresh", {
                            url: "../WLTManage/GetPromoEtype?btypeid=" + Employeebtypeid + "&billNid=" + billNid
                        })
                    }
                }
            });
        });
    });
    //保存
    function SavePeriod() {
        var txtbfullname = $("#txtbfullname").val().trim();//时段促销单名称
        if (!txtbfullname) {
            layer.tips('时段促销单名称不能为空！', '#txtbfullname', {
                tips: [2, "red"]
            })
            return;
        }
        var strdatename = $("#strdatename").val();  /*开始时间*/
        if (!strdatename) {
            layer.tips('开始时间不能为空！', '#strdatename', {
                tips: [1, "red"]
            })
            return;
        }
        var enddatename = $("#enddatename").val(); /*结束时间*/
        if (!enddatename) {
            layer.tips('结束时间不能为空！', '#enddatename', {
                tips: [1, "red"]
            })
            return;
        } if (!$.TimeComparison(strdatename, enddatename)) {
            layer.tips('开始时间不能大于结束时间！', '#strdatename', {
                tips: [1, "red"]
            });
            return;
        }
        var pmStartDate = $("#pmStartDate").val(); /*促销开始日期*/
        if (!pmStartDate) {
            layer.tips('开始时间不能为空！', '#pmStartDate', {
                tips: [1, "red"]
            })
            return;
        }
        var pmEndDate = $("#pmEndDate").val();  /*促销结束日期*/
        if (!pmEndDate) {
            layer.tips('结束时间不能为空！', '#pmEndDate', {
                tips: [1, "red"]
            })
            return;
        }
        if (!$.DateComparison(pmStartDate, pmEndDate)) {
            layer.tips('开始日期不能大于结束日期！', '#pmStartDate', {
                tips: [1, "red"]
            });
            return;
        }
        var obj = document.getElementsByName("cbradios");
        var check_val = [];                 /*促销周期*/
        for (k in obj) {
            if (obj[k].checked)
                check_val.push(obj[k].value);
        }
        if (check_val.length < 1) {
            layer.tips('促销周期至少勾选一个！', '#checkbox', {
                tips: [1, "red"]
            })
            return;
        }
        if (!$("#billnumberId").val()) {
            layer.msg("单据ID生成失败,请联系管理员！", { icon: 3, time: 2000 });
            return;
        }
        if (!$.WeekComparison(pmStartDate, pmEndDate, check_val)) {
            layer.tips('选择促销周期超出促销日期时间段！', '#checkbox', {
                tips: [1, "red"]
            })
            return;
        }
        if ($('#periodPromotionTable').bootstrapTable('getData') == "") {
            $("#period").click();
            layer.tips('选择促销商品！', '#periodPromotionTable', { tips: [1, "red"] });
            return;
        }
        var count = $('#periodGivetionTable').bootstrapTable("getData");
        if (count.length < 1) {
            $("#give").click();
            layer.tips('选择搭赠商品！', '#periodGivetionTable', {
                tips: [1, "red"]
            });
            return;
        }
        if ($('#NotToApplyCustomerTable').bootstrapTable('getData') == "") {
            $("#client").click();
            layer.tips('选择适用客户！', '#NotToApplyCustomerTable', { tips: [1, "red"] });
            return;
        }
        if ($('#NotToApplyTheWarehouseTable').bootstrapTable('getData') == "") {
            $("#storc").click();
            layer.tips('选择适用仓库！', '#NotToApplyTheWarehouseTable', { tips: [1, "red"] });
            return;
        }
        if ($('#NotToApplyToTheClerkTable').bootstrapTable('getData') == "") {
            $("#salesman").click();
            layer.tips('选择适用业务员！', '#NotToApplyToTheClerkTable', { tips: [1, "red"] });
            return;
        }
        $.ajax({
            url: "../WLTManage/SaveAddOrEditPromo",
            data: {
                check: check_val.toString(),//促销周期
                pmStartDate: pmStartDate,//促销开始时间
                pmEndDate: pmEndDate,//促销结束时间
                strdatename: strdatename,//开始时间
                enddatename: enddatename,//结束时间
                txtbfullname: txtbfullname,//时段促销
                rsRemark: $("#rsRemark").val(),//摘要
                billNid: $("#billNid").val(),//促销单据
                billnumberId: $("#billnumberId").val(),//单据ID
                type: pagetype//页面类型
            },
            datatype: "text",
            type: "post",
            success: function (data) {
                if (data == "ok") {
                    parent.$('#SelectPeriodPromotionTable').bootstrapTable("refresh");
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);
                }
            }, error: function () {

            }
        })
    }
    </script>
    <script>  $(function () { $('.tabs a:last').tab('show') })</script>
</body>