/**
 * <p>
 *  文件上传
 * </p>
 *
 * @author Administrator
 * @since 2021/6/7
 */
let fileMap = new Map();
let saveResult = {
    done: false,
    success: false,
    data: null
};
layui.use(['layer', 'uploader', 'element', 'form', 'laydate', 'dict', 'datalabel'], function () {
    let form = layui.form,
        laydate = layui.laydate;

    let param = layui.url().search || {};
    bindDatetimePlugins();

    let uploader = layui.uploader.render({
        url: `${ctx}/sys/file/upload/chunk`,//上传文件服务器地址，必填
        fileCheckUrl: `${ctx}/sys/file/upload/check`,//文件校验地址
        fileMergeUrl: `/sys/file/upload/chunk/complete`,
        fileBoxEle: "#uploader-table",//上传容器
        multiple: true,
        dirUpload: param.dirUpload,
        getFormData: getFormVal,
        uploadFinished: function (ok) {
            if (ok) {
                saveResult.done = true;
                saveResult.success = true;
                //let index = parent.layer.getFrameIndex(window.name);
                parent.layer.msg('上传成功');
                layerOkCallback && layerOkCallback(saveResult);
                closeWindow()
            } else {
                layerCancelCallback && layerCancelCallback(saveResult);
                showErrorMsg("上传失败");
                $('#fileUploadAction').removeClass('layui-disabled').removeAttr('disabled')
            }
        }
    });

    $('#fileUploadAction').on('click', function () {
        let json = getFormVal();
        if (!json['secretLevel']) {
            showErrorMsg("请选择文件密级");
            return false;
        }
        if(json['secretLevel'] > param.secretLevel){
            layer.alert('禁止上传超过当前目录数据密级的文件，当前目录的密级为【'+ DICT.getText('secret_level', param.secretLevel) +'】', {icon:2})
            return false;
        }
        if(json['secretLevel'] > user.secretLevel){
            layer.alert('禁止上传超过自身涉密等级的文件，您的涉密等级为【'+ DICT.getText('secret_level', user.secretLevel) +'】', {icon:2})
            return false;
        }
        if (json.exerciseData === '1') {
            if (uploader.getFiles().length <= 0) {
                showErrorMsg("还没有选择文件");
                return false;
            }
            if (!json['inputDate']) {
                showErrorMsg('任务时间不能为空');
                return false;
            }
            if (!json['source']) {
                showErrorMsg('文件来源不能为空')
                return false;
            }
            if (!json['taskCode']) {
                showErrorMsg('任务代号不能为空')
                return false;
            }
            if (!json['taskNature']) {
                showErrorMsg('任务性质不能为空')
                return false;
            }
            if (!json['troopCode']) {
                showErrorMsg('部队代号不能为空')
                return false;
            }
            if (!json['equipmentModel']) {
                showErrorMsg('装备型号不能为空')
                return false;
            }

        }
        $('#fileUploadAction').addClass('layui-disabled').attr('disabled', 'true')
        uploader.uploadToServer();
    });

    if (window.layerCancelCallback) {
        $('#cancelBtn').show().on('click', closeWindow);
    }

    function closeWindow() {
        window.layerCancelCallback && window.layerCancelCallback();
    }

    function renderRequiredItem() {
        let formVal = form.val('file-form');
        if (formVal.exerciseData === '1') {
            $('.star-mark').show();
        } else {
            $('.star-mark').hide();
        }
    }

    form.on('radio(exerciseData)', renderRequiredItem);
    setTimeout(renderRequiredItem, 50);

    /**
     * 获取form表单数据
     * @returns {*}
     */
    function getFormVal() {
        let formVal = form.val('file-form');
        formVal.entityId = param.directoryId;
        formVal.inputDate = formVal.inputDate ? formVal.inputDate + '.000' : '';
        // 置标标签数据
        formVal.labelStr = JSON.stringify(layui.datalabel.getData(formVal.id, 'file'));
        return formVal;
    }


    /**
     * 绑定日期时间插件
     */
    function bindDatetimePlugins() {
        //日期选择器
        laydate.render({
            elem: 'input[name="inputDate"]',
            format: "yyyy-MM-dd HH:mm:ss",
            type: 'datetime',
            value: new Date(),
            isInitValue: true,
        });
    }
});

function save() {
    $('#fileUploadAction').click();
    return getSaveStatus();
}

/**
 * 每隔100毫秒获取表单保存进度，如果保存请求完成则返回保存状态
 * @returns {Promise<boolean|boolean|*>}
 */
async function getSaveStatus() {
    await commonUtil.sleep(100);
    if (saveResult.done) {
        return saveResult;
    }
    return getSaveStatus();

}
