/**
 * Created by Zhong on 2017/8/14.
 */
$(function () {
    let dispNameArr;
    let compilationsArr;
    let usedCom;
    let deleteCount = 0;
    let preDeleteId = null;
    let selCompilationId;
    $('#del').on('hidden.bs.modal', function () {
        deleteCount = 0;
    });
    getCompilationList(function (datas) {
        compilationsArr = datas;
        getAllGljLib(function (dispNames, compilationsUsedArr) {
            usedCom = compilationsUsedArr;
            dispNameArr = dispNames;
            //添加
            $('#addBtn').click(function () {
                let compilationName = $('#compilationSels option:selected').text();
                let compilationId = $('#compilationSels option:selected').val();
                let libName = $('#libNameTxt').val();
                if(libName.trim().length === 0){
                    alert('名称不可为空！');
                    $('#libNameTxt').val('')
                }
                else if(compilationsUsedArr.indexOf(compilationId) !== -1){// compilationsUsedArr;//在该编办下已建库，限制一个编办只能有一个库
                    alert('该编办已被绑定！');
                    $('#libNameTxt').val('')
                }
                else if(dispNames.indexOf(libName) !== -1){
                    alert('此人材机库已存在！');
                    $('#libNameTxt').val('')
                }
                else if(compilationName.trim().length === 0){
                    alert('编办不可为空！');
                }
                else{
                    let newGljLib = {};
                    newGljLib.dispName = libName;
                    newGljLib.compilationId = compilationId;
                    newGljLib.compilationName = compilationName;
                    newGljLib.creator = oprtor;
                    newGljLib.appType = "建筑";
                    $('#libNameTxt').val('');
                    createGljLib(newGljLib, dispNameArr, usedCom);
                }
            });

            $('#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 = '#edit']", function(){
                let renameId = $(this).parent().parent().attr("id");
                let compilationName = $(this).parent().parent().children()[1].textContent;
                $('#compilationEdit option').text(compilationName);
                $('#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{
                    renameGljLib({ID: libId, newName: newName, orgName: orgName}, dispNameArr);
                }
            });
            //删除
            $("#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();
                let compilationName = $("#" + deleteId + " td:eq(1)").text();
                if(deleteCount === 3){
                    for(let i = 0, len = compilationsArr.length; i < len; i++){
                        if(compilationsArr[i].name === compilationName.trim()){
                            usedCom.splice(usedCom.indexOf(compilationsArr[i]._id), 1);
                            break;
                        }
                    }
                    removeGljLib({libId: deleteId, libName: libName}, dispNameArr);
                    deleteCount = 0;
                }
            });
            // 锁定、解锁
            $('#showArea').on('click', '.lock', function () {
                lockUtil.handleLockClick($(this));
            });

        });
    });
    let selLibId = -1;
    const importType = {
        price: 1,
        component: 2
    };
    let importAction;
    $("#showArea").on("click", ".import-data", function () {
        importAction = importType.price;
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        selLibId = id;
        $("#import").modal("show");
    });
    $("#showArea").on("click", ".import-components", function () {
        importAction = importType.component;
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        selLibId = id;
        $("#import").modal("show");
    });
    function importExcel(url) {
        $.bootstrapLoading.start();
        const self = $(this);
        console.log(self);
        try {
            let formData = new FormData();
            let file = $("input[name='import_data']")[0];
            if (file.files.length <= 0) {
                throw '请选择文件!';
            }
            formData.append('file', file.files[0]);
            // 获取人材机库id
            if (selLibId <= 0) {
                return false;
            }
            formData.append('gljLibId', selLibId);
            $.ajax({
                url: url,
                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);
                        }
                        // 成功则关闭窗体
                        $('#import').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);
            $.bootstrapLoading.end();
        }
    }
    $("#data-import").click(function () {
        // 导入单价
        if (importAction === importType.price) {
            importExcel.call(this, '/stdGljRepository/api/importPrice');
        } else {
            // 导入组成物
            importExcel.call(this, '/stdGljRepository/api/importComponents');
        }
    });
    //设置补充人材机库分类树模板
    $("#showArea").on("click", ".set-comple", function () {
        let id = $(this).data("id");
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }
        selLibId = 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(`api/classTemplateCount/${selCompilationId}`, function (rstData) {
            rstData.data.count > 0 ?
                $('#templateText').text('该费用定额下已有人材机分类树模板数据，是否确认覆盖数据？') :
                $('#templateText').text('确认是否将此库的分类树设置成该费用定额下补充人材机分类树模板？');
            $('#templateA').removeClass('disabled');
        });
    });
    $('#templateA').click(function () {
        if (selLibId <= 0 && selCompilationId) {
            return false;
        }
        $.bootstrapLoading.start();
        CommonAjax.post('api/initClassTemplate', {gljLibId: selLibId, compilationId: selCompilationId}, function () {
            $.bootstrapLoading.end();
            $('#template').modal('hide');
        }, function () {
            $.bootstrapLoading.end();
            $('#template').modal('hide');
        });
    });
});

function getAllGljLib(callback){
    $.ajax({
        type: 'post',
        url: 'api/getAllGljLib',
        dataType: 'json',
        success: function (result) {
            let dispNames = [];
            let compilationsUsedArr = [];
            if(result.data.length > 0){
                for(let i = 0; i < result.data.length; i++){
                    compilationsUsedArr.push(result.data[i].compilationId);//已建库的编办
                    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;
                    let compilationId = result.data[i].compilationId;
                    let rationLibs = result.data[i].rationLibs;
                    let rationLibsName = '';
                    for(let j = 0; j < rationLibs.length; j++){
                        rationLibsName += rationLibs[j].dispName + "</br>";
                    }
                    dispNames.push(result.data[i].dispName);
                    $("#showArea").append(
                        "<tr id='"+id+"' data-compilationId='"+ compilationId + "'>" +
                        "<td><a href='/stdGljRepository/glj?gljLibId="+id+"&locked=true'>"+libName+"</a></td>" +
                        "<td>"+compilationName+" </td>" +
                        "<td>"+rationLibsName+" </td>" +
                        "<td>"+createDate+" </td>" +
                        "<td><a class='lock-btn-control disabled' 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 lock-btn-control disabled' title='删除'>" +
                        "<i class='fa fa-remove'></i></a> " +
                        "<a class='lock' data-locked='true' href='javascript:void(0);' title='解锁'><i class='fa fa-unlock-alt'></i></a>" +
                        "</td>" +
                        "<td><a class='btn btn-secondary btn-sm import-data lock-btn-control disabled' 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-secondary btn-sm import-components lock-btn-control disabled' 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-secondary btn-sm set-comple lock-btn-control disabled' href='javacript:void(0);' data-id='"+ id +"' title='将分类树设为补充模板数据'><i class='fa fa-sign-in fa-rotate-90'></i>设置</a></td>" +
                        "</tr>");
                }
            }
            callback(dispNames, compilationsUsedArr);
        }
    });
}
function getCompilationList(callback){
    $.ajax({
        type: 'post',
        url: 'api/getCompilationList',
        dataType: 'json',
        success: function (result) {
            //addoptions
            for(let i = 0; i < result.data.length; i++){
                let $option =  $("<option >"+ result.data[i].name +"</option>");
                $option.val( result.data[i]._id);
                $('#compilationSels').append($option);
            }
            $('#compilationSels').on("change", function () {
            });
            callback(result.data);
        }
    });
}
function createGljLib(gljLibObj, dispNamesArr, usedCom){
    $.ajax({
        type: 'post',
        url: 'api/createGljLib',
        data: {gljLibObj: JSON.stringify(gljLibObj)},
        dataType: 'json',
        success: function (result) {
            if(result.data){
                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);
                usedCom.push(gljLibObj.compilationId);
                $("#showArea").append(
                    "<tr id='"+id+"' data-compilationId='"+ gljLibObj.compilationId + "'>" +
                    "<td><a href='/stdGljRepository/glj?gljLibId="+id+"&locked=true'>"+libName+"</a></td>" +
                    "<td>"+compilationName+" </td>" +
                    "<td>"+''+" </td>" +
                    "<td>"+createDate+" </td>" +
                    "<td><a class='lock-btn-control disabled' 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 lock-btn-control disabled' title='删除'>" +
                    "<i class='fa fa-remove'></i></a>" +
                    "<a class='lock' data-locked='true' href='javascript:void(0);' title='解锁'><i class='fa fa-unlock-alt'></i></a>" +
                    "</td>" +
                    "<td><a class='btn btn-secondary btn-sm import-data lock-btn-control disabled' 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-secondary btn-sm import-components lock-btn-control disabled' 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-secondary btn-sm set-comple lock-btn-control disabled' href='javacript:void(0);' data-id='"+ id +"' title='将分类树设为补充模板数据'><i class='fa fa-sign-in fa-rotate-90'></i>设置</a></td>" +
                    "</tr>");
            }
            $('#cancelBtn').click();
        }
    })
}
function renameGljLib(renameObj, dispNames){
    $.ajax({
        type: 'post',
        url: 'api/renameGljLib',
        data: {oprtor: oprtor, 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 removeGljLib(delObj, dispNames){
    $.bootstrapLoading.start();
    $.ajax({
        type: 'post',
        url: 'api/removeGljLib',
        data: {oprtor: oprtor, libId: delObj.libId},
        dataType: 'json',
        success: function (result) {
            if(!result.error){
                if(result.message === '此人材机库已被引用！'){
                    $('#delCancelBtn').click();
                    alert("此人材机库已被引用，不可删除！");
                }
                else if(result.message === '删除成功'){
                    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();
        }
    })

}