'use strict';

/**
 * 项目信息js
 *
 * @author EllisRan.
 * @date 2019/3/19
 * @version
 */

$(document).ready(() => {
    // 启用和停用账号
    $('.account-switch-btn').on('click', function () {
        const data = {
            enable: $(this).hasClass('btn-outline-success') ? 1 : 0,
            id: $(this).data('account'),
        };
        postData('/setting/user/switch', data, function () {
            window.location.href = '/setting/user';
        });
    });

    // 编辑账号
    $('a[data-target="#edit-user"]').on('click', function () {
        const account = $(this).data('account');
        $('#edit-user input[name="account"]').val(account.account);
        $('#edit-user input[name="name"]').val(account.name);
        $('#edit-user input[name="company"]').val(account.company);
        $('#edit-user input[name="role"]').val(account.role);
        $('#edit-user input[name="mobile"]').val(account.mobile);
        $('#edit-user input[name="telephone"]').val(account.telephone);
        $('#edit-user input[name="id"]').val(account.id);
        $('#edit-user select[name="account_group"]').val(account.account_group);
        $('#edit-user input[class="account-check"]').val(account.account);
    });

    // 分配随机密码
    $("#rand-password").click(function() {
        const password = randPassword();
        $(this).parent().parent().find('input').val(password);
    });

    // 重置密码
    let isChange = false;
    $("#reset-password-btn").click(function() {
        try {
            if (isChange) {
                throw '稍后再操作';
            }
            const resetPassword = $("#reset-password").val();
            const id = $("#user-id").val();
            if (resetPassword.length < 6) {
                throw '密码长度不能小于6';
            }
            if (!/^[0-9a-zA-Z*~!@&%$^\\(\\)#_\[\]\-\+={}|?'":,<>.`]+$/.test(resetPassword)) {
                throw '密码只支持英文数字及符号';
            }
            const btn = $(this);
            $.ajax({
                url: '/setting/user/reset/password',
                type: 'post',
                data: { id: id, reset_password: resetPassword },
                dataType: 'json',
                error: function() {
                    isChange = false;
                    btn.html('重置密码');
                    throw '网络错误!';
                },
                beforeSend: function(xhr) {
                    let csrfToken = Cookies.get('csrfToken');
                    xhr.setRequestHeader('x-csrf-token', csrfToken);
                    isChange = true;
                    btn.html('<i class="fa fa-spinner fa-pulse"></i>');
                },
                success: function(response) {
                    isChange = false;
                    btn.html('重置密码');
                    if (response.err !== 0) {
                        throw response.msg;
                    }
                    $("#reset-password").val('');
                    toast('重置成功', 'success', 'check');
                }
            });
        } catch (error) {
            toast(error, 'error', 'exclamation-circle');
            console.log(error);
        }
    });

    // 账号查重
    $('input[name="account"]').on('blur', function () {
        const self = $(this);
        if (self.val() !== self.siblings('input').val()) {
            const data = {account: $(this).val()};
            postData('/setting/user/exist', data, function (data) {
                if (data === null) {
                    self.removeClass('is-invalid');
                } else {
                    self.addClass('is-invalid');
                }
            })
        } else {
            self.removeClass('is-invalid');
        }
    });

    // 选中创建标段才可以选择协作办公
    $('a[data-target="#edit-user2"]').on('click', function () {
        $('#edit-user2 input:radio').prop('checked', false);
        $('#edit-user2 input:checkbox').prop('checked', false);
        const account = $(this).data('account');
        $('#edit-user2 input[name="id"]').val(account.id);
        // 权限赋值
        if (account.permission !== '') {
            const permission = JSON.parse(account.permission);
            for (const pm in permission) {
                if (pm === 'tender' && permission[pm].indexOf('1') !== -1) {
                    $('#edit-user2 input[name="cooperation"]').attr('disabled', false);
                } else {
                    $('#edit-user2 input[name="cooperation"]').attr('disabled', true);
                }
                for (const index of permission[pm]) {

                    $('#edit-user2 input:checkbox[id="' + pm + '_' + index + '"]').prop('checked', true);
                }
            }
        }
        // 协作赋值
        $('#edit-user2 input:radio[value="' + account.cooperation + '"]').prop('checked', true);
    });

    // 选择创建标段功能后可选协作办公
    $('#edit-user2 input:checkbox').click(function () {
        if ($(this).attr('id') === 'tender_1') {
            if ($(this).is(':checked')) {
                $('#edit-user2 input[name="cooperation"]').attr('disabled', false);
            } else {
                $('#edit-user2 input[name="cooperation"]').attr('disabled', true);
            }
        }
    })
});


/**
 * 表单检测
 */
function checkUserForm(status) {
    try {
        if (status === 'add') {
            if ($('#add-user select[name="account_group"]').val() == 0) {
                throw '请选择账号组';
            }
            if ($('#add-user input[name="account"]').val() == '' || $('#add-user input[name="account"]').hasClass('is-invalid')) {
                throw '账号不能为空或已存在';
            }
            if ($('#add-user input[name="password"]').val() == '' || $('#add-user input[name="password"]').val().length < 6) {
                throw '密码不能为空或不能小于6位';
            }
            if (!/^[0-9a-zA-Z*~!@&%$^\\(\\)#_\[\]\-\+={}|?'":,<>.`]+$/.test($('#add-user input[name="password"]').val())) {
                throw '密码只支持英文数字及符号';
            }
            if ($('#add-user input[name="name"]').val() == '') {
                throw '姓名不能为空';
            }
            if ($('#add-user input[name="company"]').val() == '') {
                throw '单位名称不能为空';
            }
            if ($('#add-user input[name="role"]').val() == '') {
                throw '职位名称不能为空';
            }
            if ($('#add-user input[name="mobile"]').val() == '') {
                throw '手机号不能为空';
            }
        } else {
            if ($('#edit-user select[name="account_group"]').val() == 0) {
                throw '请选择账号组';
            }
            if ($('#edit-user input[name="account"]').val() == '' || $('#add-user input[name="account"]').hasClass('is-invalid')) {
                throw '账号不能为空或已存在';
            }
            if ($('#edit-user input[name="name"]').val() == '') {
                throw '姓名不能为空';
            }
            if ($('#edit-user input[name="company"]').val() == '') {
                throw '单位名称不能为空';
            }
            if ($('#edit-user input[name="role"]').val() == '') {
                throw '职位名称不能为空';
            }
            if ($('#edit-user input[name="mobile"]').val() == '') {
                throw '手机号不能为空';
            }
        }
    } catch (err) {
        toast(err, 'error', 'exclamation-circle');
        return false;
    }
}

/**
 * 随机密码
 */
function randPassword() {
    let result = '';
    // 随机6-10位
    const length = Math.ceil(Math.random() * 2 + 8);
    let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
        'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
        'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

    const randSeed = stringSeed.concat(numberSeed);
    const seedLength = randSeed.length - 1;
    for (let i = 0; i < length; i++) {
        const index = Math.ceil(Math.random() * seedLength);
        result += randSeed[index];
    }

    return result;
}
