/*
 *title:server-user-add
 *@auther  liaoxin
 *date:2018/11/29
*/
layui.extend({
    common    :   'js/common',
    region    :   'layui/lay/mymodules/region',
    formSelects:  'lib/formSelects-v4',
    xmSelect    :   'layui/dist/xm-select'
}).use([ 'jquery','common','form','region','formSelects','xmSelect'], function () {
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //引入表单
    var form = layui.form;
    // 多选下拉框
    var formSelects = layui.formSelects;
    //  引入下拉菜单
    var xmSelect = layui.xmSelect;

    //  页面元素
    var $node = {
        //  省市区表单
        provinceInput   :   $('input[name="regionProvince"]'),
        cityInput       :   $('input[name="regionCity"]'),
        areaInput       :   $('input[name="regionArea"]'),
        regionInput     :   $('#region'),
    };

    $.ajax({
        type: 'GET',
        url: '/permissions/dict/getByCode/sex',
        success: function (result) {
            sexDic.update({data:result.list}).setValue([$('#sexValue').val()])
        },
    });
    var sexDic = xmSelect.render({
        el: '#sex_dic',
        name: 'sex',
        layVerify: 'required',
        radio: true,
        clickClose: true,
        prop: {
            name: 'dictValue',
            value: 'dictKey',
        },
        on: function (data) {},
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });
    $.ajax({
        type: 'GET',
        url: '/permissions/dict/getByCode/serverUserType',
        success: function (result) {
            serverUserTypeDic.update({data:result.list}).setValue([$('#typeValue').val()])
        },
    });
    var serverUserTypeDic = xmSelect.render({
        el: '#type',
        name: 'type',
        layVerify: 'required',
        radio: true,
        clickClose: true,
        prop: {
            name: 'dictValue',
            value: 'dictKey',
        },
        on: function (data) {},
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });
    //  初始化省市区
    layui.region.init({
        //  元素节点
        elem        :  '#region_body',
        //  触发此元素时显示
        trigger     :   '#region',
        //  选中省的回调
        provinceCallbackFn  :   function(data){
            var address = data.province.text;
            $('#region').val(address);
            $('input[name="regionProvince"]').val(data.province.id);
        },
        //  选中市的回调
        cityCallbackFn  :   function(data){
            var address = data.province.text + '-' + data.city.text;
            $('#region').val(address);
            $('input[name="regionCity"]').val(data.city.id);
        },
        //  选中区域的回调
        areaCallbackFn  :   function(data){
            var address = data.province.text + '-' + data.city.text + '-' +data.county.text;
            $('#region').val(address);
            $('input[name="regionArea"]').val(data.county.id);
        },
        //  关闭时的回调
        hideCallbackFn  :   function(data){
        },
        //清空回调
        clearFn : function(){
            $node.regionInput.val('');
            $node.provinceInput.val('');
            $node.cityInput.val('');
            $node.areaInput.val('');
        }
    });
    //监听提交
    form.on('submit(submitButton)', function(data){
        common.timer($('button[lay-filter="submitButton"]'));
        common.sendAsyncRequest("/estate/serverUser/addOrEditServerUser",'POST',data.field,callbackFn);
    });
    //回调函数
    function callbackFn(result) {
        if(result.code==='200'){
            layer.msg("添加成功",{
                time: 500,
                shade : [0.1 , '#000' , true]
            },function () {
                //获取当前弹窗出层的名字
                var index = parent.layer.getFrameIndex(window.name);
                //关闭弹窗层
                parent.layer.close(index);
                // 父页面刷新
                parent.location.reload();
            });
        }else {//添加失败
            layer.msg("操作失败");
        }
    }
    //取消按钮
    $('#cancel_btn').on("click",function(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

/*    //  绑定所属机构绑定事件
    form.on('select(residential_event)', function(data){
        var selectResidentialId = data.value;
        $('#residential_name').val($('#residential_id option[value="'+ selectResidentialId +'"]').text());
        initUnitFn(selectResidentialId);
    });*/

    /**
     * 初始化所属单元下拉多选框
     */
    var initUnitFn  = function (selectResidentialId) {
        formSelects.data('select1', 'server', {
            url:'/estate/unit/getListByXqId/'+selectResidentialId,
            beforeSuccess: function(id, url, searchVal, result){
                result = result.list;
                var arr = [];
                $.each(result, function(index, item) {
                    var data={
                        name : item.name,
                        value : item.id
                    }
                    arr.push(data);
                });
                return arr;
            },
            success: function(id, url, searchVal, result){
                var unitIds = $("#unitIds").val();
                if(unitIds){
                    var arr = unitIds.split(',');
                    formSelects.value('select1', arr);
                }
            }
        });
    }
    
    /**
     * 初始化所属小区下拉框（列表）
     */
    var residentialSelect = xmSelect.render({
            el: '#residential_id',
            name: 'residentialId',
            radio: true,
            prop: {
                name: 'name',
                value: 'id',
            },
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                $.ajax({
                    type: 'GET',
                    url: '/estate/residential/getListByLikeName',
                    data: {
                        name : val,
                        isSelect : true
                    },
                    success: function (result) {
                        cb(result.list);
                    },
                    error: function () {
                        cb([]);
                    }
                });
            },
            //监听选择
            on: function (data) {
                var change = data.change;
                if (change.length > 0) {
                    $('#residential_name').val(change[0].name);
                    initUnitFn(change[0].id)
                }
                if (!data.isAdd) {
                    $('#residential_name').val('');
                    initUnitFn('')
                }
            },
            //显示方式
            model: {
                label: {
                    type: 'text',
                    text: {
                        //左边拼接的字符
                        left: '',
                        //右边拼接的字符
                        right: '',
                        //中间的分隔符
                        separator: ', ',
                    },
                }
            },
        });
    //  初始化
    (function () {
        //  加载所属小区
        // initResidentialFn();
    })();
});