@{
    ViewBag.Title = "新增配货协议";
    Layout = "~/Views/Shared/_LayoutTable.cshtml";
}
<body>
    <input id="uploadliginid" type="hidden" />
    <input type="hidden" id="CommodityBtypeid" />
    <input type="hidden" id="billnumberId" />

    <div class="container-fluid">
        <div class="row-fluid">
            <div class="col-lg-3 col-md-6 col-sm-6" style="margin-top:5px">
                <table id="AttendanceSetingTable" class="table table-bordered table-striped table-hover">
                    <tbody>
                        <tr>
                            <td style="text-align: right">协议名称：</td>
                            <td>
                                <input type="text" class="form-control" maxlength="18" name="address" id="txtBillHttpName" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-lg-3 col-md-6 col-sm-6" style="margin-top:5px">
                <table id="AttendanceSetingTable" class="table table-bordered table-striped table-hover">
                    <tbody>
                        <tr>
                            <td style="text-align: right">客户名称：</td>
                            <td>
                                <input type="text" class="form-control" id="fullname" disabled="disabled" />
                            </td>
                            <td>
                                <button onclick="ClientName()" class="glyphicon glyphicon-plus btn btn-default"></button>
                                <button class="glyphicon glyphicon-minus btn btn-default" onclick="Clear()"></button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-lg-3 col-md-6 col-sm-6" style="margin-top:5px">
                <table id="AttendanceSetingTable" class="table table-bordered table-striped table-hover">
                    <tbody>
                        <tr>
                            <td style="text-align: right">生效时间：</td>
                            <td>
                                <input type="text" class="form-control" onfocus="WdatePicker({isShowClear:false,readOnly:true})" id="pmStartDate" value="" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-lg-3 col-md-6 col-sm-6" style="margin-top:5px">
                <table id="AttendanceSetingTable" class="table table-bordered table-striped table-hover">
                    <tbody>
                        <tr>
                            <td style="text-align: right">失效时间：</td>
                            <td>
                                <input type="text" class="form-control" onfocus="WdatePicker({isShowClear:true,readOnly:true})" id="pmEndDate" value="" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-md-12">
                <div id="toolbar">
                    <button class="btn-default btn" onclick="SelectBtype()"><i class="glyphicon glyphicon-th"></i>选择商品</button>
                    <button class="btn-default btn" onclick="BatchSet()"><i class="glyphicon glyphicon-wrench"></i>批量设置</button>
                    <button class="btn-default btn" onclick="SaveHttpBill()"><i class="glyphicon glyphicon-saved"></i>保存协议</button>
                    <button class="btn-default btn" onclick="IntoHttpBill()"><i class="glyphicon glyphicon-floppy-save"></i>一键导入</button>
                </div>
                <table id="httpbilltab"></table>
            </div>
        </div>
    </div>
    <script type="text/javascript">

    var pagetype = "Add";
    /*一键导入*/
    function IntoHttpBill() {
        var httpBillName = $("#txtBillHttpName").val().trim();
        if (!httpBillName) {
            layer.tips('请选择协议名', '#txtBillHttpName', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var fullName = $("#fullname").val().trim();
        if (!fullName) {
            layer.tips('请选择客户名称', '#fullname', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var staDate = $("#pmStartDate").val().trim();
        if (!staDate) {
            layer.tips('请选择生效时间', '#pmStartDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var endDate = $("#pmEndDate").val().trim();
        if (!endDate) {
            layer.tips('请选择失效时间', '#pmEndDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        }
        if (!$.DateComparison(staDate, endDate)) {
            layer.tips('失效时间不能小于生效时间', '#pmEndDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        }
        layer.confirm('<table class="table table-bordered table-striped table-hover"><tr><td>开始时间：</td><td><input type="text"   onfocus="WdatePicker({isShowClear:false,readOnly:true})" id="staDate" value="" /></td></tr>'
           + '<tr><td>结束时间：</td><td><input type="text"   onfocus="WdatePicker({isShowClear:false,readOnly:true})" id="endDate" value="" /></td></td></tr></table>',
           { title: "导入时间段" }, function (index) {
               var staDate = $("#staDate").val();
               var endDate = $("#endDate").val();
               if (staDate != "" && endDate != "") {
                   if (!$.DateComparison(staDate, endDate)) {
                       layer.tips('结束时间不能小于开始时间', '#endDate', { tips: [1, "red"], icon: 1, time: 2000 })
                       return false;
                   }
               }
               else {
                   if (staDate=="") {
                       layer.tips('请选择日期', '#staDate', { tips: [1, "red"], icon: 1, time: 2000 })
                   } else if (endDate=="") {
                       layer.tips('请选择日期', '#endDate', { tips: [1, "red"], icon: 1, time: 2000 })
                   }
                   return false;
               }
               $.ajax({
                   url: "../Shop/IntoHttpBill",
                   data: {
                       staDate: staDate,
                       endDate: endDate,
                       btypeid: $("#uploadliginid").val(),
                       billNid: $("#billnumberId").val()
                   },
                   datatype: "text",
                   type: "post",
                   success: function (data) {
                       if (data == "ok") {
                           $("#httpbilltab").bootstrapTable("refresh", { url: "../Shop/SaveHttpPtype?billNid=" + $("#billnumberId").val() });
                          parent.layer.msg("导入成功!", { time: 2000 });
                       }
                       else {
                           layer.msg(staDate + "至" + endDate + "期间此客户无销售记录!", { time: 2000 });
                       }
                       layer.close(index);
                   }, error: function () {
                       layer.close(index);
                   }
               });
           })
    }
    /*保存协议*/
    function SaveHttpBill() {
        var httpBillName = $("#txtBillHttpName").val().trim();
        if (!httpBillName) {
            layer.tips('请选择协议名', '#txtBillHttpName', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var fullName = $("#fullname").val().trim();
        if (!fullName) {
            layer.tips('请选择客户名称', '#fullname', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var staDate = $("#pmStartDate").val().trim();
        if (!staDate) {
            layer.tips('请选择生效时间', '#pmStartDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        var endDate = $("#pmEndDate").val().trim();
        if (!endDate) {
            layer.tips('请选择失效时间', '#pmEndDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        } if ($("#httpbilltab").bootstrapTable("getData") == "") {
            layer.tips('请选择商品', '#httpbilltab', { tips: [1, "red"], icon: 1, time: 2000 })
            return;
        }
        if (!$.DateComparison(staDate, endDate)) {
            layer.tips('失效时间不能小于生效时间', '#pmEndDate', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        }
        var billnumberId = $("#billnumberId").val().trim();
        if (!billnumberId) return;
        var btypeid = $("#uploadliginid").val().trim();
        $.ajax({
            url: "../Shop/SaveAddHttpBill",
            data: {
                billnumberId: billnumberId,
                httpBillName: httpBillName,
                btypeid: btypeid,
                staDate: staDate,
                endDate: endDate,
                pagetype: pagetype
            },
            datatype: "text",
            type: "post",
            success: function (data) {
                if (data == "ok") {
                    parent.$('#configurationTable').bootstrapTable("refresh");
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);
                } else if (data == "errqty") {
                    layer.msg("商品信息单价和数量不能为空或为0！", { time: 2000 });
                }
            }
        })
    }
    /*绑定商品列表信息*/
    function Bind(billNid) {
        $("#httpbilltab").bootstrapTable({
            url: "../Shop/SaveHttpPtype",         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 30, 50],        //可供选择的每页的行数（*）
            minimumCountColumns: 2,  //最少允许的列数
            //height: "100%",               //行高，如果没有设置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").val().trim(),
                };
            },//传递参数（*）
            columns: [
                {
                    field: 'index', title: '序号', formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                { field: 'UserCode', title: '商品编号', width: 160 },
                { field: 'TypeName', title: '商品名称', width: 400 },
                { field: 'Price', title: '协议单价' },
                { field: 'qty', title: '协议数量' },
                { field: 'Comment', title: '备注' },
                {
                    field: 'operation', 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 == "Price") {
                    layer.confirm('<input id="price" type="text" value="' + row["Price"] + '"   />', { title: "协议单价" }, function (index) {
                        var price = $("#price").val().trim();
                        var reg = /^\d{1,}\.{0,1}\d{0,}$/;
                        if (reg.test(price)) {
                            price = $.NumberBzQz(price, 8);
                        } else {
                            return;
                        };
                        $.ajax({
                            url: "../Shop/SetPriceOrQtyOrComment",
                            data: {
                                value: price,
                                field: field,
                                typeid: row["TypeId_"]
                            },
                            dataType: "text",
                            type: "post",
                            success: function (data) {
                                if (data == "ok") {
                                    row["Price"] = price;
                                    $('#httpbilltab').bootstrapTable('updateRow', { index: row.index - 1, row: row }); /*更行行数据*/
                                }
                            }
                        })
                        layer.close(index);
                    })
                } else if (field == "qty") {
                    layer.confirm('<input id="qty" type="text" value="' + row["qty"] + '"   />', { title: "协议数量" }, function (index) {
                        var qty = $("#qty").val().trim();
                        if (!/^(0|[1-9][0-9]*)$/.test(qty)) {
                            return;
                        };
                        $.ajax({
                            url: "../Shop/SetPriceOrQtyOrComment",
                            data: {
                                value: qty,
                                field: field,
                                typeid: row["TypeId_"]
                            },
                            dataType: "text",
                            type: "post",
                            success: function (data) {
                                if (data == "ok") {
                                    row["qty"] = qty;
                                    $('#httpbilltab').bootstrapTable('updateRow', { index: row.index - 1, row: row }); /*更行行数据*/
                                }
                            }
                        })
                        layer.close(index);
                    })
                } else if (field == "Comment") {
                    layer.confirm('<input id="comment" type="text"    value="' + row["Comment"] + '"  />', { title: "协议备注" }, function (index) {
                        var comment = $("#comment").val().trim();
                        $.ajax({
                            url: "../Shop/SetPriceOrQtyOrComment",
                            data: {
                                value: comment,
                                field: field,
                                typeid: row["TypeId_"]
                            },
                            dataType: "text",
                            type: "post",
                            success: function (data) {
                                if (data == "ok") {
                                    row["Comment"] = comment;
                                    $('#httpbilltab').bootstrapTable('updateRow', { index: row.index - 1, row: row }); /*更行行数据*/
                                }
                            }
                        })
                        layer.close(index);
                    })
                } else if (field == "operation") {
                    $.ajax({
                        url: "../Shop/DelHttpPtype",
                        data: {
                            typeid: row["TypeId_"],
                            billnid: $("#billnumberId").val().trim()
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "ok") {
                                layer.msg("删除成功！", { time: 2000 });
                                $("#httpbilltab").bootstrapTable("refreshOptions", {
                                    url: "../Shop/SaveHttpPtype?billNid=" + $("#billnumberId").val().trim() + "&" + new Date().getTime(),
                                    pageNumber: $('#httpbilltab').bootstrapTable('getOptions').pageNumber
                                });
                            }
                        }
                    })
                }
            }
        });
    }
    /*选择商品*/
    function SelectBtype() {
        if (!$("#txtBillHttpName").val().trim()) {
            layer.tips('请选择协议名', '#txtBillHttpName', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        if (!$("#fullname").val().trim()) {
            layer.tips('请选择客户名称', '#fullname', { tips: [2, "red"], icon: 1, time: 2000 })
            return;
        };
        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) {
                    $("#httpbilltab").bootstrapTable("refresh", {
                        url: "../Shop/SaveHttpPtype?billNid=" + billNid + "&BtypeId=" + commodityBtypeid
                    });
                }
            }
        });
    };
    /*批量设置单价 数量*/
    function BatchSet() {
        if (!$("#txtBillHttpName").val().trim()) {
            layer.tips('请选择协议名', '#txtBillHttpName', { tips: [2, "red"], icon: 1, time: 2000 });
            return;
        };
        if (!$("#fullname").val().trim()) {
            layer.tips('请选择客户名称', '#fullname', { tips: [2, "red"], icon: 1, time: 2000 });
            return;
        };
        if ($("#httpbilltab").bootstrapTable("getData") == "") { /*无数据时 不可批量设置*/
            layer.tips('请选择商品', '#httpbilltab', { tips: [1, "red"], icon: 1, time: 2000 })
            return;
        }
        layer.confirm('<table class="table table-bordered table-striped table-hover"><tr><td>协议单价：</td><td><input id="txtprice" type="text"   /></td></tr> <tr><td>协议数量：</td><td><input id="txtqty" type="text"  /></td></tr></table>', { title: '批量设置' }, function (index) {
            var price = $("#txtprice").val().trim();
            var qty = $("#txtqty").val().trim();
            if (!price && !qty) {
                layer.close(index);
            };
            var reg = /^\d{1,}\.{0,1}\d{0,}$/;
            if (reg.test(price)) {
                price = $.NumberBzQz(price, 8);
            } else {
                layer.tips('请输入正确价格', '#txtprice', { tips: [1, "red"], icon: 1, time: 2000 });
                return;
            };
            if (!/^(0|[1-9][0-9]*)$/.test(qty)) {
                layer.tips('请输入正确数量', '#txtqty', { tips: [1, "red"], icon: 1, time: 2000 })
                return;
            };
            $.ajax({
                url: "../Shop/SetPriceQty",
                data: {
                    price: price,
                    qty: qty,
                    billNid: $("#billnumberId").val()
                },
                datatype: "text",
                type: "post",
                success: function (data) {
                    if (data == "ok") {
                        $("#httpbilltab").bootstrapTable("refresh", {
                            url: "../Shop/SaveHttpPtype?billNid=" + $("#billnumberId").val()
                        });
                        layer.close(index);
                    } else {
                        layer.msg("设置失败！", { time: 2000 });
                    }
                   
                }, error: function () {
                    layer.msg("连接超时！", { time: 2000 });
                }
            })
        });
    }
    /*清除客户*/
    function Clear() {
        $("#fullname").val("");
        $("#uploadliginid").val("");
    }
    /*选择客户*/
    function ClientName() {
        layer.open({
            type: 2,
            title: '客户信息',
            shadeClose: false,
            shade: 0.5,
            area: ['90%', '95%'],
            content: '../CommonSelector/ClientSelector'
        });
    }
    /*获取单据号*/
    function GetNewCode() {
        $.ajax({
            url: "../Shop/GetNewCode",
            data: {},
            datatype: "text",
            type: "post",
            success: function (data) {
                $("#billnumberId").val(data);
            }
        });
    }
    $(function () {
        pagetype = parent.$("#pagtype").val();
        if (pagetype == "Edit") {
            var datarows = parent.$('#configurationTable').bootstrapTable("getData");
            var index = parent.$("#rowIndex").val();
            var datarow = datarows[index];
            $("#txtBillHttpName").val(datarow["Billhttpname"]);
            $("#fullname").val(datarow["FullName"]);
            $("#pmStartDate").val(datarow["BillDate"]);
            $("#pmEndDate").val(datarow["BillArriveDate"]);
            $("#uploadliginid").val(datarow["BTypeid"]);
            $("#billnumberId").val(datarow["billid"]);
            $.ajax({
                url: "../Shop/SavePromoHttpPtpype",
                data: {
                    billNid: datarow["billid"]
                },
                datatype: "text",
                type: "get",
                async: false  //设置同步调用
            })
        } else {
            GetNewCode();
        }
        Bind($("#billnumberId").val());
    });
    </script>
</body>
