<%@include file="/WEB-INF/common/layouts/common.jsp" %>
<%@ page language="java" pageEncoding="UTF-8" %>
<html>
<head>
    <title>${entity.id}</title>
    <style>
        input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
            height: 10px;
        }
    </style>

</head>
<body>
<link rel="stylesheet" type="text/css" href="${static_common}/jqGrid/css/ui.jqgrid.css"/>
<%--<link rel="stylesheet" type="text/css" href="${static_common}/jqGrid/css/ui.jqgrid-bootstrap.css"/>--%>
<%--<link rel="stylesheet" type="text/css" href="${static_common}/jqGrid/css/ui.jqgrid-bootstrap-ui.css"/>--%>
<link rel="stylesheet" type="text/css" href="${static_common}/jqGrid/css/redmond/jquery-ui-1.8.16.custom.css"/>
<link rel="stylesheet" type="text/css" href="${static_common}/jquery-ui/jquery-ui.min.css"/>
<!-- 面包屑 begin -->
<div class="row-fluid">
    <div class="span12">
        <ul class="breadcrumb">
            <li>
                <span class="divider" style="color:#26a0da;font-weight:bold;">/</span>
                <a href="${ctx}/reportmarketing/daily?type=localreport">驻场日报管理</a>
            </li>
            <li class="active">
                <span class="divider" style="color:#26a0da;font-weight:bold;">/</span>
                <c:choose>
                    <c:when test="${action=='create'}">
                        <span class="inline">新增</span>
                    </c:when>
                    <c:when test="${action=='edit'}">
                        <span class="inline"> ${entity.id} </span>
                    </c:when>
                    <c:otherwise>
                        <span class="inline"> ${entity.id}</span>
                    </c:otherwise>
                </c:choose>
            </li>
        </ul>
    </div>
</div>
<!-- 面包屑 end -->
<house365:flushMessage/>

<input id="reportDateStr" name="reportDateStr" type="hidden"
       value="<fmt:formatDate value="${recordate}" type="date" pattern="yyyy-MM-dd"/>"/>

<input type="hidden" name="currentProject" id="currentProject" value="${currentProject}"/>

<table id="list"></table>
<div id="pager"></div>

<div id="dialog" style="display: none;">
    <p>处理中...</p>
</div>

<div id="confirmDialog" style="display: none;">
    <p style="font-size: 12px;">是否切换项目？未保存的数据在切换后将会丢失.</p>
</div>

<script src="${static_common}/jqGrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="${static_common}/jqGrid/src/i18n/grid.locale-cn.js" type="text/javascript"></script>
<script src="${static_common}/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>

<script>
    //保存时save编辑中row
    var lastsel, hasChange = false ;
    $(function () {
        //页面加载完成之后执行
        pageInit();
        $("#dialog").dialog({
            autoOpen: false,
            modal: true,
            show: {
                effect: "blind",
                duration: 100
            },
            hide: {
                effect: "explode",
                duration: 100
            }
        });

        $("#confirmDialog").dialog({
            dialogClass: "no-close",
            autoOpen: false,
            modal: true,
            show: {
                effect: "blind",
                duration: 100
            },
            hide: {
                effect: "explode",
                duration: 100
            }
        });

    });
    function pageInit() {
        //创建jqGrid组件
        var mygrid = jQuery("#list").jqGrid(
            {
                height: $(window).height() - 80,
                width: $(window).width() - 80,
                rownumbers: true, //设置列表显示序号,需要注意在colModel中不能使用rn作为index
                rownumWidth: 20, //设置显示序号的宽度
                url: "${ctx}/localreport/getTableData?projectId=" + $("#currentProject").val() + "&reportDateStr=" + $("#reportDateStr").val(), //组件创建完成之后请求数据的url
                datatype: "json", //请求数据返回的类型。可选json,xml,txt
                colNames: ['渠道ID', '渠道', '部门ID', '部门', '职员ID', '姓名', '报备', '到访', '认筹', '认购', '业绩'],//jqGrid的列显示名字
                colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                    {name: 'channelId', index: 'channelId', width: 50, editable: true, hidden: true},
                    {name: 'channelName', index: 'channelName', width: 150},
                    {name: 'departId', index: 'departId', width: 50, editable: true, hidden: true},
                    {name: 'departName', index: 'departName', width: 150},
                    {name: 'userId', index: 'userId', width: 50, editable: true, hidden: true},
                    {name: 'name', index: 'name', width: 100},
                    {name: 'record', index: 'record', width: 50, editable: true, editrules: {number: true,maxValue:99999}},
                    {name: 'visit', index: 'visit', width: 50, editable: true, editrules: {number: true,maxValue:99999}},
                    {name: 'buyorder', index: 'buyorder', width: 50, editable: true, editrules: {number: true,maxValue:99999}},
                    {name: 'buy', index: 'buy', width: 50, editable: true, editrules: {number: true,maxValue:99999}},
                    {
                        name: 'score',
                        index: 'score',
                        width: 50,
                        editable: true,
                        editrules: {number: true, maxValue: 999999}
                    }
                ],
                rowNum: 10000,//一页显示多少条
                rowList: [10000],//可供用户选择一页显示多少条
                pager: '#pager',//表格页脚的占位符(一般是div)的id
                sortname: 'channelId',//初始化的时候排序的字段
                sortorder: "desc",//排序方式,可选desc,asc
                mtype: "post",//向后台请求数据的ajax的类型。可选post,get
                loadonce: true,
                viewrecords: true,
                gridview: true,
                viewsortcols: true,
                toolbar: [true, "top"],
                caption: "驻场日报管理",//表格的标题名字
                onSelectRow: function (id) {
                    if (id && id !== lastsel) {
                        jQuery('#list').jqGrid('saveRow', lastsel, {
                            //仅保存数据到grid中，不会向服务器提交数据
                            url: 'clientArray',
                            successfunc: function (response) {
                                return true;
                            }
                        });
                        jQuery('#list').jqGrid('editRow', id, true);
                        lastsel = id;
                    }

                    $(".editable", "#list").on('input', function(){
                        hasChange = true;
                    });
                },
                beforeProcessing: function (data) {
                    var deptMap = {}, labelMap = {}, valueMap = {}, i, item, labels = ":All", depts = ":All",
                        values = [], $self = $(this);
                    for (i = 0; i < data.length; i++) {
                        item = data[i];
                        if (!deptMap[item.departName]) {
                            deptMap[item.departName] = true;
                            depts += ";" + item.departName + ":" + item.departName;
                        }
                        if (!labelMap[item.channelName]) {
                            labelMap[item.channelName] = true;
                            labels += ";" + item.channelName + ":" + item.channelName;
                        }
                        if (!valueMap[item.name]) {
                            valueMap[item.name] = true;
                            values.push(item.name);
                        }
                    }

                    $self.jqGrid("setColProp", "departName", {
                        stype: "select",
                        searchoptions: {
                            value: depts,
                            sopt: ["eq"]
                        }
                    });
                    $self.jqGrid("setColProp", "channelName", {
                        stype: "select",
                        searchoptions: {
                            value: labels,
                            sopt: ["eq"]
                        }
                    });
                    $self.jqGrid("setColProp", "name", {
                        searchoptions: {
                            sopt: ["cn"],
                            dataInit: function (elem) {
                                $(elem).autocomplete({
                                    source: values,
                                    delay: 0,
                                    minLength: 0,
                                    select: function (event, ui) {
                                        var grid;
                                        $(elem).val(ui.item.value);
                                        if (typeof elem.id === "string" && elem.id.substr(0, 3) === "gs_") {
                                            grid = $self[0];
                                            if ($.isFunction(grid.triggerToolbar)) {
                                                grid.triggerToolbar();
                                            }
                                        } else {
                                            // to refresh the filter
                                            $(elem).trigger("change");
                                        }
                                    }
                                });
                            }
                        }
                    });
                    // one should use stringResult:true option additionally because
                    // datatype: "json" at the moment, but one need use local filtreing later
                    $self.jqGrid("filterToolbar", {stringResult: true});
                }
            });
        /*创建jqGrid的操作按钮容器*/
        /*可以控制界面上增删改查的按钮是否显示*/
        jQuery("#list").jqGrid('navGrid', '#pager', {
            edit: false,
            add: false,
            del: false,
            search: false,
            refresh: false
        });

        jQuery("#list").jqGrid('navButtonAdd', "#pager", {
            caption: "筛选展示隐藏", title: "展示隐藏查询条件", buttonicon: 'ui-icon-pin-s',
            onClickButton: function () {
                mygrid[0].toggleToolbar()
            }
        });

        jQuery("#list").jqGrid('navButtonAdd', "#pager", {
            caption: "清空筛选条件", title: "Clear Search", buttonicon: 'ui-icon-refresh',
            onClickButton: function () {
                mygrid[0].clearToolbar()
            }
        });

//        jQuery("#list").jqGrid('filterToolbar', {stringResult: true });

        var se = "<fmt:formatDate value="${recordate}" type="date" pattern="yyyy年MM月dd日"/> 选择项目：<select name='project' id='project' onchange='changeProject()'>";
        <c:forEach items="${projects}" var="project">
        se += "<option value='${project.id}'>${project.projectName}</option>";
        </c:forEach>
        se += "</select>";

        $("#t_list").append(se);

        $("#t_list").append("<input type='button' value='保存' style='height:30px;float: right;margin-right: 20px;width: 91px;'/>");

        $("input", "#t_list").click(function () {
            $("#dialog").dialog("open");
            $(".ui-dialog-titlebar").hide();
            if (lastsel) {
                jQuery('#list').jqGrid('saveRow', lastsel, {
                    url: 'clientArray',
                    successfunc: function (response) {
                        return true;
                    }
                });
            }

            var allRowsInGrid = $('#list').jqGrid('getGridParam', 'data');
            $.ajax({
                url: '${ctx}/localreport/saveReport/',
                type: "POST",
                data: {
                    "data": JSON.stringify(allRowsInGrid),
                    "project": $("#project").val(),
                    "reportDateStr": $("#reportDateStr").val()
                },
                success: function () {
                    setTimeout("$('#dialog').dialog('close')", 1000);
                    hasChange = false;
                    return true;
                }
            });

        });

        projectId = $("#project").val();
//        console.log("--"+projectId);
    }

    function changeProject() {
        if(hasChange){
            $("#confirmDialog").dialog({
                dialogClass: "no-close",
                autoOpen: false,
                modal: true,
                show: {
                    effect: "blind",
                    duration: 100
                },
                hide: {
                    effect: "explode",
                    duration: 100
                },
                buttons: [
                    {
                        text: "确认",
                        click: function() {
                            $( this ).dialog( "close" );
                            $("#list").jqGrid('setGridParam', {
                                url: "${ctx}/localreport/getTableData?projectId=" + $("#project").val() + "&reportDateStr=" + $("#reportDateStr").val(),
                                //if set loadonce true, must set datatype json to reload from new url
                                datatype: 'json',
                            }).trigger('reloadGrid');
                            hasChange = false;
                            projectId = $("#project").val();
                            return true;
                        }
                    },
                    {
                        text: "取消",
                        click: function() {
                            $(this).dialog( "close" );
                            $("#project").val(projectId);
//                            $("#project").find("option[value='"+projectId+"']").attr("selected",true);
                            return false;
                        }
                    }
                ]
            }).dialog("open");
            $(".ui-dialog-titlebar").hide();
        }else{
            $("#list").jqGrid('setGridParam', {
                url: "${ctx}/localreport/getTableData?projectId=" + $("#project").val() + "&reportDateStr=" + $("#reportDateStr").val(),
                //if set loadonce true, must set datatype json to reload from new url
                datatype: 'json',
            }).trigger('reloadGrid');
            projectId = $("#project").val();
        }
    }

</script>
</body>

</html>
