/**
 * Created by Syusuke on 2017/3/17.
 */

$(function () {
    let dispNameArr;
    let preDeleteId = null;
    let deleteCount = 0;
    $('#del').on('hidden.bs.modal', function () {
        deleteCount = 0;
    });
    getAllRationLib(function (dispNames) {
        dispNameArr = dispNames;
        //添加
        $('#addBtn').click(function () {
            let compilationName = $('#compilationSels option:selected').text();
            let compilationId = $('#compilationSels option:selected').val();
            let gljLibName = $('#gljLibSels option:selected').text();
            let gljLibId = $('#gljLibSels option:selected').val();
            let libName = $('#libNameTxt').val();
            if(libName.trim().length === 0){
                alert('名称不可为空！');
                $('#libNameTxt').val('')
            }
            else if(dispNames.indexOf(libName) !== -1){
                alert('此定额库已存在！');
                $('#libNameTxt').val('')
            }
            else if(compilationName.trim().length === 0){
                alert('编办不可为空！');
            }
            else if(gljLibName.trim().length === 0){
                alert("请选择工料机库！");
            }
            else{
                let newRationLib = {};
                newRationLib.dispName = libName;
                newRationLib.compilationId = compilationId;
                newRationLib.compilationName = compilationName;
                newRationLib.gljLib = gljLibId;
                newRationLib.creator = userAccount;
                newRationLib.appType = "建筑";
                $('#libNameTxt').val('');
                createRationLib(newRationLib, dispNameArr);
            }
        });
        //重命名
        $("#showArea").on("click", "[data-target = '#edit']", function(){
            let renameId = $(this).parent().parent().attr("id");
            $('#renameText').val($(this).parent().parent().find('td:first-child').text());
            $("#renameA").attr("renameId", renameId);
        });
        $("#renameA").click(function(){
            let newName = $("#renameText").val();
            let libId = $(this).attr("renameId");
            let jqSel = "#" + libId + " td:first" + " a";
            let orgName = $(jqSel).text();
            if(newName.trim().length === 0){
                alert("名称不可为空！");
                $("#renameText").val('');
            }
            else if(dispNameArr.indexOf(newName) !== -1){
                alert("该定额库已存在！");
                $("#renameText").val('');
            }
            else{
                renameRationLib({ID: libId, newName: newName, orgName: orgName}, dispNameArr);
            }
        });
        $('#edit').on('shown.bs.modal', function () {
            setTimeout(function () {
                $('#renameText').focus();
            }, 100);
        });

        $('#add').on('shown.bs.modal', function () {
            setTimeout(function () {
                $('#libNameTxt').focus();
            }, 100);
        });
        $('#add').on('hidden.bs.modal', function () {
            $('#libNameTxt').val('');
        });
        //删除
        $("#showArea").on("click", "[data-target = '#del']", function(){
            let deleteId = $(this).parent().parent().attr("id");
            $("#deleteA").attr("deleteId", deleteId);
        });
        $("#deleteA").click(function(){
            let deleteId = $(this).attr("deleteId");
            if(preDeleteId && preDeleteId !== deleteId){
                deleteCount = 0;
            }
            preDeleteId = deleteId;
            deleteCount++;
            let jqSel = "#" + deleteId + " td:first" + " a";
            let libName = $(jqSel).text();
            if(deleteCount === 3){
                deleteCount = 0;
                removeRationLib({libId: deleteId, libName: libName}, dispNameArr);
                $('#del').modal('hide');
            }
        });


    });
    getCompilationList();

    // 导入原始数据按钮
    let rationRepId = 0;
    $("#showArea").on("click", ".import-source", function () {
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        rationRepId = id;
        $("#import").modal("show");
    });
    // 导入内部数据
    $("#showArea").on("click", ".import-data", function () {
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        rationRepId = id;
        $("#import2").modal("show");
    });

    // 导入原始数据确认
    $("#source-import,#data-import").click(function() {
        const self = $(this);
        const type = self.is("#source-import") ? 'source_file' : 'import_data';
        const dialog = type === 'source_file' ? $("#import") : $("#import2");
        try {
            let formData = new FormData();
            let file = $("input[name='"+ type +"']")[0];
            if (file.files.length <= 0) {
                throw '请选择文件!';
            }
            formData.append('file', file.files[0]);
            // 获取定额库id
            if (rationRepId <= 0) {
                return false;
            }
            formData.append('rationRepId', rationRepId);
            formData.append('type', type);
            $.ajax({
                url: '/rationRepository/api/upload',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    self.attr('disabled', 'disabled');
                    self.text('上传中...');
                },
                success: function(response){
                    self.removeAttr('disabled');
                    self.text('确定导入');
                    if (response.err === 0) {
                        const message = response.msg !== undefined ? response.msg : '';
                        if (message !== '') {
                            alert(message);
                        }
                        // 成功则关闭窗体
                        dialog.modal("hide");
                    } else {
                        const message = response.msg !== undefined ? response.msg : '上传失败!';
                        alert(message);
                    }
                },
                error: function(){
                    alert("与服务器通信发生错误");
                    self.removeAttr('disabled');
                    self.text('确定导入');
                }
            });
        } catch(error) {
            alert(error);
        }
    });

    // 导出数据
    $("#showArea").on("click", ".export", function () {
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        window.location.href = '/rationRepository/api/export?rationRepId=' + id;
    });
});

function getAllRationLib(callback){
    $.ajax({
        type: 'post',
        url: 'api/getRationDisplayNames',
        dataType: 'json',
        success: function (result) {
            let dispNames = [];
            if(result.data.length > 0){
                for(let i = 0; i < result.data.length; i++){
                    storageUtil.setSessionCache("RationGrp","repositoryID_" + result.data[i].ID, result.data[i].dispName);
                    if(result.data[i].gljLib){
                        storageUtil.setSessionCache("gljLib","repositoryID_" + result.data[i].ID, result.data[i].gljLib);
                    }
                    let id = result.data[i].ID;
                    let libName = result.data[i].dispName;
                    let createDate = result.data[i].createDate.split(' ')[0];
                    let compilationName = result.data[i].compilationName;
                    dispNames.push(result.data[i].dispName);
                    $("#showArea").append(
                        "<tr id='tempId'>" +
                        "<td><a href='/stdGljRepository/glj'>"+libName+"</a></td>" +
                        "<td>"+compilationName+" </td>" +
                        "<td>"+createDate+" </td>" +
                        "<td><a href='javascript:void(0);' data-toggle='modal' data-target='#edit' title='编辑'>" +
                        "<i class='fa fa-pencil-square-o'></i></a> <a href='javascript:void(0);' data-toggle='modal' data-target='#del' class='text-danger' title='删除'>" +
                        "<i class='fa fa-remove'></i></a></td>" +
                        "<td><a class='btn btn-secondary btn-sm import-source' href='javacript:void(0);' data-id='"+ id +"' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                        "<td><a class='btn btn-success btn-sm export' href='javacript:void(0);' data-toggle='modal' data-id='"+ id +"' data-target='#emport' title='导出内部数据'><i class='fa fa-sign-out fa-rotate-270'></i>导出</a> " +
                        "<a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入内部数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                        "</tr>");
                    var newHref = "/rationRepository/ration?repository="+id;
                    $("#tempId td:first a").attr("href", newHref);
                    $("#tempId").attr("id", id);
                }
            }
            callback(dispNames);
        }
    });
}
function getCompilationList(){
    $.ajax({
        type: 'post',
        url: 'api/getCompilationList',
        dataType: 'json',
        success: function (result) {
            console.log(result);
            //addoptions
            for(let i = 0; i < result.data.compilation.length; i++){
                let $option =  $("<option >"+ result.data.compilation[i].name +"</option>");
                $option.val( result.data.compilation[i]._id);
                $('#compilationSels').append($option);
            }
            //初始工料机库选项
            if(result.data.compilation.length > 0 && result.data.gljLibs.length > 0){
                let compilationId = result.data.compilation[0]._id;
                //console.log(compilationId);
                let gljLibOps = getGljLibOps(compilationId, result.data.gljLibs);
                console.log(gljLibOps);
                for(let i = 0; i < gljLibOps.length; i++){
                    let $option =  $("<option >"+ gljLibOps[i].dispName +"</option>");
                    $option.val(gljLibOps[i].ID);
                    $('#gljLibSels').append($option);
                }

            }
            $('#compilationSels').on("change", function () {
                //刷新工料机库选项
                $('#gljLibSels').children().remove();
                let newGljLibOps = getGljLibOps(this.selectedOptions[0].value, result.data.gljLibs);
                for(let i = 0; i < newGljLibOps.length; i++){
                    let $option =  $("<option >"+ newGljLibOps[i].dispName +"</option>");
                    $option.val(newGljLibOps[i].ID);
                    $('#gljLibSels').append($option);
                }
            });
        }
    });
}
function getGljLibOps(compilationId, gljLibs){
    let rst = [];
    for(let i = 0; i < gljLibs.length; i++){
        if(gljLibs[i]){
            if(compilationId === gljLibs[i].compilationId){
                rst.push(gljLibs[i]);
            }
        }
    }
    return rst;
}

function createRationLib(rationObj, dispNamesArr){
    $.ajax({
        type: 'post',
        url: 'api/addRationRepository',
        data: {rationRepObj: JSON.stringify(rationObj)},
        dataType: 'json',
        success: function (result) {
            if(result.data){
                storageUtil.setSessionCache("RationGrp","repositoryID_" + result.data.ID, result.data.dispName);
                if(result.data.gljLib){
                    storageUtil.setSessionCache("gljLib","repositoryID_" + result.data.ID, result.data.gljLib);
                }
                let id = result.data.ID;
                let libName = result.data.dispName;
                let createDate = result.data.createDate.split(' ')[0];
                let compilationName = result.data.compilationName;
                dispNamesArr.push(libName);
                $("#showArea").append(
                    "<tr id='tempId'>" +
                    "<td><a href='/stdGljRepository/glj'>"+libName+"</a></td>" +
                    "<td>"+compilationName+" </td>" +
                    "<td>"+createDate+" </td>" +
                    "<td><a href='javascript:void(0);' data-toggle='modal' data-target='#edit' title='编辑'>" +
                    "<i class='fa fa-pencil-square-o'></i></a> <a href='javascript:void(0);' data-toggle='modal' data-target='#del' class='text-danger' title='删除'>" +
                    "<i class='fa fa-remove'></i></a>" +
                    "<td><a class='btn btn-secondary btn-sm import-source' href='javacript:void(0);' data-id='"+ id +"' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                    "<td><a class='btn btn-success btn-sm export' href='javacript:void(0);' data-toggle='modal' data-id='"+ id +"' data-target='#emport' title='导出内部数据'><i class='fa fa-sign-out fa-rotate-270'></i>导出</a> " +
                    "<a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入内部数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                    "</tr>");
                var newHref = "/rationRepository/ration?repository="+id;
                $("#tempId td:first a").attr("href", newHref);
                $("#tempId").attr("id", id);
            }
            $('#cancelBtn').click();
        }
    })
}
function renameRationLib(renameObj, dispNames){
    $.ajax({
        type: 'post',
        url: 'api/editRationLibs',
        data: {oprtor: userAccount, renameObj: JSON.stringify(renameObj)},
        dataType: 'json',
        success: function (result) {
            if(!result.error){
                let jqSel = "#" + renameObj.ID + " td:first" + " a";
                $(jqSel).text(renameObj.newName);
                let index = dispNames.indexOf(renameObj.orgName);
                dispNames.splice(index, 1);
                dispNames.splice(index, 0, renameObj.newName);
            }
            $('#editCancelBtn').click();
            $('#renameText').val('');
        }
    })
}
function removeRationLib(delObj, dispNames){
    $.bootstrapLoading.start();
    $.ajax({
        type: 'post',
        url: 'api/deleteRationLibs',
        data: {oprtor: userAccount, libId: delObj.libId},
        dataType: 'json',
        success: function (result) {
            if(!result.error){
                var jqSel = "#"+ delObj.libId;
                $(jqSel).remove();
                let index = dispNames.indexOf(delObj.libName);
                dispNames.splice(index, 1);
                $('#delCancelBtn').click();
            }
            $.bootstrapLoading.end();
        },
        error: function () {
            alert('删除失败');
            $.bootstrapLoading.end();
        }
    })
}
