/**
 * 校区服务JS
 */

$(function() {
    //初始化日历插件
    $('#datetimepicker').datetimepicker({
        format: 'yyyy-mm-dd', //格式
        language: 'zh-CN', //中文
        weekStart: 1, //每周开始日期
        todayBtn: 1, //'今天'按钮
        autoclose: true, //自动关闭
        todayHighlight: 1, //今天高亮
        bootcssVer: 3,
        startView: 2,
        minView: 2,
        startDate: new Date() //起始时间
    });
    var ERROK = 200;
    var contextPath = $("#contextPath").val()
    var imageServer = $("#imageServer").val()
    var visitPrefix = $("#visitPrefix").val()
    var serviceCategoryJson = $("#serviceCategoryJson").val()
    var serviceCategory = JSON.parse(serviceCategoryJson)
    var serviceStatusGropTypeJson = $("#serviceStatusGropTypeJson").val()
    var serviceStatusGropType = JSON.parse(serviceStatusGropTypeJson)

    var table;
    var api = {
        init: function() {
            this.render();
            this.bindEvent();
        },
        render: function() {
            this.rendertable();
        },
        bindEvent: function() {
            var _this = this;
            //查询
            $('body').on('click', '#btn-search', function() {
                console.log(9999)
                _this.againRenderTable();

            });
            // 模糊搜索
            _this.search_fuzzy()
        },
        // 模糊搜索事件
        search_fuzzy: function() {
            var default_option = {
                org_attrName: 'org__id',
                com_attrName: 'com__id',
                dep_attrName: 'dep__id',
                org_spanName: 'org__span',
                com_spanName: 'com__span',
                dep_spanName: 'dep__span',
                org_path: '/admin/templ/getOrgListByName',
                com_path: '/admin/templ/getVirList',
                dep_path: '/admin/templ/getDept',
                contextPath: $("#contextPath").val()
            }
            var option_1 = $.extend(true, {}, default_option, {
                org_target: '.default-select#organizationId',
            });

            function eve(option_, otherOption) {
                var obj = $.extend(true, {}, option_, otherOption);
                var type = obj.type
                var _path, _target, _attrName, _spanName
                if (type == 1) {
                    _path = obj.org_path
                    _target = obj.org_target
                    _attrName = obj.org_attrName
                    _spanName = obj.org_spanName
                } else if (type == 2) {
                    _path = obj.com_path
                    _target = obj.com_target
                    _attrName = obj.com_attrName
                    _spanName = obj.com_spanName
                } else if (type == 3) {
                    _path = obj.dep_path
                    _target = obj.dep_target
                    _attrName = obj.dep_attrName
                    _spanName = obj.dep_spanName
                }
                $('body').on("input", _target, function(event) {
                    var _this = $(this)
                    var obj_input = $.extend(true, {}, obj, {
                        "_this": _this
                    });
                    cjqt.search_fuzzy.event_input(_this, _attrName, _spanName, contextPath, _path, obj_input)
                });
                $('body').on("focus", _target, function(event) {
                    var _this = $(this)
                    var obj_focus = $.extend(true, {}, obj, {
                        "_this": _this
                    });
                    cjqt.search_fuzzy.event_focus(_this, _attrName, _spanName, contextPath, _path, obj_focus)
                });
                $('body').on('blur', _target, function(event) {
                    var _this = $(this)
                    var obj_blur = $.extend(true, {}, obj, {
                        "_this": _this
                    });
                    cjqt.search_fuzzy.event_blur(_this, _attrName, obj_blur)
                });
                $('body').on('click', _target + '~.select_wrap>.' + _spanName, function(event) {
                    event.preventDefault();
                    event.stopPropagation();
                    /* Act on the event */
                    var _this = $(this)
                    var obj_click = $.extend(true, {}, obj, {
                        "_this": _this
                    });
                    cjqt.search_fuzzy.event_click(_this, _attrName, _target, obj_click)
                });

            }
            // 搜索联动
            eve(option_1, {type: 1})
        },
        rendertable: function() {
            var _this = this;
            layui.use(['table', 'laydate', 'form'], function() {
                table = layui.table;
                var form = layui.form,
                    layer = layui.layer,
                    laydate = layui.laydate;
                //日期
                laydate.render({
                    elem: '#date1'
                });
                //方法级渲染
                table.render({
                    elem: '#LAY_table_user',
                    url: $("#contextPath").val() + "/service/allocation/getServiceProject",
                    method: "post",
                    skin: 'nob' //行边框风格
                        ,
                    even: true //开启隔行背景
                        ,
                    size: 'lg' //小尺寸的表格
                        ,
                    cols: [
                        [{
                            field: 'index',
                            title: '序号',
                            width: '80',
                            templet: '#indexTpl'
                        }, {
                            field: 'serviceName',
                            title: '服务名称',
                            minWidth: 200
                        }, {
                            field: 'deviceNames',
                            title: '自定义服务分类',
                            minWidth: 200,
                            templet: function(data) {
                                var res = ''
                                $.each(serviceCategory,function(index, el) {
                                    if(data.serviceCategory == el.itemcode){
                                        res =  el.itemname
                                    }
                                });
                                return res
                            }
                        }, {
                            field: 'organizationName',
                            title: '服务图标',
                            minWidth: 200,
                            templet: function(data) {
                                if(data.customServiceIcon){
                                    return '<img style="height:100%" src="'+ visitPrefix+data.customServiceIcon +'" alt="" />'
                                }else{
                                    return '<img style="height:100%" src="'+ visitPrefix+data.serviceIcon +'" alt="" />'
                                }
                            }
                        }, {
                            field: 'creator',
                            title: '服务状态',
                            minWidth: 200,
                            templet: function(data) {
                                res = ''
                                $.each(serviceStatusGropType,function(index, el) {
                                    if(data.serviceallcationStatus == el.itemcode){
                                        res =  el.itemname
                                    }
                                });
                                return res
                            }
                        }, {
                            field: 'indate',
                            title: '有效期',
                            minWidth: 200,
                            // templet: function(data) {
                            //     var time = data.createTime
                            //     var timeDate = new Date(time)
                            //     var year = timeDate.getFullYear()
                            //     var month = timeDate.getMonth() + 1
                            //     var day = timeDate.getDate()
                            //     var hours = timeDate.getHours()
                            //     var min = timeDate.getMinutes()
                            //     var sec = timeDate.getSeconds()
                            //     return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + " " + (hours < 10 ? '0' + hours : hours) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec)
                            // }
                        }, {
                            field: 'orderNo',
                            title: '服务排序号',
                            minWidth: 200
                        },  {
                            title: '操作',
                            fixed: 'right',
                            width: 260,
                            align: 'center',
                            templet: function(data) {
                                var str = '';
                                str += '<perm:hasPermission permCode="pc:setting:project:edit">'
                                str += '<a href="javascript:void(0);" class="btn btn-back btn-bj" title="编辑" data-id="'+ data.id + '" data-serviceName="' + data.serviceName+ '" data-serviceId="' + data.serviceId+'">'
                                str += '<span>编辑</span>'
                                str += '</a>'
                                str += '</perm:hasPermission>'
                                if(data.serviceStatus == 1){
                                    str += '<a href="javascript:void(0);" class="btn btn-info btn-xq" title="详情" data-serviceId="'+ data.serviceId + '">'
                                    str += '<span>详情</span>'
                                    str += '</a>'
                                    str += '<perm:hasPermission permCode="pc:setting:project:delete">'
                                    str += '<a href="javascript:void(0);" class="btn btn-danger btn-sc" title="删除"  style="padding-left: 10px;"  data-serviceName="' + data.serviceName +'" data-serviceId="' + data.serviceId+ '">'
                                    str += '<span>删除</span>'
                                    str += '</a>'
                                    str += '</perm:hasPermission>'
                                    str += '<perm:hasPermission permCode="pc:setting:project:edit">'
                                    str += '<a href="javascript:void(0);" class="btn btn-back btn-xg" title="修改"  style="padding-left: 10px;" data-serviceId="' + data.serviceId+ '">'
                                    str += '<span>修改</span>'
                                    str += '</a>'
                                    str += '</perm:hasPermission>'
                                }
                                // str += '<button class="t-btn t-red-btn t-detail-btn" data-id=' + data.ID + '  >修改</button>';
                                // str += '<button class="t-btn t-red-btn t-edit-btn" data-id=' + data.ID + '  >修改</button>';
                                // str += '<button class="t-btn t-red-btn t-delete-btn" data-id=' + data.ID + '>删除</button>';
                                return str;
                            }
                        }]
                    ],
                    id: 'testReload',
                    page: true,
                    response: {
                        statusName: 'code' //数据状态的字段名称，默认：code
                            ,
                        statusCode: 200 //成功的状态码，默认：0
                            ,
                        countName: "count" //数据总数的字段名称，默认：count
                            ,
                        dataName: "data" //数据列表的字段名称，默认：data
                    },
                    request: {
                        pageName: 'pageNo' //页码的参数名称，默认：page
                            ,
                        limitName: 'pageSize' //每页数据量的参数名，默认：limit
                    },
                    done: function(res, curr, count) {
                        //  编辑
                        $(".btn-bj").on("click", function() {
                             // onclick="showSaveUpdateServiceProject('${obj.id}','${obj.serviceName }','${obj.serviceId }')"  
                            var id = $(this).data("id");
                            var serviceName = $(this).data("servicename");
                            var serviceId = $(this).data("serviceid");
                            console.log(serviceId)
                            showSaveUpdateServiceProject(id,serviceName,serviceId)
                        });
                        //  详情
                        $(".btn-xq").on("click", function() {
                            // onclick="showServiceTypeInfoDetails('${obj.serviceId}')"
                            var serviceId = $(this).data("serviceid");
                            showServiceTypeInfoDetails(serviceId)
                        });
                        //  删除
                        $(".btn-sc").on("click", function() {
                            // onclick="delServiceTypeInfo('${obj.serviceId}','${obj.serviceName}')"
                            var serviceId = $(this).data("serviceid");
                            var serviceName = $(this).data("servicename");
                            delServiceTypeInfo(serviceId,serviceName)
                        });
                        //  修改
                        $(".btn-xg").on("click", function() {
                            // onclick="showEidtServiceTypeInfo('${obj.serviceId}')"
                            var serviceId = $(this).data("serviceid");
                            showEidtServiceTypeInfo(serviceId)
                        });
                    }
                });

            });
        },
        /*重新渲染table*/
        againRenderTable: function(option) {
            var obj = $.extend(true, {}, option);
            var type = obj.type || ''
            var $orgId = $("#conditionform  .single-orgid");
            var orgId = $("#conditionform  #organizationId").attr('org__id')
            var serviceType = $('#serviceType').val()
            if (type == 1) {
                table.reload('testReload', {
                    where: {
                        organizationId: $orgId.length ? orgId : '',
                        paramValue: '',
                        serviceType:''
                    },
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            } else {
                table.reload('testReload', {
                    where: {
                        organizationId: orgId,
                        paramValue: $(".paramValue").val() || '',
                        serviceType:serviceType
                    },
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }
        },
        /**
         * 请求详情
         * @param id
         * @param callback
         */
        ajaxDetail: function(id, callback) {
            var _this = this;
            $.ajax({
                type: "post",
                url: contextPath + "/lingling/getDeviceGroupInfo",
                data: {
                    id: id
                },
                success: function(data) {
                    if (data.code == ERROK) {
                        callback(data.data)
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function(error) {
                    layer.msg('error')
                }
            });
        },
    };
    api.init();

});
/**
 * 查询
 */
function searchServiceProjectAllocation() {
    $("#conditionform").submit();
}

/**
 * 有效期计算
 * @param closeTime
 * @returns {boolean}
 */
function selectCloseTime(closeTime) {
    var formatDate;

    if (closeTime == '' || closeTime == null) { //closeTime为空 说明是永久
        formatDate = new Date(); //时间格式化
    } else {
        formatDate = new Date(closeTime); //时间格式化
    }

    var type = $("#serviceIndate").val(); //选择的类型  7天{0},15天{1},1个月{2},3个月{3},半年{4},一年{5},永久{6},自定义截止时间{7}

    //只有在自定义截止日期时 日历插件才生效
    if (type == '7') {

        //让插件变亮
        $('#datetimepicker').attr("style", "");
        //设置初始值
        $('#datetimepicker').datetimepicker('setDate', formatDate);
    } else {
        //让插件变灰且不可选
        $('#datetimepicker').attr("style", "border: 0px;outline:none;cursor: pointer;color: gray;font-size: 14px;font-weight:normal;");

        if (type == '0') { //7天
            var newDate = $('#datetimepicker').datetimepicker('moveDate', formatDate, 7); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == 1) { //15天
            var newDate = $('#datetimepicker').datetimepicker('moveDate', formatDate, 15); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == '2') { //一个月
            var newDate = $('#datetimepicker').datetimepicker('moveMonth', formatDate, 1); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == '3') { //三个月
            var newDate = $('#datetimepicker').datetimepicker('moveMonth', formatDate, 3); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == '4') { //半年
            var newDate = $('#datetimepicker').datetimepicker('moveMonth', formatDate, 6); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == '5') { //一年
            var newDate = $('#datetimepicker').datetimepicker('moveYear', formatDate, 1); //移动日期
            $('#datetimepicker').datetimepicker('setDate', newDate);
        } else if (type == '6') { //永久
            $('#datetimepicker').val('');
        } else if (type == '') {
            $('#datetimepicker').datetimepicker('setDate', formatDate);
        }
    }

}


/**
 * 上线下线的动态model
 */
function showSaveUpdateServiceProject(id, serviceName, serviceId) {
    $("#save").show();
    $("#serviceNames").html(serviceName);
    $("#serviceId").val(serviceId);
    if (id != null && id != "") {
        var url = $("#contextPath").val() + "/service/allocation/findServiceProjectAllocation";
        $.ajax({
            url: url,
            data: {
                id: id
            },
            type: "POST",
            success: function(data) {
                if (data != null) {
                	
                    $("#orderNo").val(data.orderNo);
                    $(".form-group #organizationId").val(data.orgName);
                	$(".form-group #organizationId").attr('org__id',data.projectId)
                    if (data.status == "") {
                        $("#status").val(0);
                    } else {
                        $("#status").val(data.status);
                    }

                    $("#serviceIcon").val(data.serviceIcon);
                    $(".customShowimg").html("<img src='" + $("#visitPrefix").val() + data.serviceIcon + "' alt='' />");
                    var roleGroup = data.roleGroup;
                    var roleGroupArray = roleGroup.split(",");
                    var roleGroupArrayCheck = document.getElementsByName('roleGroup');
                    $.each(roleGroupArrayCheck, function(index, item) {
                        $.each(roleGroupArray, function(no, obj) {
                            if (item.value == obj) {
                                $("#check" + item.value + "").attr("checked", true);
                            }
                        })
                    })

                    if (data.permission == 1) {
                        $("#permission").attr("checked", true);
                    } else {
                        $("#permission").attr("checked", false);
                    }

                    var closeTime = data.indate;
                    if (closeTime == '' || closeTime == null) {
                        $('#datetimepicker').val('');
                    } else {
                        $('#datetimepicker').val(closeTime);
                    }

                    //给选择有效期select绑定事件
                    $("#serviceIndate").change(function() {
                        selectCloseTime(closeTime);
                    });
                }

            },
            error: function() {
                layer.msg("提交失败，请检测网络", {
                    icon: 5,
                    end: function() {

                    }
                });
            }
        });
    }
    $("#projectId").val(id);
    $("#myModalLabel").html("校区服务内容信息配置");
    $('#saveUpdateServiceProjectModal').modal('show');
}

/**
 * 商圈的动态model
 */
function showSaveUpdateServiceConfig() {
    $("#save1").show();
    var orgId = $("#organizationId").attr('org__id');
    if (id != null && id != "") {
        var url = $("#contextPath").val() + "/service/allocation/getDiscoverConfig";
        $.ajax({
            url: url,
            data: {
                orgId: orgId
            },
            type: "POST",
            success: function(data) {
                if (data.code == '200') {
                    if (data.data != null) {
                        $("#discoverIsEnabled").val(data.data.discoverIsEnabled);
                        $("#discoverCategory").val(data.data.discoverCategory);
                        $("#discoverConfig").val(data.data.id);
                    }
                }

            },
            error: function() {
                layer.msg("提交失败，请检测网络", {
                    icon: 5,
                    end: function() {

                    }
                });
            }
        });
    }
    // $("#projectId").val(id);
    $("#myModalLabel").html("商圈发现配置");
    $('#saveUpdateServiceConfigModal').modal('show');
}

/**
 * 保存
 */
function saveUpdateServiceProject() {
    var roleGroupArray = document.getElementsByName('roleGroup');
    var roleGroup = '';
    for (var i = 0; i < roleGroupArray.length; i++) {
        if (roleGroupArray[i].checked) roleGroup += roleGroupArray[i].value + ','; //如果选中，将value添加到变量s中
    }

    var orderNo = $("#orderNo").val();
    if ($.trim(orderNo) == "") {
        layer.msg('请输入序号');
        return;
    }

    var status = $("#status").val();
    if ($.trim(status) == "") {
        layer.msg('请选择服务状态！');
        return;
    }

    var serviceIndate = $("#datetimepicker").val(); //有效期
    if (status != '1') { //如果是灰度或者下线操作,有效期置为空
        serviceIndate = '';
    }

    /*if ($.trim(roleGroup) == "") {
        layer.msg('请选择权限分组！');
        return;
    }*/

    var organizationId = $(".form-group #organizationId").attr('org__id');
    var serviceIcon = $("#serviceIcon").val();
    var url = $("#contextPath").val() + "/service/allocation/saveUpdateServiceProject";

    var permission = 0;
    if ($("#permission").get(0).checked) {
        permission = 1;
    }

    $.ajax({
        url: url,
        data: {
            id: $("#projectId").val(),
            serviceId: $("#serviceId").val(),
            orderNo: orderNo,
            roleGroup: roleGroup,
            organizationId: organizationId,
            status: status,
            serviceIndate: serviceIndate,
            serviceIcon: serviceIcon,
            permission: permission
        },
        type: "POST",
        success: function(data) {
            url = "/super_service/service/allocation/serviceProjectAllocationPage?funcid=" + $("#funcid").val();
            if (data.flag) {
                layer.alert(data.desc, {
                    icon: 6,
                    end: function() {
                        $("#conditionform").submit();
                    }
                });
            } else {
                layer.msg(data.desc, {
                    icon: 5,
                    end: function() {
                        $("#conditionform").submit();
                    }
                });
            }

        },
        error: function() {
            layer.msg("提交失败，请检测网络", {
                icon: 5,
                end: function() {

                }
            });
        }
    });
}

/**
 * 保存校区商圈配置
 */
function saveUpdateServiceConfig() {
    var discoverIsEnabled = $("#discoverIsEnabled").val();
    if ($.trim(discoverIsEnabled) == "") {
        layer.msg('请选择是否开启');
        return;
    }
    var discoverCategory = $("#discoverCategory").val();
    if ($.trim(discoverCategory) == "") {
        layer.msg('请选择页面名称');
        return;
    }
    var url = $("#contextPath").val() + "/service/allocation/saveDiscoverConfig";
    $.ajax({
        url: url,
        data: {
            id: $("#discoverConfig").val(),
            orgId: $("#organizationId").attr('org__id'),
            isEnabled: discoverIsEnabled,
            discoverCategory: discoverCategory
        },
        type: "POST",
        success: function(data) {
            url = "/super_service/service/allocation/serviceProjectAllocationPage?funcid=" + $("#funcid").val();
            if (data.code == '200') {
                layer.alert(data.msg, {
                    icon: 6,
                    end: function() {
                        $("#conditionform").submit();
                    }
                });
            } else {
                layer.msg(data.msg, {
                    icon: 5,
                    end: function() {
                        $("#conditionform").submit();
                    }
                });
            }

        },
        error: function() {
            layer.msg("提交失败，请检测网络", {
                icon: 5,
                end: function() {

                }
            });
        }
    });
}

/**
 * 翻页
 * @param pageNo 页码
 */
function goPage(pageNo) {
    if (pageNo == "gopage") {
        $("#pageNo").val($("#gopage").val());
    } else {
        $("#pageNo").val(pageNo);
    }
    $("#conditionform").submit();
}

/**
 * 跳转批量上线下线服务
 */
function manageServiceInfo() {
    var organizationId = $("#organizationId").attr('org__id');
    if (organizationId == "" || organizationId == null) {
        alert("请选择校区");
    } else {
        var contextPath = $("#contextPath").val();
        var funcid = $("#funcid").val();
        window.location.href = contextPath + "/service/type/serviceProjectTypeManage?organizationId=" + organizationId + "&funcid=" + funcid;
    }

}