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

$(function () {
    let preDeleteId = null;
    let deleteCount = 0;
    let selCompilationId,
        compilationsArr = [];
    $('#del').on('hidden.bs.modal', function () {
        deleteCount = 0;
    });
    //添加
    $('#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();
        let libCode = $('#libCode').val().trim();
        if(libName.trim().length === 0){
            alert('名称不可为空！');
            $('#libNameTxt').val('')
        } else if (!libCode) {
            alert('定额库编码不可为空');
            $('#libCode').val('');
        } else if(allNames.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.libCode = libCode; //定额编号，标准数据导出xml需要
            newRationLib.compilationId = compilationId;
            newRationLib.compilationName = compilationName;
            newRationLib.gljLib = gljLibId;
            newRationLib.creator = userAccount;
            newRationLib.appType = "建筑";
            $('#libNameTxt').val('');
            createRationLib(newRationLib);
        }
    });
    //重命名
    $("#showArea").on("click", "[data-target = '#edit']", function(){
        let renameId = $(this).parent().parent().attr("id");
        $('#renameText').val($(this).parent().parent().find('td:first-child').text());
        $('#renameCode').val($(this).parent().parent().find('td:eq(1)').text());
        $("#renameA").attr("renameId", renameId);
    });
    $("#renameA").click(function(){
        let newName = $("#renameText").val();
        let newLibCode = $('#renameCode').val().trim();
        let libId = $(this).attr("renameId");
        let jqSel = "#" + libId + " td:first" + " a";
        let orgName = $(jqSel).text();
        let filterName = allNames.filter(function (v) {
            return v === newName;
        });
        if(newName.trim().length === 0){
            alert("名称不可为空！");
            $("#renameText").val('');
        } else if (!newLibCode) {
            alert('定额库编码不可为空！');
            $('#renameCode').val('');
        } else if(filterName.length > 0 && newName !== orgName){
            alert("该定额库已存在！");
            $("#renameText").val('');
        } else{
            renameRationLib({ID: libId, newName: newName, orgName: orgName, newLibCode: newLibCode});
        }
    });
    $('#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);
        let delLibName = $(`#${deleteId}`).find('td:first').text();
        $('#del').find('.modal-body h5').text(`准备删除 “${delLibName}”，会导致已引用此库的地方出错，确定要删除吗？`);
    });
    $("#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});
            $('#del').modal('hide');
        }
    });
    //全部计算
    $("#showArea").on("click", "[data-target = '#reCalcAll']", function(){
        let recalcId = $(this).parent().parent().attr("id");
        $("#reCalcConfirm").attr("recalcId", recalcId);
    });
    $("#reCalcConfirm").click(function(){
        $('#reCalcConfirm').addClass('disabled');
        $.bootstrapLoading.start();
        let recalcId = $(this).attr("recalcId");
        CommonAjax.post('/rationRepository/api/reCalcAll', {rationRepId: recalcId}, function (rstData) {
            $.bootstrapLoading.end();
            $('#reCalcAll').modal('hide');
            $('#reCalcConfirm').removeClass('disabled');
        }, function () {
            $.bootstrapLoading.end();
            $('#reCalcAll').modal('hide');
            $('#reCalcConfirm').removeClass('disabled')
        });
    });
    // 锁定、解锁
    $('#showArea').on('click', '.lock', function () {
        lockUtil.handleLockClick($(this));
    });
    getCompilationList(function (data) {
        compilationsArr = data.compilation;
    });

    // 导入原始数据按钮
    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");
    });
    // 导入章节数据
    $('#showArea').on('click', '.import-section', function () {
        let id = $(this).data('id');
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        rationRepId = id;
    });

    // 导入原始数据确认
    $("#source-import,#data-import").click(function() {
        $.bootstrapLoading.start();
        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) {
                        $.bootstrapLoading.end();
                        const message = response.msg !== undefined ? response.msg : '';
                        if (message !== '') {
                            alert(message);
                        }
                        // 成功则关闭窗体
                        dialog.modal("hide");
                    } else {
                        $.bootstrapLoading.end();
                        const message = response.msg !== undefined ? response.msg : '上传失败!';
                        alert(message);
                    }
                },
                error: function(){
                    $.bootstrapLoading.end();
                    alert("与服务器通信发生错误");
                    self.removeAttr('disabled');
                    self.text('确定导入');
                }
            });
        } catch(error) {
            alert(error);
        }
    });
    // 导入章节数据确认
    $('#import-section-confirm').click(function() {
        $.bootstrapLoading.start();
        const self = $(this);
        const dialog = $('#section');
        try {
            const formData = new FormData();
            const file = $('input[name=section_file]')[0];
            if (file.files.length <= 0) {
                throw '请选择文件!';
            }
            formData.append('file', file.files[0]);
            formData.append('type', 'section_file');
            // 获取定额库id
            if (rationRepId <= 0) {
                return false;
            }
            formData.append('rationRepId', rationRepId);
            $.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) {
                        $.bootstrapLoading.end();
                        const message = response.msg !== undefined ? response.msg : '';
                        if (message !== '') {
                            alert(message);
                        }
                        // 成功则关闭窗体
                        dialog.modal("hide");
                    } else {
                        $.bootstrapLoading.end();
                        const message = response.msg !== undefined ? response.msg : '上传失败!';
                        alert(message);
                    }
                },
                error: function(){
                    $.bootstrapLoading.end();
                    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;
    });

    //设置补充定额库章节树模板
    $("#showArea").on("click", ".set-comple", function () {
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        rationRepId = id;
        $('#templateA').addClass('disabled');
        $('#template').modal('show');
        $('#compilations').empty();
        for (let data of compilationsArr) {
            let $opt = $(`<option value="${data._id}">${data.name}</option>`);
            $('#compilations').append($opt);
        }
        $('#compilations').change();
    });
    $('#compilations').change(function () {
        selCompilationId = $(this).select().val();
        CommonAjax.get(`/rationRepository/api/sectionTemplateCount/${selCompilationId}`, function (rstData) {
            rstData.data.count > 0 ?
                $('#templateText').text('该费用定额下已有定额章节树模板数据，是否确认覆盖数据？') :
                $('#templateText').text('确认是否将此库的章节树设置成该费用定额下补充定额章节树模板？');
            $('#templateA').removeClass('disabled');
        });
    });
    $('#templateA').click(function () {
        if (rationRepId <= 0 && selCompilationId) {
            return false;
        }
        $.bootstrapLoading.start();
        CommonAjax.post('/rationRepository/api/initSectionTemplate', {rationLibId: rationRepId, compilationId: selCompilationId}, function () {
            $.bootstrapLoading.end();
            $('#template').modal('hide');
        }, function () {
            $.bootstrapLoading.end();
            $('#template').modal('hide');
        });
    });
});

function getCompilationList(callback){
    $.ajax({
        type: 'post',
        url: '/rationRepository/api/getCompilationList',
        dataType: 'json',
        success: function (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);
                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);
                }
            });
            callback(result.data);
        }
    });
}
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){
    $.ajax({
        type: 'post',
        url: '/rationRepository/api/addRationRepository',
        data: {rationRepObj: JSON.stringify(rationObj)},
        dataType: 'json',
        success: function (result) {
            window.location.href = location.href;
            $('#cancelBtn').click();
        }
    })
}
function renameRationLib(renameObj){
    $.ajax({
        type: 'post',
        url: '/rationRepository/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);
                $(`#${renameObj.ID} td:eq(1)`).text(renameObj.newLibCode);
                let index = allNames.indexOf(renameObj.orgName);
                allNames.splice(index, 1);
                allNames.splice(index, 0, renameObj.newName);
            }
            $('#editCancelBtn').click();
            $('#renameText').val('');
            $('#renameCode').val('');
        }
    })
}
function removeRationLib(delObj){
    $.bootstrapLoading.start();
    $.ajax({
        type: 'post',
        url: '/rationRepository/api/deleteRationLibs',
        data: {oprtor: userAccount, libId: delObj.libId},
        dataType: 'json',
        success: function (result) {
            if(!result.error){
                var jqSel = "#"+ delObj.libId;
                $(jqSel).remove();
                let index = allNames.indexOf(delObj.libName);
                allNames.splice(index, 1);
                $('#delCancelBtn').click();
            }
            $.bootstrapLoading.end();
        },
        error: function () {
            alert('删除失败');
            $.bootstrapLoading.end();
        }
    })
}
