$(function() {
    initialPage();
    getGrid("../sys/dept/list?name=");
});

function initialPage() {
    $(window).resize(function() {
        TreeGrid.table.resetHeight({ height: $(window).height() - 100 });
    });
}

const deptData = {}

function getGrid(url) {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, url, colunms);
    table.setExpandColumn(2);
    table.setIdField("deptId");
    table.setCodeField("deptId");
    table.setParentCodeField("parentId");
    table.setExpandAll(true);
    table.setHeight($(window).height() - 100);
    TreeGrid.table = table;
    TreeGrid.table.init()
}

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


/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function() {

    function dateFtt(fmt, date) { //author: meizz   
        var o = {
            "M+": date.getMonth() + 1, //月份   
            "d+": date.getDate(), //日   
            "h+": date.getHours(), //小时   
            "m+": date.getMinutes(), //分   
            "s+": date.getSeconds(), //秒   
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
            "S": date.getMilliseconds() //毫秒   
        };

        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    var columns = [
        { field: 'selectItem', radio: true },
        { title: '公司ID', field: 'deptId', visible: false, align: 'center', valign: 'middle', width: '80px' },
        { title: '公司名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '180px' },
        { title: '账号', field: 'managerPhoneNum', align: 'center', valign: 'middle', sortable: true, width: '180px' },
        { title: '上级公司', field: 'parentName', align: 'center', valign: 'middle', sortable: true, width: '100px' },
        { title: '可新增员工数', field: 'staffNum', align: 'center', valign: 'middle', sortable: true, width: '100px' },
        { title: '已有员工数', field: 'curStaffNum', align: 'center', valign: 'middle', sortable: true, width: '100px' },
        { title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '100px' },
        {
            title: '到期时间',
            field: 'expirationDate',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: '100px',
            formatter: function(value, row, index) {
                return dateFtt("yyyy-MM-dd", new Date(value.expirationDate))
            }
        }
    ]
    return columns;
};

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

const validateNoNullCheck = function(rule, value, callback) {
    console.log(value)
    if (value == '' || !value) {
        callback(new Error(rule.msg + '不能为空'));
    } else {
        callback();
    }
};



let rule1 = {
    username: [
        { required: true, message: '指房宝APP账号不能为空', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '所属密码不能为空', trigger: 'blur' }
    ]
}

let rule2 = {
    name: [
        { required: true, message: '公司名称不能为空', trigger: 'blur' }
    ],
    logoUrl: [
        { required: true, message: '公司封面不能为空', trigger: 'blur' }
    ],
    expirationDate: [
        { required: true, message: '到期时间不能为空', trigger: 'change', pattern: /.+/ }
    ],
    staffNum: [
        { required: true, validator: validateNoNullCheck, msg: '可新增员工数', trigger: 'blur' }
    ],
    // orderNum: [
    //     {required: true, validator: validateNoNullCheck,  msg: '排序号', trigger: 'blur'}
    // ]
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        comfirmActive: 1,
        showList: true,
        title: null,
        dept: {
            password: '',
            username: '',
            staffNum: null,
            name: '',
            orderNum: null,
            logoUrl: '',
            expirationDate: '',
            deptId: ''
        },
        rule1,
        rule2,
        q: {
            name: ''
        }
    },

    methods: {
        limitNum() {
            if (this.dept.staffNum - 0 == 0 && this.dept.staffNum.length == 1) {
                this.dept.staffNum = 1
            } else {
                this.dept.staffNum = this.dept.staffNum.replace(/[^0-9]/g, '')

            }
        },
        dateFormat: function(fmt, date) { //author: meizz   
            var o = {
                "M+": date.getMonth() + 1, //月份   
                "d+": date.getDate(), //日   
                "h+": date.getHours(), //小时   
                "m+": date.getMinutes(), //分   
                "s+": date.getSeconds(), //秒   
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
                "S": date.getMilliseconds() //毫秒   
            };

            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        handleSuccessPicUrl: function(res, file) {
            // vm.goods.logoUrl = file.response.url
            vm.dept.logoUrl = file.response.url + window.fixImg + 'm_fixed,w_108,h_81';

        },
        handleFormatError: function(file) {
            this.loading = false
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function(file) {
            this.loading = false
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大。'
            });
        },
        eyeImageItemPicUrl: function(url) {
            eyeImage(url);
        },
        validUser: function() {
            let params = {
                username: vm.dept.username,
                password: encodeStr(Base64.encode(vm.dept.password)),
                // password: vm.dept.password
            }
            if (!vm.dept.username || !vm.dept.password) {
                return alert('信息未填写完整');
            }
            // vm.comfirmActive = 2
            Ajax.request({
                url: "../sys/loginWithoutAuth",
                async: true,
                contentType: "application/json",
                params: JSON.stringify(params),
                type: "POST",
                successCallback: function(result) {
                    vm.comfirmActive = 2
                }
            });
        },
        getDept: function() {
            //加载公司树
            Ajax.request({
                url: "../sys/dept/select",
                async: true,
                successCallback: function(r) {
                    ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                    var node = ztree.getNodeByParam("deptId", vm.dept.parentId);
                    if (node) {
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    } else {
                        node = ztree.getNodeByParam("deptId", 0);
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    }
                }
            });
        },
        validatorDept: function(id, cb) {
            Ajax.request({
                url: "../sys/dept/countDeptLevel?deptId=" + id,
                async: true,
                successCallback: function(r) {
                    cb(r)
                }
            });
        },
        add: function() {
            vm.comfirmActive = 1
            vm.showList = false;
            vm.title = "新增";
            vm.dept = {
                password: '',
                username: '',
                staffNum: null,
                name: '',
                orderNum: null,
                logoUrl: '',
                expirationDate: ''
            };
            return

        },
        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 = "修改";
                    r.dept.expirationDate = vm.dateFormat("yyyy-MM-dd", new Date(r.dept.expirationDate))
                    vm.dept = r.dept;
                    // vm.dept.expirationDate = dateFtt("yyyy-MM-dd",new Date(r.dept.expirationDate))
                    console.log(vm.dept);
                    vm.comfirmActive = 2
                        // vm.getDept();
                }
            });
        },
        back: function() {
            if (vm.title === "修改") {
                vm.reload();
            } else {
                vm.comfirmActive = 1
            }
        },
        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();
                        });
                    }
                });
            });
        },
        saveOrUpdate: function(event) {
            vm.dept.expirationDate = this.dateFormat("yyyy-MM-dd", vm.dept.expirationDate)
            var date_format = /^(\d{4})-(\d{2})-(\d{2})$/
            if (!date_format.test(vm.dept.expirationDate)) {
                alert("格式错误！" + "(到期时间格式：yyyy-MM-dd)")
                return
            }
            var url = vm.dept.deptId == null ? "../sys/dept/save" : "../sys/dept/update";
            if (vm.dept.username) {
                vm.dept.managerPhoneNum = vm.dept.username
            }
            Ajax.request({
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.dept),
                type: 'POST',
                successCallback: function() {
                    alert('操作成功', function(index) {
                        vm.reload();
                    });
                }
            });
        },
        query: function() {
            getGrid('../sys/dept/list?name=' + vm.q.name);
        },
        deptTree: function() {
            openWindow({
                title: "选择公司",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function(index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级公司
                    vm.validatorDept(node[0].deptId, function(r) {
                        if (r.num < 5) {
                            vm.dept.parentId = node[0].deptId;
                            vm.dept.parentName = node[0].name;
                            layer.close(index);
                        } else {
                            return alert('部门层级已经达到5层了，无法再创建子部门');
                        }
                    })

                }
            });
        },
        reload: function() {
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        handleSubmit: function(name) {
            console.log(vm.dept.staffNum)
            handleSubmitValidate(this, name, function() {
                vm.saveOrUpdate()
            });
        },
        handleReset: function(name) {
            handleResetForm(this, name);
        }
    }
});

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