layui.extend({
    common    :   'js/common',
    region    :   'layui/lay/mymodules/region',
    xmSelect    :   'layui/dist/xm-select',
    index    : 'lib/index'
}).use(['jquery','layer','common','region','form','xmSelect'],function(){
    var $ = layui.jquery;
    var form = layui.form;
    var common = layui.common;

    //  页面元素
    var $node = {
        //  省市区表单
        provinceInput   :   $('input[name="regionProvince"]'),
        orgPid          :    $("#orgPid"),

        cityInput       :   $('input[name="regionCity"]'),

        areaInput       :   $('input[name="regionArea"]'),
        regionStreet    :   $("#regionStreet"),

        regionInput     :   $('#region'),
        provinceNameInput   :   $('input[name="provinceName"]'),

        cityNameInput       :   $('input[name="cityName"]'),

        areaNameInput       :   $('input[name="areaName"]'),
        //  上级机构表单
        pidInput        :   $('#pid'),
        streetNameInput :  $('input[name="streetName"]'),
        //  取消按钮
        resetBtn        :   $('button[type="reset"]')
    };

    var map = new AMap.Map('container1', {
        resizeEnable: true, //是否监控地图容器尺寸变化
        center: [106.24749,38.508705],
        zoom:16,
        viewMode:'3D',
        showBuildingBlock:true,
        pitch:50,
        pitchEnable:true,
        showIndoorMap:true,
    });
    //输入提示
    var autoOptions = {
        input: "tipinput"
    };
    var auto = new AMap.Autocomplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
        map: map
    });  //构造地点查询类
    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
    function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);  //关键字查询查询
    }


    var clickHandler = function(e) {
        $('input[name=longitude]').val(e.lnglat.lng);
        $('input[name=latitude]').val(e.lnglat.lat);
        console.log(e.lnglat);
        // marker.setPosition(e.lnglat);
    };

    map.on('click', clickHandler);

    //查询社区机构下拉列表
    /*var agecyOrgSelect = xmSelect.render({
        el: '#orgPid',
        name: 'orgPid',
        layVerify: 'required',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/permissions/org/getListByLikeName',
                data: {
                    name : val,
                    flag : 1,
                    orgType: 4,
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
            }
            if (!data.isAdd) {
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });*/
    //表单验证
    layui.form.verify({
        specialCharacters : function (value) {
            if(!/^[a-zA-Z0-9_\u4e00-\u9fa5\s·]+$/.test(value)){
                return '名称不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '名称首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '名称不能全为数字';
            }
        },
        length : function (value) {
            if (value.length <2 || value.length > 20){
                return  '名称只能输入2-20个字符!'
            }
        },
        phoneNum : function (value) {
            if(value != ''){
                // if(!/^1[3|4|5|7|8]\d{9}$/.test(value)){
                if(value.length != 11){
                    return '请输入正确的手机号码!';
                }
            }
        },
    });

    //  获取机构信息
    common.sendAsyncRequest('/estate/agency/getAgencyById/' + pageData.orgId,'GET',{},function(result){
        var entity = result.data;
        //  填充表单数据
        form.val('entity_form',entity);
        // agecyOrgSelect.
        //  上级机构
        $("#orgPid").val(entity.orgPid);
        $("#org_name").val(entity.orgName);
        $("#region").val(entity.provinceName + '-' + entity.cityName + '-' + entity.areaName);
        //所属机构
        // $("#regionStreet").val(entity.regionStreet);
        // agecyOrgSelect.update({initVal: [entity.orgPid]});

        // $node.orgPid.val(entity.orgPid);
        // $node.regionStreet.val(entity.regionStreet)
        // $node.streetNameInput.val(entity.streetName)

        //点击区后加载街道列表
        /*var streetSelect = xmSelect.render({
            el: '#regionStreet',
            name: 'regionStreet',
            layVerify: 'required',
            radio: true,
            prop: {
                name: 'name',
                value: 'code',
            },
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (areaCode,cb) {
                $.ajax({
                    type: 'GET',
                    url: '/permissions/street/getListByAreaCode',
                    data: {
                        areaCode:areaCode
                    },
                    success: function (result) {
                        cb(result.list);
                    },
                    error: function () {
                        cb([]);
                    }
                });
            },
            //监听选择
            on: function (data) {
                var change = data.change;
                if (change.length > 0) {
                    $node.streetNameInput.val(change[0].name)
                }
                if (!data.isAdd) {
                }
            },
            //显示方式
            model: {
                label: {
                    type: 'text',
                    text: {
                        //左边拼接的字符
                        left: '',
                        //右边拼接的字符
                        right: '',
                        //中间的分隔符
                        separator: ', ',
                    },
                }
            },
        });*/

        //  初始化省市区
        layui.region.init({
            //  元素节点
            elem        :  '#region_body',
            //  触发此元素时显示
            trigger     :   '#region',
            //  初始化选中数据
            selectData        :   {
                province : entity['regionProvince'],
                city : entity['regionCity'],
                county : entity['regionArea']
            },
            //  选中省的回调
            provinceCallbackFn  :   function(data){
                $node.regionInput.val(data.province.text);
                $node.provinceInput.val(data.province.id);
                $node.provinceNameInput.val(data.province.text);
            },
            //  选中市的回调
            cityCallbackFn  :   function(data){
                var address = data.province.text + '-' + data.city.text;
                $node.regionInput.val(address);
                $node.cityInput.val(data.city.id);
                $node.cityNameInput.val(data.city.text);
            },
            //  选中区域的回调
            areaCallbackFn  :   function(data){
                var address = data.province.text + '-' + data.city.text + '-' +data.county.text;
                $node.regionInput.val(address);
                $node.areaInput.val(data.county.id);
                $node.areaNameInput.val(data.county.text);
                streetSelect.update({data:initStreetFn(data.county.id)}).setValue('');
            },
            //清空回调
            clearFn : function(){
                $node.regionInput.val('');
                $node.provinceInput.val('');
                $node.cityInput.val('');
                $node.areaInput.val('');
            }
        });
        // streetSelect.update({initVal:[entity.regionStreet]});
        // $("#orgPid").val(entity.orgPid);
        $("#regionStreet").val(entity.regionStreet);
        // // $node.orgPid.val(entity.orgPid);
        // $node.regionStreet.val(entity.regionStreet)
        // // $node.streetNameInput.val(entity.streetName)
    });



    //  绑定表单提交事件
    form.on("submit(submit_button)",function(data){
        var url = "/estate/agency/editAgency";
        //  提交表单
        common.sendAsyncRequest(url,"POST",data.field,function(){
            $node.resetBtn.click();
            parent.location.reload();
        });
    });

    //  点击取消事件
    $node.resetBtn.on('click',function(){
        //  关闭当前页面弹窗
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });



    function initStreetFn(areaCode){
        var streetList;
        common.sendSyncRequest("/permissions/street/getListByAreaCode", 'get', {
            areaCode: areaCode,

        }, function (result) {
            streetList = result.list;
            return streetList;
        });
        return streetList;
    }

});