"use strict";
layui.extend({
    common    :   'js/common',
    xmSelect    :   'layui/dist/xm-select',
}).use(['jquery','form','common','xmSelect'],function(){
    var $ = layui.jquery;

    var common = layui.common;

    var xmSelect = layui.xmSelect;

    var isSerialNumberExist = false;

    //  页面元素
    var $node = {
        //  取消按钮
        resetBtn        :   $('button[type="reset"]'),
        deviceFactoryInput  :   $('input[name="deviceFactory"]'),
        deviceModelNumberInput  :   $('input[name="deviceModelNumber"]'),
        serialNumberInput   :   $('input[name="serialNumber"]'),
    };

    var pageDate = {
        devicePathType : 0,
        parentId : $('#parentId').val(),
        flag : $('#flag').val()
    };

    //设备厂商
    if ($node.deviceFactoryInput.val() === undefined){
        $.ajax({
            type: 'GET',
            url: '/permissions/dict/getByCode/deviceFactory',
            success: function (result) {
                deviceFactoryDict.update({data:result.list})
            },
        });

        var deviceFactoryDict = xmSelect.render({
            el: '#factory',
            name: 'deviceFactory',
            layVerify: 'required',
            radio: true,
            clickClose: true,
            prop: {
                name: 'dictValue',
                value: 'dictKey',
            },
            //监听选择
            on: function (data) {
                deviceModelNumberSelect.update({data : initDeviceTemplateFn(data),disabled: false});
            },
            //显示方式
            model: {
                label: {
                    type: 'text',
                    text: {
                        //左边拼接的字符
                        left: '',
                        //右边拼接的字符
                        right: '',
                        //中间的分隔符
                        separator: ', ',
                    },
                }
            },
        });

        //设备型号下拉
        var deviceModelNumberSelect = xmSelect.render({
            el:'#device_model_number',
            name:'deviceModelNumber',
            tips:'请先选择设备厂商',
            empty:'暂时没有该设备厂商的设备配置与型号，请先添加该设备厂商的设备配置',
            disabled:true,
            radio: true,
            prop: {
                name: 'typeCode',
                value: 'typeCode'
            },
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod:function (val,cb,show) {
                $.ajax({
                    type: 'GET',
                    url: '/deviceTemplate/manage/getListByLikeTypeCode',
                    data: {
                        deviceFactory : deviceFactoryDict.getValue('keyStr'),
                        typeCode : val,
                        isSelect : true,
                    },
                    success:function (result) {
                        cb(result.list);
                    },
                    error:function () {
                        cb([]);
                    }
                })
            },
            //显示方式
            model: {
                label: {
                    type: 'text',
                    text: {
                        //左边拼接的字符
                        left: '',
                        //右边拼接的字符
                        right: '',
                        //中间的分隔符
                        separator: ', ',
                    },
                }
            },
        });
    }
    function initDeviceTemplateFn(data) {
        var deviceTemplateList;
        common.sendSyncRequest("/deviceTemplate/manage/getListByLikeTypeCode", 'get', {
            deviceFactory : data.change[0].dictKey,
            isSelect : true,
        }, function (result) {
            deviceTemplateList = result.list;
        });
        return deviceTemplateList;
    }


    //小区查询下拉列表
    var residentialSelect = xmSelect.render({
        el: '#residential_id',
        name: 'xqId',
        layVerify: 'required',
        tips: '请选择小区',
        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;
            $('input[name="xqName"]').val(change.name)
            if (change.length > 0) {
                unitSelect.update({data : initUnitFn(change[0].id),disabled: false });
            }
            if (!data.isAdd) {
                unitSelect.update({disabled: true });
                devicePathSelect.update({disabled: true });
            }
            //重置单元选择
            unitSelect.setValue([]);
            devicePathSelect.setValue([]);
            $('input[name="unitName"]').val('');
            $('input[name="installPath"]').val('');
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //单元查询下拉列表
    var unitSelect = xmSelect.render({
        el: '#unit_id',
        name: 'unitId',
        disabled: true,
        tips: '请选择位置类型',
        radio: true,
        toolbar: {
            show: true,
            list: [{
                name: '单元',
                method : function(data){
                    pageDate.devicePathType = 1;
                }
            },{
                name: '小区',
                method : function(data){
                    pageDate.devicePathType = 0;
                    devicePathSelect.update({data:initDevicePathFn(residentialSelect.getValue('valueStr'),pageDate.devicePathType),disabled:false});
                    unitSelect.setValue([{name:'小区',value:''}]).closed()
                }
            }]
        },
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/estate/unit/getListByLikeName',
                data: {
                    name : val,
                    // residentialId : residentialSelect.getValue('valueStr'),
                    residentialId : pageDate.flag==2?pageDate.parentId:residentialSelect.getValue('valueStr'),
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                pageDate.devicePathType = 1;
                $('input[name="unitName"]').val(change[0].name)
                devicePathSelect.update({data:initDevicePathFn(residentialSelect.getValue('valueStr'),pageDate.devicePathType),disabled:false})
            }
            if (!data.isAdd) {}
            devicePathSelect.setValue([])
            $('input[name="installPath"]').val('')
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //单元查询下拉列表
    var devicePathSelect = xmSelect.render({
        el: '#install_path_id',
        name: 'installPathId',
        layVerify: 'required',
        disabled: true,
        tips: '请选择设备位置',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/device/path/getDevicePathListByName',
                data: {
                    name : val,
                    residentialId : residentialSelect.getValue('valueStr'),
                    type : pageDate.devicePathType,
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                $('input[name="installPath"]').val(change[0].name)
            }
            if (!data.isAdd) {
                $('input[name="installPath"]').val('')
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });
    function initUnitFn(residentialId) {
        var unitList;
        common.sendSyncRequest("/estate/unit/findListByPosition", 'get', {residentialId: residentialId}, function (result) {
            unitList = result.list;
        });
        return unitList;
    }
    function initDevicePathFn(residentialId,type) {
        var devicePathList;
        common.sendSyncRequest("/device/path/getDevicePathListByName", 'get', {xqId: residentialId,type:type}, function (result) {
            devicePathList = result.list;
        });
        return devicePathList;
    }

    //  绑定表单提交事件
    layui.form.on("submit(entity_submit_event)",function(data){
        common.timer($('button[lay-filter="entity_submit_event"]'));
        $.ajax({
            url     :   '/device/manage/complete',
            data    :   data.field,
            type    :   'POST',
            success :   function (result) {
                if (result.code === '200'){
                    $node.resetBtn.click();
                    parent.location.reload();
                } else {
                    layer.alert(result.msg);
                }
            }
        });
    });

    //  点击取消事件
    $node.resetBtn.on('click',function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

    //  表单校验
    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个字符!'
            }
        },
        //  密码校验
        password   : [
            /^[0-9]{4,6}$/
            ,'密码由4到6个数字组成'
        ],
        //  密码校验
        adminPassword   : [
            /^[0-9]{4,8}$/
            ,'管理密码由4到8个数字组成'
        ],
        uniqueSerialNumber: function(value, item){
            if (isSerialNumberExist){
                return "设备序列号已存在!";
            }
        },
        letterAndNumber : function (value) {
            if (!/^[A-Za-z0-9-_]+$/.test(value)){
                return '只能输入英文字母、数字、-和_'
            }
        }
    });

    //失焦事件提前判断，解决校验异步结果还没返回就执行提交方法的问题
    //失焦事件，根据序列号获取设备信息，来判断设备是否已存在
    $node.serialNumberInput.on("blur", function(){
        var value = this.value;
        if (!value){
            return;
        }
        $.ajax({
            url     :   '/device/manage/getDeviceBySerialNumber',
            data    :   {serialNumber : value},
            type    :   'GET',
            success :   function (result) {
                if (result.code === '200'){
                    if (result.data){
                        // return "设备序列号已存在!";
                        isSerialNumberExist = true;
                    }else{
                        isSerialNumberExist = false;
                    }
                } else {
                    layer.alert(result.msg);
                }
            }
        });
    });

    (function() {
        if (pageDate.parentId != null){
            switch (pageDate.flag) {
                case '2':
                    $.ajax({
                        type: 'GET',
                        url: '/estate/residential/findResidentialById/'+pageDate.parentId,
                        success: function (result) {
                            residentialSelect.update({disabled:true,data:[result.data]}).setValue([pageDate.parentId]);
                            unitSelect.update({disabled: false });
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    })()
});
