let userInfo = window.localStorage && JSON.parse(localStorage.getItem('_userInfo'))
$(function () {

    $("#jqGrid").Grid({
        url: '../sys/user/staffList',
        postData: {
            deptId: userInfo.deptId,
            bindStatus: ''
        },
        rownumWidth: 60,
        multiboxonly: true,
        prmNames: {
            page: "pageNum",
            rows: "pageSize",
            order: "order"
        },
        jsonReader: {
            root: "list",
            page: "curPage",
            total: "totalPageNum",
            records: "totalNum"
        },
        colModel: [{
                label: 'ID',
                name: 'userId',
                index: "userId",
                key: true,
                hidden: true
            },
            {
                label: '所属公司',
                name: 'deptName',
                width: 75
            },
            {
                label: '员工名称',
                name: 'username',
                width: 75
            },
            {
                label: '手机号',
                name: 'mobile',
                width: 100
            },
            {
                label: '角色',
                name: 'roleName',
                width: 100,
                sortable: false
            },
            {
                label: '状态',
                name: 'status',
                index: 'create_time',
                width: 100,
                formatter: function (value) {
                    return value ? '正常' : '禁用'
                }
            },
            {
                label: '创建时间',
                name: 'createTime',
                index: 'create_time',
                width: 100,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd');
                }
            },
        ]
    });
});

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

const validatePhoneCheck = async function (rule, value, callback) {
    if (value === '' || !value) {
        callback(new Error('手机号不能为空'));
    } else if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('手机号不正确'));
    } else {
        await $.ajax({
            url: "../sys/user/checkUser?phoneNum=" + value,
            async: true,
            success: function (data) {
                if (data.code == 0) {
                    $('#isSign').hide()
                } else {
                    $('#isSign').show()
                }

            }
        })

        callback();

        // callback(new Error('手机号未在指房宝APP中进行注册'));
    }
};


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

var vm = new Vue({
    el: '#rrapp',
    data: {
        delInfo: {
            list: [],
            type: 1,
            select: '',
        },

        show_delModal: false,
        userRole: userInfo.roleIdList[0],
        modal1: false,
        q: {
            key: '',
            deptName: ''
        },
        showList: true,
        title: null,
        lessNum: 0,
        roleList: {},
        user: {
            status: 1,
            deptName: '',
            roleId: '',
            roleIdList: [],
            brandIdList: [],
            brandList: []
        },
        delValidate: {
            select: [{
                required: true,
                message: '请选择迁移的员工',
                trigger: 'change'
            }],
        },
        ruleValidate: {
            username: [{
                required: true,
                message: '用户名不能为空',
                trigger: 'blur'
            }],
            roleId: [{
                required: true,
                validator: validateNoNullCheck,
                msg: '角色',
                trigger: 'change'
            }],
            status: [{
                required: true,
                validator: validateNoNullCheck,
                msg: '状态',
                trigger: 'change'
            }],
            // deptName:[{required: true, message: '所属公司不能为空', trigger: 'change'}],
            // email: [
            //     {required: true, message: '邮箱不能为空', trigger: 'blur'},
            //     {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
            // ],
            mobile: [{
                required: true,
                validator: validatePhoneCheck,
                trigger: 'blur'
            }]
        },
        brandsList: [],
        brandPage: 1,
        brandPerPage: 10,
        brandTotal: 0,
        brandSeleced: [],
        social: [],
        cacheData: {},
        cacheDataFirst: {}
    },
    watch: {
        brandPage: function name(newVal) {
            this.getBrandList()
        }
    },
    mounted() {
        this.getLessNum()
    },
    methods: {
        getLessNum: function () {
            Ajax.request({
                url: '../sys/dept/getLessNum?deptId=' + userInfo.deptId,
                async: true,
                successCallback: function (r) {
                    vm.lessNum = r.less
                }
            });
        },
        clickCheck: function (item, idx) {
            item['checked'] = !item['checked']
            this.$set(this.brandsList, idx, item)
        },
        open: function () {
            var data = getSelectedRowData("#jqGrid");
            if (data == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '绑定员工',
                content: `../shop/selectUser.html?name=${data.name}&sceneName=${data.sceneName}&id=${data.id}`
            })
        },
        ok: function () {
            let temp = []
            let tempid = []
            var that = this
            Object.keys(vm.cacheData).forEach(function (item) {
                that.cacheData[item].page.list.forEach(function (sub) {
                    if (sub['checked']) {
                        temp.push(sub)
                        tempid.push(sub.id)
                    }
                })
            })
            vm.user.brandList = temp
            vm.user.brandIdList = tempid
        },
        cancel: function () {
            this.cacheData = {}
            this.modal1 = false
        },
        query: function () {
            vm.reload();

        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.roleList = {};
            vm.user = {
                status: 1,
                roleId: '',
                roleIdList: [],
                brandIdList: [],
                deptId: '',
                deptName: ''
            };

            //获取角色信息
            this.getRoleList();
            vm.getDept();
        },
        getDept: function () {
            //加载公司树
            Ajax.request({
                url: "../sys/dept/list?name=",
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#deptTree"), setting, r.list);
                    var node = ztree.getNodeByParam("deptId", vm.user.deptId);
                    if (node != null) {
                        ztree.selectNode(node);

                        vm.user.deptName = node.name;
                    }
                }
            });
        },
        pageChange: function (page) {
            this.brandPage = page
        },
        getBrandList: function () {
            this.modal1 = true
            if (this.cacheData[this.brandPage]) {
                let temp = this.cacheData[this.brandPage]
                this.brandsList = temp.page.list
                this.brandPage = temp.page.currPage
                this.brandTotal = temp.page.totalCount
                return
            }
            let that = this

            Ajax.request({
                url: '../brand/list?_search=false&limit=' + that.brandPerPage + '&page=' + that.brandPage + '&sidx=&order=asc',
                async: true,
                successCallback: function (res) {
                    res.page.list.forEach(function (item, index) {
                        item['checked'] = false
                        if (that.user.brandList) {
                            that.user.brandList.forEach(function (sub) {
                                // item['checked'] = false
                                if (item.id === sub.brandId || item.id === sub.id) {
                                    item['checked'] = true
                                    return
                                }
                            })
                        }
                    })

                    that.cacheData[res.page.currPage] = res
                    that.brandsList = res.page.list
                    that.brandPage = res.page.currPage
                    that.brandTotal = res.page.totalCount
                }
            });
        },
        update: function () {
            var userId = getSelectedRow("#jqGrid");
            if (userId == null) {
                return;
            }

            vm.showList = false;
            vm.title = "修改";

            Ajax.request({
                url: "../sys/user/info/" + userId,
                async: true,
                successCallback: function (r) {
                    vm.user = r.user;
                    vm.user.roleId = vm.user.roleIdList[0]

                    console.log(vm.user.roleId);
                    //获取角色信息
                    vm.getRoleList();
                    vm.getDept();
                }
            });

        },
        comfirmDel() {
            if (this.delInfo.type == 3) {
                this.$refs['formDelValidate'].validate((valid) => {
                    if (valid) {
                        vm.del()
                    }
                })
            } else if (this.delInfo.type == 2) {
                vm.show_delModal = false
            } else if (this.delInfo.type == 1) {
                vm.del()
            }


        },
        cancelDel() {
            // this.$Message.info('点击了取消');
            vm.show_delModal = false
        },
        checkDel: function () {
            var userIds = getSelectedRows("#jqGrid");

            if (userIds == null) {
                return;
            }
            if (userIds.length > 1) {
                alert("只能选择一条记录");

                return;
            }
            let params = {
                "userId": userIds.join(),
            }

            Ajax.request({
                url: "../sys/user/preDeleteStaff",
                contentType: 'application/json',
                dataType: 'json',
                params: JSON.stringify(params),
                type: 'POST',
                successCallback: function (r) {
                    console.log(r)
                    vm.show_delModal = true
                    if (r.code == 0) {
                        if (r.list) {
                            //需先进行场景重新分配用户
                            vm.delInfo.type = 3
                            vm.delInfo.list = r.list
                            // vm.delInfo.msg = r.msg
                        } else {
                            //可删除

                            vm.delInfo.type = 1
                        }

                        // vm.delInfo.msg = r.msg
                    } else if (r.code == 500) {
                        //不可删除
                        vm.delInfo.type = 2
                        // vm.delInfo.msg = r.msg
                    }


                },
                failCallback: function (error) {
                    // vm.show_delModal = true
                }

            });
        },
        del: function () {
            var userIds = getSelectedRows("#jqGrid");
            // if (userIds == null) {
            //     return;
            // }
            let params = {
                userId: userIds.join(),
            }
            if (vm.delInfo.type == 3) {
                params.toUser = vm.delInfo.select
            }
            vm.show_delModal = false
            // confirm('确定要删除选中的记录？', function () {
            Ajax.request({
                url: "../sys/user/deleteStaff",
                params: JSON.stringify(params),
                contentType: "application/json",
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
            // });
        },
        saveOrUpdate: function (event) {
            if ($('#isSign').css("display") == 'block') {
                return alert('手机号未在指房宝APP中进行注册')
            }
            var url = vm.user.userId == null ? "../sys/user/staffSave" : "../sys/user/update";
            vm.user.roleIdList = [vm.user.roleId]
            vm.user.deptId = vm.user.userId == null ? userInfo.deptId : vm.user.deptId
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.user),
                contentType: "application/json",
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        getRoleList: function () {
            Ajax.request({
                url: '../sys/role/select',
                async: true,
                successCallback: function (r) {
                    vm.roleList = r.list;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'staffName': vm.q.key,
                    'deptName': vm.q.deptName
                },
                page: 1
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
            vm.getLessNum()
        },
        deptTree: function () {
            openWindow({
                title: "选择公司",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级公司
                    vm.user.deptId = node[0].deptId;
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
            this.cacheData = {}
            this.user = {
                status: 1,
                deptName: '',
                roleIdList: [],
                roleId: '',
                brandIdList: [],
                brandList: []
            }
        }
    }
});