$(function(){
    layui.use('form', function(){
        layui.form.render();
    })        
})

//定义一个存储数据的数组，用于下面重复选择判断，删除标签
var oliIdArray = [];
var gids;
//点击输入框时候
$("body").on("click",".selectBox .imitationSelect",function(event){
// $(".selectBox .imitationSelect").click(function(event){
    // alert(1);
    $(this).parent().next().toggle();//ul弹窗展开
    // $(this).parent().next().css('display:block');//ul弹窗展开
    $(this).next().toggleClass("fa-caret-up")//点击input选择适合，小图标动态切换
    if($(this).next().hasClass("fa-caret-down")){
        $(this).next().removeClass("fa-caret-down").addClass("fa-caret-up")//点击input选择适合，小图标动态切换
    }else{
        $(this).next().addClass("fa-caret-down").removeClass("fa-caret-up")//点击input选择适合，小图标动态切换
    }
    if (event.stopPropagation) {   
        // 针对 Mozilla 和 Opera   
        event.stopPropagation();   
    }else if (window.event) {   
        // 针对 IE   
        window.event.cancelBubble = true;   
    }
});
    
//点击右边箭头icon时候
$("body").on("click",".selectBox .fa",function(event){
    $(this).parent().next().toggle();//ul弹窗展开
    if($(this).hasClass("fa-caret-down")){
        $(this).removeClass("fa-caret-down").addClass("fa-caret-up")//点击input选择适合，小图标动态切换
    }else{
        $(this).addClass("fa-caret-down").removeClass("fa-caret-up")//点击input选择适合，小图标动态切换
    }
    if (event.stopPropagation) {   
        // 针对 Mozilla 和 Opera   
        event.stopPropagation();   
    }else if (window.event) {   
        // 针对 IE   
        window.event.cancelBubble = true;   
    }  
});
    
// $(".selectUl li").click(function(event){
$("body").on("click",".selectUl li",function(event){
    event=event||window.event; 
    $(this).addClass("actived_li");//点击当前的添加   actived_li这个类；
    var oliId = $(this).attr("oliId");
    if(oliIdArray.indexOf(oliId)>-1){

    }else{
        
        oliIdArray.push(oliId);
        $.ajax({
            type: "POST",
            url: "getGroupStaff",
            data: {group_id: oliIdArray},
            dataType: 'json',
            success: function (ret) {
                var staffs = ret.data
                var inp = '<table class="tb_ry"><tr><td>ID</td><td>姓名</td><td>上限</td><td>上移</td><td>下移</td></tr>';
                for (var i = 0; i < staffs.length; i++) {
                    inp += '<tr>';
                    inp += '<td>'+staffs[i]["staff_id"]+'</td><td>'+staffs[i]["staff_name"]+'</td><td><input class="layui-input fp_staff_ids" style="height:26px;" maxlength="4" name="staffMax" sid="'+staffs[i]["staff_id"]+'" sname="'+staffs[i]["staff_name"]+'" value="" /></td><td><input type="button" value="上移" onclick="moveUp(this)" class="tb_ry_up"/></td><td><input type="button" value="下移" onclick="moveDown(this)" class="tb_ry_down"/></td>';
                };
                inp += '</table>';
                // $(".set_group").html(inp);
                // $("."+$('.renyuan_show').val()).html(inp);
                $(".set_group2").html(inp);
                form.render('select');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var ret = XMLHttpRequest.responseJSON
                layer.alert('操作失败');
            }
        });
        $(this).parent().prev().children().attr("oliId",oliIdArray);//把当前点击的oliId赋值到显示的input的oliId里面
        $("#role_select").append("<span class='person_root'><span>"+$(this).text()+"</span><i class='close' oliId='" + oliId + "' >x</i></span>");
    }
    // console.log(oliIdArray)
    oliDelete();
});
    
function oliDelete(){
    //进行绑定事件，每个删除事件得以进行
    var role_select = document.getElementById("role_select");
    var role_span= role_select.getElementsByTagName('i');
    var id;
    //console.log("span的选择个数"+role_span.length)l
    for(var i=0;i<role_span.length;i++){  
        role_span[i].onclick = function(){ 
            $(".selectUl").hide();
            var oliId = $(this).attr("oliId");
            //console.log("oliId"+oliId)
            for (var i = 0; i < oliIdArray.length; i++){
                if (oliIdArray[i] === oliId){ //表示数组里面有这个元素
                    id = i;//元素位置
                    oliIdArray.splice(i,1);
                    console.log('删除当前的序号'+oliId+';'+'剩下数组'+oliIdArray)
                }
            }
            $(".selectUl li").eq(oliId-1).removeClass("actived_li");
            $(this).parent().remove();
        }  
    }  
}
//点击任意地方隐藏下拉
$(document).click(function(event){
    // console.log(123)
    event=event||window.event; 
    $(".inputCase .fa").removeClass("fa-caret-up").addClass("fa-caret-down")//当点隐藏ul弹窗时候，把小图标恢复原状
    $(".selectUl").hide();//当点击空白处，隐藏ul弹窗
});
// })
function appendSelect(type,dataStr,form,clean){
    var data = 'type='+type;
    if(dataStr){
        data = data+'&'+dataStr;
    }
    if(type == 'default'){
        $(".customer_value_box").each(function(){
            $(this).remove();
        });
        $('#order_sort').val(9999);
    }
    
    $.ajax({
        type: "POST",
        url: "getCustomerConditionData",
        data: data,
        dataType: 'json',
        success: function (ret) {
            if(ret.error > 0){
                return false;
            }
            var html = '';
            for(var i in ret){
                html += '<option value="'+ret[i].value+'" title="'+ret[i].title+'">'+ret[i].text+'</option>';
            }
            if(clean == 1){
                $(".customer_value_box").each(function(){
                    $(this).remove();
                });
            }
            html = '<div class="layui-inline w-90 customer_value_box"><select class="w-90" lay-search name="customer_value" lay-filter="customer_value">'+html+'</select></div>';
            $("#condition-wrap").append(html);
            form.render('select');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var ret = XMLHttpRequest.responseJSON
            layer.alert('操作失败,请重试');
        }
    })
}

layui.use('form', function() {
    var form = layui.form;
    form.on('radio(test-radio)', function (data) {
        //点击选择客户类型时，触发，获取可供选择的类型值
        $("#morechannel").empty();
        if(data.value == 'customer_region' || data.value == 'add_organize'){
            $('#img').attr('src','/img/mr_menu05.png');
        }else{
            $('#img').attr('src','');
        }
        appendSelect(data.value,'',form,1);
    });
    $('#img').click(function(){
        var selLen=$("#condition-wrap .customer_value_box");
        var selNum= 0,selStr='',selName;
        for(var i=selLen.length-1;i>=0;i--) {
            if(selNum==0){
                selNum = selLen.eq(i).find('select option:selected').val();
                selName = selLen.eq(i).find('select option:selected').html();
                selStr = selLen.eq(i).find('select option:selected').attr("title");
            }
        }
        if(selStr == 'provincelist'){
            selStr = 'province';
        }else if(selStr == 'citylist'){
            selStr = 'city';
        }else if(selStr == 'staffshoplist'){
            selStr = 'shop';
        }else if(selStr == 'staffdepartmentlist'){
            selStr = 'department';
        }else if(selStr == 'stafflist'){
            selStr = 'staff';
        }else{
            selStr = 'region';
        }
        //console.log(selNum,selName,selStr);
        var moreregion = '<div class="filter-wrap"><span class="filter-text type-val" value="'+selStr+'-'+selNum+'-'+selName+'">'+selName+'</span><span class="cus-close">×</span></div>';
        $("#morechannel").append(moreregion);
    })
    form.on('select(customer_value)', function (data) {
        var type = data.elem[data.elem.selectedIndex].title;
        $(data.othis).parent().nextAll().remove('div');
        if(data.value == 0 /* && data.elem[data.elem.selectedIndex].title != 'staffdepartmentlist'*/){
            //选部门时，就算部门为0，也要取一下数据，主要是取店下员工数据
            return false;
        }
        if(type == 'channelshoplist'){
            appendSelect('channelshoplist','shop_code=' + data.value,form);
        }else if(type == 'staffshoplist'){
            appendSelect('staffshoplist','shop_code=' + data.value,form);
        }else if (type == 'staffdepartmentlist'){
            appendSelect('staffdepartmentlist','department_id=' + data.value,form);
        }else if (type == 'region'){
            appendSelect('region','region=' + data.value,form);
        }else if (type == 'provincelist'){
            appendSelect('province','province_id=' + data.value,form);
        }else{
            var morechannel;
            if (type == 'channellist') {
                var  channelname = data.elem[data.elem.selectedIndex].innerHTML;
                var  channelid = data.elem[data.elem.selectedIndex].value;
                morechannel = '<div class="filter-wrap"><span class="filter-text type-val" value="'+channelid+'">'+channelname+'</span><span class="cus-close">×</span></div>';
                $("#morechannel").append(morechannel);
            }
            appendSelect(type,'',form);
        }
    })
    // 删除选中渠道
    $('#morechannel').on("click",".cus-close",function () {
        $(this).parent().remove();
    })
    form.on('radio(allocationtype)', function (data) {
        $('#content').css('display','block');
    })
    form.on('radio(allocationtype_none)', function (data) {
        $('#content').css('display','none');
    })
    form.on('radio(def2)', function (data) {
        $('#def').css('display','block');
    })
    form.on('radio(def1)', function (data) {
        $('#def').css('display','none');
    })
    form.on('radio(qd_radio)', function (data) {
        $("#d_dpg").html('');
        $(".set_group").html('');
        var shop_code = $('#gs_shop_code').val();
        $.ajax({
            type: "POST",
            url: "get"+data.value,
            data: {channelclass: data.value,shop_code:shop_code},
            dataType: 'json',
            success: function (ret) {
                // console.log(ret)
                var a = JSON.parse(ret);
                if(data.value == 'department_name'){
                    var crmItem = '<select class="w-90" lay-search id="d_dpg"><option value="">请选择部门</option>';
                    for (var i = 0; i < a.length; i++) {
                        crmItem += '<option value="' + a[i]['id'] + '">' + a[i]['department_name'] + '</option>';
                    }
                    crmItem += '</select>';
                    $("#type").html(crmItem);
                }else if(data.value == 'position_name'){
                    var crmItem = '<select class="w-90" lay-search id="d_dpg">';
                    for (var i = 0; i < a.length; i++) {
                        crmItem += '<option value="' + a[i]['id'] + '">' + a[i]['position_name'] + '</option>';
                    }
                    crmItem += '</select>';
                    $("#type").html(crmItem);
                }else if(data.value == 'group_name') {
                    // var crmItem = '<select class="w-90" lay-search id="d_dpg">';
                    // for (var i = 0; i < a.length; i++) {
                    //     crmItem += '<option value="' + a[i]['id'] + '">' + a[i]['group_name'] + '</option>';
                    //     $("input[name=group_id]").val(a[i]['id']);
                    // }
                    // crmItem += '</select>';
                    var crmItem = '<div class="selectBox"><div class="inputCase"><div id="role_select" class="select-menu-input imitationSelect"></div><i class="fa fa-caret-down"></i></div><ul class="selectUl">';
                    for (var i = 0; i < a.length; i++) {
                        crmItem += '<li oliName="'+a[i]['group_name']+'" oliId="'+ a[i]['id']+'">'+a[i]['group_name']+'</li>';
                    };
                    crmItem += '</ul></div>';
                    $("#type").html(crmItem);
                }else if(data.value == 'staff_name') {
                    // var inp = '<div class="layui-inline"><label class="layui-form-label" style="width:115px;padding:5px 0;">双击添加删除人员：</label><div class="layui-input-block" style=""><input type="text" id="search" class="layui-input w-120" style="float: left;margin-right: 5px" value=""><button class="layui-btn" style="float: left" type="button" id="query">查询</button></div><div class="layui-input-block" style="margin-top:10px;overflow: hidden"><div class="store-wrap"><ul class="store-list all-list-contain">';
                    // for (var i = 0; i < a.length; i++) {
                    //     inp += '<li id="'+a[i]["id"]+'">'+a[i]["staffname"]+'</li>';
                    // }
                    // inp += '</ul> <div class="store-tit" style="font-size: 14px">可添加</div> </div> <span class="layui-icon set-qh">&#xe65b;</span><div class="store-wrap"><ul class="store-list recive-list-contain"></ul> <div class="store-tit" style="font-size: 14px">已添加</div> </div> </div> </div> ';
                    var inp = '<table class="tb_ry"><tr><td>ID</td><td>姓名</td><td>上限</td><td>上移</td><td>下移</td></tr>';
                    for (var i = 0; i < a.length; i++) {
                        inp += '<tr>';
                        inp += '<td>'+a[i]["id"]+'</td><td>'+a[i]["staffname"]+'</td><td><input class="layui-input fp_staff_ids" style="height:26px;" maxlength="4" name="staffMax" sid="'+a[i]["id"]+'" sname="'+a[i]["staffname"]+'" value="" /></td></td><td><input type="button" value="上移" onclick="moveUp(this)" class="tb_ry_up"/></td><td><input  type="button" value="下移" onclick="moveDown(this)" class="tb_ry_down"/></td>';
                    };
                    inp += '</table>';
                    $("#type").html('');
                    $(".set_group2").html(inp);
                    // $("."+$('.renyuan_show').val()).html(inp);
                    // $(".set_group").html(inp);
                    oliIdArray = [];
                    $(".person_root").html('');
                }
                form.render('select');
                // }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var ret = XMLHttpRequest.responseJSON
                layer.alert('操作失败');
            }
        })
    });
})
// 上移 
function moveUp(obj) { 
    var current = $(obj).parent().parent(); //获取当前<tr>
    var prev = current.prev();  //获取当前<tr>前一个元素
    if (current.index() > 1) { 
        current.insertBefore(prev); //插入到当前<tr>前一个元素前
    }
}
// 下移 
function moveDown(obj) { 
    var current = $(obj).parent().parent(); //获取当前<tr>
    var next = current.next(); //获取当前<tr>后面一个元素
    if (next) { 
        current.insertAfter(next);  //插入到当前<tr>后面一个元素后面
    } 
} 
var listStr=function(name){
    var str="";
    var staffname="";
    for(var i=0;i<$(name).length;i++){
        var sid=$(name).eq(i).attr("id");
        var sname=$(name).eq(i).html();
        if(i==$(name).length-1){
            str+=sid;
            staffname+=sname;
        }else{
            str+=sid+',';
            staffname+=sname+',';
        }
    }
    return str+'-'+staffname;
};
$('#add-box').on('click','#query',function(){
    var search = $('#search').val();
    $.ajax({
        type: "POST",
        url: "searchStaff",
        data: {key_words:search},
        dataType: 'json',
        success: function (ret) {
            if(ret.code == 200){
                var data = ret.data;
                var inp = '';
                for (var i = 0; i < data.length; i++) {
                    inp += '<li id="'+data[i]["id"]+'">'+data[i]["staffname"]+'</li>';
                }
                $(".all-list-contain").html(inp);
            }
        }
    })
})

//双击添加和移除事件
$("#add-box").on("dblclick",".all-list-contain li",function(){
    var removeDom=$(this).remove();
    $(".recive-list-contain").append(removeDom);
});
$("#add-box").on("dblclick",".recive-list-contain li",function(){
    var removeDom=$(this).remove();
    $(".all-list-contain").append(removeDom);
});
$('#btn').click(function(){
    table.reload('idTest', {
        url: 'FPListJSON'
        ,where: {department_name:$('#department_name').val()} //设定异步数据接口的额外参数
        //,height: 300
    });
})
