@{
    ViewBag.Title = "新增简单拜访";
    Layout = "~/Views/Shared/_LayoutTable.cshtml";
}
<head>
    <link href="~/BootStrap/ReOrder/bootstrap-table-reorder-rows.css" rel="stylesheet" />
</head>
<body>
    <div class="container-fluid">
        <div class="row-fluid" style="padding: 10px; margin-top: 10px; border-radius: 10px;">
            <div class="col-lg-6 col-md-6 col-sm-6">
                <div class="form-inline">
                    <div class="form-group">
                        <lable>时间段：</lable>
                        <input type="text" class="form-control" onFocus="WdatePicker({ isShowClear: true, readOnly: true })" id="txtStartDate" value="@ViewBag.startDate" @{ @(ViewBag.startDate != null && ViewBag.startDate != "" ? "disabled='disabled'" : "")     } />
                        <input type="text" class="form-control" onFocus="WdatePicker({isShowClear:true,readOnly:true})" id="txtEndDate" value="@ViewBag.endDate" @{ @(ViewBag.endDate != null && ViewBag.endDate != "" ? "disabled='disabled'" : "")    } />
                    </div>
                </div>
            </div>
            <div class="col-lg-5 col-md-5 col-sm-5">
                <div class="form-inline">
                    <div class="form-group">
                        <lable>业务员：</lable>
                        <select id="ddlSalesman" data-placeholder="请选择业务员" class="chosen-select">
                            @{
                                if (@ViewBag.ulist != null && @ViewBag.ulist.Rows.Count > 0)
                                {
                                    for (int i = 0; i < @ViewBag.ulist.Rows.Count; i++)
                                    {
                                        <option @(@ViewBag.ulist.Rows[i]["TypeID_"].ToString() == @ViewBag.etypeid ? "selected" : "") value=@ViewBag.ulist.Rows[i]["TypeID_"].ToString()>@ViewBag.ulist.Rows[i]["FullName"].ToString()</option>
                                    }
                                }
                            }
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-lg-1  col-md-1 col-sm-1">
                <button id="btnSave" onclick="Save()" class="btn btn-default"><i class="glyphicon glyphicon-save"></i>保存</button>
            </div>
        </div>
        <div class="row-fluid" style="margin-top: 10px">
            <div class="col-lg-12">
                <div class="alert alert-info alert-dismissable" style="margin-top: 5px">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <strong>注意! </strong>按住鼠标可拖动排序.修改后需保存提交
                </div>
                <div id="toolbar">
                    <button id="btnNewCallCustomer" onclick="NewCallCustomer()" class="btn btn-default"><i class="glyphicon glyphicon-plus-sign"></i>选择客户</button>
                    <button id="btnNewCallCustomers" onclick="NewCallCustomers()" class="btn btn-default"><i class="glyphicon glyphicon-plus-sign"></i>按线路选择客户</button>
                </div>
                <input type="hidden" id="etypeid" />
                <input type="hidden" id="billid" value="@ViewBag.billid" />
                <input type="hidden" id="btypeid" />
                <input type="hidden" id="bnum" />
                <input type="hidden" id="ClientBtypeid" />
                <input id="hidBillid" type="hidden" />
                <input id="isornosave" type="hidden" />
                <table id="NewSimpleCPTable" data-use-row-attr-func="true" data-reorderable-rows="true"></table>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var oldcount = 0;
        function today() {//取当前时间
            var today = new Date();
            var h = today.getFullYear();
            var m = today.getMonth() + 1;
            var d = today.getDate();
            if (m < 10) {
                m = "0" + m;
            }
            if (d < 10) {
                d = "0" + d;
            }
            return h + "-" + m + "-" + d;
        }
        function Save() {//保存
            $("#btnSave").attr("disabled", true);
            var data = $("#NewSimpleCPTable").bootstrapTable("getData");
            var obj = document.getElementById("ddlSalesman"); //定位id
            var index = obj.selectedIndex; // 选中索引
            var etypename = obj.options[index].text; // 选中文本
            var cusinfo = "";
            if ($.trim($("#txtStartDate").val()).length <= 0 || $.trim($("#txtEndDate").val()).length <= 0) {
                layer.msg("请选择日期段！"); return false;
            }
            if ($.trim($("#ddlSalesman").val()).length <= 0) {
                layer.msg("请选择业务员！"); return false;
            }
            if (data.length <= 0) {
                layer.msg("请选择要拜访的客户！"); return false;
            } else {
                for (var i = 0; i < data.length; i++) {
                    if (i == data.length - 1) {
                        cusinfo += data[i].btypeid + ":" + data[i].bfullname + ":" + data[i].address;
                    } else {
                        cusinfo += data[i].btypeid + ":" + data[i].bfullname + ":" + data[i].address + ",";
                    }
                }
                $.ajax({
                    url: "../Shop/SaveCallPlanning",
                    dataType: "text",
                    data: {
                        strdate: $("#txtStartDate").val(),
                        enddate: $("#txtEndDate").val(),
                        etypeid: $.trim($("#ddlSalesman").val()),
                        etypename: etypename,
                        billid: $("#billid").val(),
                        customer: cusinfo
                    },
                    type: "post",
                    success: function (data) {
                        parent.$("#SimpleCallPlanningTable").bootstrapTable("refresh");
                        parent.layer.msg(data);
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    },
                    error: function (data) {
                        layer.msg(data);
                    }
                })
            }
        }


        function Del(btypeid) {//行删除按钮
            layer.confirm("确认删除？", function (enter) {//删除前提示
                if (enter) {
                    $("#NewSimpleCPTable").bootstrapTable('removeByUniqueId', btypeid);
                    parent.$("#isornodel").val("yes");
                    layer.msg("删除成功！", { time: 2000 });
                    var index = layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    layer.close(index);
                }
            })
        }
        function NewCallCustomers() {//按线路选择客户
            if ($.trim($("#txtStartDate").val()).length <= 0 || $.trim($("#txtEndDate").val()).length <= 0) {
                layer.msg("请选择日期段！"); return;
            }
            var beginDate = $("#txtStartDate").val();
            var endDate = $("#txtEndDate").val();
            var bd = new Date(beginDate.replace(/\-/g, "\/"));
            var ed = new Date(endDate.replace(/\-/g, "\/"));

            if (beginDate != "" && endDate != "" && bd > ed) {
                layer.msg("开始时间不得晚于结束时间！"); return;
            }
            if ($.trim($("#ddlSalesman").val()).length <= 0) {
                layer.msg("请选择业务员！"); return;
            }
            var edit = '@ViewBag.etypeid';
            if (edit != null && edit != "") {
                layer.open({
                    type: 2,
                    title: '<i class="glyphicon glyphicon-plus-sign"></i> 按线路选择客户',
                    shadeClose: false,
                    shade: 0.5,
                    area: ['80%', '90%'],
                    content: '../Shop/V_SimpleSelectCallPlanning?etypeid=' + $.trim($("#ddlSalesman").val()) + '&begindate=' + $("#txtStartDate").val() + '&enddate=' + $("#txtEndDate").val(),
                    end: function () {//关闭弹窗后
                    }
                });
            } else {
                var cusid = '@ViewBag.cusid';
                var startdate = '@ViewBag.sdate'
                var enddate = '@ViewBag.edate'
                var cusids = cusid.split(",");
                var startdates = startdate.split(",");
                var enddates = enddate.split(",");
                for (var i = 0; i < cusids.length; i++) {
                    var obd = startdates[i];
                    var nbd = enddates[i];
                    var str = new Date(obd.replace(/\-/g, "\/"));
                    var end = new Date(nbd.replace(/\-/g, "\/"));
                    if (cusids[i] == $("#ddlSalesman").val() && str <= bd && end >= ed || cusids[i] == $("#ddlSalesman").val() && str >= bd && end <= ed) {
                        layer.msg("已存在该时间段的拜访！"); return;
                    }
                }
                layer.open({
                    type: 2,
                    title: '<i class="glyphicon glyphicon-plus-sign"></i> 按线路选择客户',
                    shadeClose: false,
                    shade: 0.5,
                    area: ['80%', '90%'],
                    content: '../Shop/V_SimpleSelectCallPlanning?etypeid=' + $.trim($("#ddlSalesman").val()) + '&begindate=' + $("#txtStartDate").val() + '&enddate=' + $("#txtEndDate").val(),
                    end: function () {//关闭弹窗后
                    }
                });
            }
        }
        function NewCallCustomer() {//选择客户
            $('#ClientBtypeid').val("");
            if ($.trim($("#txtStartDate").val()).length <= 0 || $.trim($("#txtEndDate").val()).length <= 0) {
                layer.msg("请选择日期段！"); return;
            }
            var beginDate = $("#txtStartDate").val();
            var endDate = $("#txtEndDate").val();
            var bd = new Date(beginDate.replace(/\-/g, "\/"));
            var ed = new Date(endDate.replace(/\-/g, "\/"));

            if (beginDate != "" && endDate != "" && bd > ed) {
                layer.msg("开始时间不得晚于结束时间！"); return;
            }
            if ($.trim($("#ddlSalesman").val()).length <= 0) {
                layer.msg("请选择业务员！"); return;
            }
            var edit = '@ViewBag.etypeid';
            if (edit != null && edit != "") {
                layer.open({
                    type: 2,
                    title: '<i class="glyphicon glyphicon-plus-sign"></i> 选择客户',
                    shadeClose: false,
                    shade: 0.5,
                    area: ['80%', '90%'],
                    content: '../CommonSelector/ClientSelectorMore',
                    end: function () {//关闭弹窗后
                    }
                });
            } else {
                var cusid = '@ViewBag.cusid';
                var startdate = '@ViewBag.sdate'
                var enddate = '@ViewBag.edate'
                var cusids = cusid.split(",");
                var startdates = startdate.split(",");
                var enddates = enddate.split(",");
                for (var i = 0; i < cusids.length; i++) {
                    var obd = startdates[i];
                    var nbd = enddates[i];
                    var str = new Date(obd.replace(/\-/g, "\/"));
                    var end = new Date(nbd.replace(/\-/g, "\/"));
                    if (cusids[i] == $("#ddlSalesman").val() && str <= bd && end >= ed || cusids[i] == $("#ddlSalesman").val() && str >= bd && end <= ed) {
                        layer.msg("已存在该时间段的拜访！"); return;
                    }
                }
                layer.open({
                    type: 2,
                    title: '<i class="glyphicon glyphicon-plus-sign"></i> 选择客户',
                    shadeClose: false,
                    shade: 0.5,
                    area: ['80%', '90%'],
                    content: '../CommonSelector/ClientSelectorMore',
                    end: function () {//关闭弹窗后
                    }
                });
            }
        }
        $(function () {
            if ("@ViewBag.billid" == "") {
                $("#txtStartDate").val(today());
                $("#txtEndDate").val(today());
            }
            $('#NewSimpleCPTable').bootstrapTable({//线路信息
                url: '../Shop/GetNewSimpleCPList?billid=@ViewBag.billid',         //请求后台的URL（*）
                method: 'post',                      //请求方式（*）
                toolbar: '',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                pagination: false,                   //是否显示分页（*）
                sortOrder: "asc",                   //排序方式
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                //height: "100%",               //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "btypeid",            //每一行的唯一标识，一般为主键列
                undefinedText: ' ',
                clickToSelect: true,              //是否启用点击选中行
                sortable: true,                     //是否启用排序
                undefinedText: ' ',
                silentSort: true,
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: false,
                showColumns: false,            //是否显示所有的列
                showRefresh: false,              //是否显示刷新按钮
                showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                rowReorder: true,
                columns: [
                    {
                        title: '拜访顺序', width: '5%', align: 'center',
                        formatter: function (value, row, index) {
                            var pageNumber = $('#NewSimpleCPTable').bootstrapTable('getOptions').pageNumber;
                            var pageSize = $('#NewSimpleCPTable').bootstrapTable('getOptions').pageSize;
                            return (pageNumber - 1) * pageSize + index + 1;
                        }
                    },
                    { field: "usercode", title: "客户编号", width: '10%' },
                    { field: "btypeid", title: "btypeid" },
                    { field: "bfullname", title: "客户名称", width: '20%' },
                     {
                         field: "Area", title: "地区", width: '10%', formatter: function (value, row, index) {
                             if (!(value)) {
                                 return value;
                             } else {
                                 return "";
                             }
                         }
                     },
                { field: "address", title: "地址", width: '30%' },
                    {
                        field: "Edit", title: "操作", width: '25%', align: 'center', formatter: function (value, row, index) {

                            var strHtml = '<button id="btnDelete"     class="btn btn-default" onclick="Del(\'' + row.btypeid + '\')"><i class="glyphicon glyphicon-trash"></i> 删除</button>';
                            return strHtml;
                        }
                    }
                ]
            });
            //隐藏列
            //$('#NewSimpleCPTable').bootstrapTable('hideColumn', 'enddate');
            //$('#NewSimpleCPTable').bootstrapTable('hideColumn', 'etypeid');
            //$('#NewSimpleCPTable').bootstrapTable('hideColumn', 'Num');
            $('#NewSimpleCPTable').bootstrapTable('hideColumn', 'btypeid');

        });
    </script>
</body>
