$(function () {
    // initialPage();
    // getGrid();
});

var TreeGrid = {
    id: "deptTable",
    table: null,
    layerIndex: -1
};

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

const validatezishu =function (rule, value, callback)  {
        
    let size = rule.size?parseInt(rule.size):50

    if (value === '' || !value) {
        callback(new Error(rule.name+'不能为空'));
    }
    else if(value.length>size){
        callback(new Error(rule.name+'不能超过'+rule.size+'个字符'));
    }else {
        callback();
    }
};

let rule1 = {
    deptName: [
        {required: true, name: '所在公司', size:15,validator: validatezishu, trigger: 'blur'}
    ],
    adminUserName: [
        {required: true, message: '所属管理员名称不能为空', trigger: 'blur'}
    ],
    adminPhoneNum: [
        {required: true, message: '绑定管理员电话不能为空', trigger: 'blur'}
    ],
    smsCode: [
        {required: true, message: '验证码不能为空', trigger: 'blur'}
    ]
}

let rule2 = {
    parentName: [
        {required: true, message: '总公司名称不能为空', trigger: 'change'}
    ],
    parentAdminPhoneNum: [
        {required: true, message: '所属管理员电话不能为空', trigger: 'blur'}
    ],
    parentSmsCode: [
        {required: true, message: '验证码不能为空', trigger: 'blur'}
    ],
    deptName: [
        {required: true, name: '所在公司', size:15,validator: validatezishu, trigger: 'blur'}
    ],
    adminUserName: [
        {required: true, message: '所属管理员名称不能为空', trigger: 'blur'}
    ],
    adminPhoneNum: [
        {required: true, message: '绑定管理员电话不能为空', trigger: 'blur'}
    ],
    smsCode: [
        {required: true, message: '验证码不能为空', trigger: 'blur'}
    ]
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        isNext:false,
        active:0,
        comfirmActive:'',
        showList: true,
        interTime: 60,
        jishi: false,
        interl: null,
        interTime2: 60,
        jishi2: false,
        interl2: null,
        title: null,
        userinfo:'',
        dept: {
            adminPhoneNum: "",
            adminUserName: "",
            deptName: "",
            parentAdminPhoneNum: "",
            parentId: '',
            parentName: "",
            parentSmsCode: "",
            smsCode: "",
            type: ""
        },
        rule1,
        rule2
    },
    computed:{
        ruleValidate(){
            return this.comfirmActive === 1 ? rule1 : rule2
        }
    },
    watch:{
        comfirmActive(val){
            vm.dept= {
                adminPhoneNum: "",
                adminUserName: "",
                deptName: "",
                parentAdminPhoneNum: "",
                parentId: '',
                parentName: "",
                parentSmsCode: "",
                smsCode: "",
                type: ""
            }
            this.dept.adminUserName = this.userinfo.username
            this.dept.adminPhoneNum = this.userinfo.mobile
            this.clearTime(2)
            this.clearTime()
            if (val==2) {
                this.getDept();
            }
        }
    },
    methods: {
        clearTime:function (secend='') {
            vm['jishi'+secend] = false
            vm['interTime'+secend] = 60
            clearInterval(vm['interl'+secend])
            vm['interl'+secend] = null
        },
        getDept: function () {
            //加载部门树
            Ajax.request({
                url: "../sys/dept/anonList",
                type:'post',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#deptTree"), setting, r.list);
                }
            });
        },

        validCode:function () {
            let params = {
                parentAdminPhoneNum: vm.comfirmActive ==2 ? vm.dept.parentAdminPhoneNum:'',
                parentId: vm.comfirmActive ==2 ? vm.dept.parentId:'',
                parentSmsCode: vm.comfirmActive ==2 ? vm.dept.parentSmsCode:'',
            }
            Ajax.request({
                url: "../sys/dept/validParentAdmin",
                async: true,
                contentType: "application/json",
                params: JSON.stringify(params),
                type: "POST",
                successCallback: function (result) {
                    vm.isNext = true
                }
            });
        },

        getSmsCode:function (num, secend='', deptId='') {
            if (vm['jishi'+secend]) {
                return
            }
            if (deptId) {
                if (!vm.dept.parentId) {
                    return alert('请选择总公司名称');
                }
            }
            Ajax.request({
                url: "../sys/sms/authCode/",
                params: {"phoneNum": num,"deptId":deptId?vm.dept.parentId:null},
                type:'post',
                async: true,
                successCallback: function (r) {
                    if (r.code == 0) {
                        vm['interl'+secend] && clearInterval(vm['interl'+secend])
                        vm['interl'+secend] = null
                        vm['jishi'+secend] = true
                        vm['interl'+secend] = setInterval(() => {
                            vm['interTime'+secend]--
                          if (vm['interTime'+secend] <= 0) {
                            vm['jishi'+secend] = false
                            vm['interTime'+secend] = 60
                            clearInterval(vm['interl'+secend])
                            vm['interl'+secend] = null
                          }
                        }, 1000)
                    }
                    alert(r.msg, function () {
                        
                    });
                }
            });
        },
        saveOrUpdate: function () {
            let params = {
                adminPhoneNum: vm.dept.adminPhoneNum,
                adminUserName: vm.dept.adminUserName,
                deptName: vm.dept.deptName,
                smsCode: vm.dept.smsCode,
                parentAdminPhoneNum: vm.comfirmActive ==2 ? vm.dept.parentAdminPhoneNum:'',
                parentId: vm.comfirmActive ==2 ? vm.dept.parentId:'',
                parentName: vm.comfirmActive ==2 ? vm.dept.parentName:'',
                parentSmsCode: vm.comfirmActive ==2 ? vm.dept.parentSmsCode:'',
                type:  vm.comfirmActive ==2 ? 'join':'new'
            }
            Ajax.request({
                url: "../sys/dept/createDept",
                async: true,
                contentType: "application/json",
                params: JSON.stringify(params),
                type: "POST",
                successCallback: function (result) {
                    if (result.code == 0) {
                        alert('操作成功', function (index) {
                            setTimeout(() => {
                                parent.location.href = '/platform-framework/index.html';
                            }, 500);
                        });
                        
                    }
                }
            });
        },
        update: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }
            Ajax.request({
                url: "../sys/dept/info/" + deptId,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "修改";
                    vm.dept = r.dept;

                    vm.getDept();
                }
            });
        },
        del: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../sys/dept/delete",
                    params: {"deptId": deptId},
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        
        deptTree: function () {
            openWindow({
                title: "选择公司",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.dept.parentId = node[0].deptId;
                    vm.dept.parentName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    },
    mounted(){
        this.userinfo = JSON.parse(localStorage.getItem('userInfo'))
    }
});

function getDeptId() {
    var selected = $('#deptTable').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        alert("请选择一条记录");
        return false;
    } else {
        return selected[0].id;
    }
}