'use strict';
/**
 * 变更令详细页js
 *
 * @author EllisRan.
 * @date 2018/11/22
 * @version
 */
$.event.special.valuechange = {
    teardown: function (namespaces) {
        $(this).unbind('.valuechange');
    },
    handler: function (e) {
        $.event.special.valuechange.triggerChanged($(this));
    },
    add: function (obj) {
        $(this).on('keyup.valuechange cut.valuechange paste.valuechange input.valuechange', obj.selector, $.event.special.valuechange.handler)
    },
    triggerChanged: function (element) {
        var current = element[0].contentEditable === 'true' ? element.html() : element.val()
            , previous = typeof element.data('previous') === 'undefined' ? element[0].defaultValue : element.data('previous');
        if (current !== previous) {
            element.trigger('valuechange', [element.data('previous')]);
            element.data('previous', current);
        }
    }
};
$(document).ready(() => {
    // tab切换
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        const tab = $(this).attr('aria-controls');
        $('.show_title').hide();
        $('#'+ tab +'_title').show();
        if (tab === 'bills' && $('#bills').hasClass('first-bill-pane')) {
            if (table) {
                table.destroy();
            }
            table = $('.table-list').removeAttr('width').DataTable(billsTable);
            if (!$('.change-detail-checkbox').is(':checked')) {
                const column = table.column(3);
                column.visible(!column.visible());
            }
            $('#bills').removeClass('first-bill-pane');
        }
    });
    $('#add-bj').on('click', 'input[type="checkbox"]', function () {
        const isCheck = $(this).prop('checked')
        if (isCheck) {
            $('#add-bj input[type="checkbox"]').each(function () {
                $(this).prop('checked', false)
            })
            $(this).prop('checked', true)
        }
    })
    $('#bg-copy').click(function() {
        const cid = $('#add-bj input:checked').data('id')
        postData(window.location.pathname + '/copy', cid, function () {
            window.location.reload()
        })
    })
    // 上传附件
    $('#upload-file-btn').click(function () {
        const files = $('#upload-file')[0].files;
        const formData = new FormData();
        formData.append('cid', $('#changeId').val());
        formData.append('tid', $('#tenderId').val());
        for (const file of files) {
            if (file === undefined) {
                toastr.error('未选择上传文件!');
                return false;
            }
            const filesize = file.size;
            if (filesize > 30 * 1024 * 1024) {
                toastr.error('文件大小过大!');
                return false;
            }
            const fileext = '.' + file.name.toLowerCase().split('.').splice(-1)[0];
            if (whiteList.indexOf(fileext) === -1) {
                toastr.error('只能上传指定格式的附件!');
                return false;
            }
            formData.append('size', filesize);
            formData.append('file[]', file);
        }
        if (auditList.findIndex(item => item.uid === parseInt(accountId)) === -1) {
            return toastr.error('暂无权限上传!')
        }
        postDataWithFile(window.location.pathname + '/file/upload', formData, function (data) {
            $('#addfujian').modal('hide');
            let html = '';
            let index = $('#attList tr').length + 1;
            for (const fileInfo of data) {
                html += '
 ' +
                    ` | ` +
                    '' + index + ' |  ' +
                    `${fileInfo.filename}${fileInfo.fileext} | `+
                    '' + fileInfo.filesize + ' |  ' +
                    '' + fileInfo.in_time + ' |  ' +
                    ``+
                    ( auditStatus === 4 ?
                        fileInfo.extra_upload ? `` : ''
                        : ` `)+
                    ` | `+
                    // '   |  ' +
                    '
';
                ++index;
            }
            $('#attList').append(html);
        }, function () {
        });
        $('#upload-file').val('');
    });
    // 删除附件
    $('body').on('click', '.delete-file', function () {
        let attid = $(this).data('attid');
        let self = $(this);
        const data = {id: attid};
        postData(window.location.pathname + '/file/delete', data, function (result) {
            self.parents('tr').remove();
            // 重新排序
            let newsort = 1;
            $('#attList tr').each(function(){
                $(this).children('td').eq(1).text(newsort);
                newsort++;
            });
        });
    });
    // /change/download/file/
    $('#attList').on('click', '.file-atn', function() {
        const id = $(this).attr('f-id')
        postData(`/change/download/file/${id}`, {}, (data) => {
            const { filepath } = data
            $('#file-upload').attr('href', filepath)
            $('#file-upload')[0].click()
        })
    })
    $('#attList').on('click', '.check-file', function() {
        const checkedList = $('#attList').find('input:checked')
        const childs = $('#attList').children().length
        const checkBox = $('#check-all-file')
        if (checkedList.length === childs) {
            checkBox.prop("checked", true)
        } else {
            checkBox.prop("checked", false)
        }
    })
    $('#check-all-file').click(function() {
        const isCheck = $(this).is(':checked')
        $('#attList').children().each(function() {
            $(this).find('input:checkbox').prop("checked", isCheck)
        })
    });
    $('#bach-download').click(function() {
        const fileIds = []
        $( '#attList .check-file:checked').each(function() {
            const fileId = $(this).attr('file-id')
            fileId && fileIds.push(fileId)
        })
        if (fileIds.length) {
            const tid = $('#tenderId').val()
            const cid = $('#changeId').val()
            $('#downloadZip').attr('href', `/tender/${tid}/change/${cid}/download/compresse-file?fileIds=${JSON.stringify(fileIds)}`);
            $('#downloadZip')[0].click();
        }
    });
    //
    const cca = getLocalCache('change-checkbox-account-' + accountId);
    if (cca !== null && cca !== undefined) {
        $('#customCheck1').prop('checked', cca !== 'false');
    }
    // 变更详情展示和隐藏
    $('.change-detail-checkbox').on('click', function (e) {
        if($(e.target).is('label')){
            return;
        }
        let column = table.column(3);
        // 设置用户项目本地记录展示和隐藏情况
        setLocalCache('change-checkbox-account-'+ accountId, $(this).is(':checked'));
        column.visible(!column.visible());
    })
    // 重新审批获取手机验证码
    // 获取验证码
    let isPosting = false;
    $("#get-code").click(function() {
        if (isPosting) {
            return false;
        }
        const btn = $(this);
        $.ajax({
            url: '/profile/code?_csrf_j=' + csrf,
            type: 'post',
            data: { mobile: authMobile, type: 'shenpi' },
            dataTye: 'json',
            error: function() {
                isPosting = false;
            },
            beforeSend: function() {
                isPosting = true;
            },
            success: function(response) {
                isPosting = false;
                if (response.err === 0) {
                    codeSuccess(btn);
                    $("input[name='code']").removeAttr('readonly');
                    $("#re-shenpi-btn").removeAttr('disabled');
                } else {
                    toast(response.msg, 'error');
                }
            }
        });
    });
});
/**
 * 获取成功后的操作
 *
 * @param {Object} btn - 点击的按钮
 * @return {void}
 */
function codeSuccess(btn) {
    let counter = 60;
    btn.addClass('disabled').text('重新获取 ' + counter + 'S');
    btn.parent().siblings('input').removeAttr('readonly').attr('placeholder', '输入短信中的6位验证码');
    const bindBtn = $("#bind-btn");
    bindBtn.removeClass('btn-secondary disabled').addClass('btn-primary');
    const countDown = setInterval(function() {
        const countString = counter - 1 <= 0 ? '' : ' ' + (counter - 1) + 'S';
        // 倒数结束后
        if (countString === '') {
            clearInterval(countDown);
            btn.removeClass('disabled');
        }
        const text = '重新获取' + countString;
        btn.text(text);
        counter -= 1;
    }, 1000);
}