'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/5/29
 * @version
 */

const billsGuidanceMain = (function () {
    const updateType = {create: 'create', update: 'update', delete: 'delete'};
    const typeString = {1: '清单指引', 2: '清单精灵'};
    let guidanceLibs = [];
    let curLib = null;
    //上一个选择的库（三次确认删除同一库时用）
    let preLib = null;
    let deleteCount = 0;

    //获取编办及编办下清单库
    //@return {void}
    function getComBillsLibInfo(){
        CommonAjax.post('/billsGuidance/api/getComBillsLibInfo', {}, function (rstData) {
            const comSels = $('#comSels');
            const billsLibSels = $('#billsLibSels');
            //设置编办及清单规则库选择
            comSels.empty();
            function setBillsLib(libs){
                billsLibSels.empty();
                for(let lib of libs){
                    let libOpt = `<option value="${lib.billsLibId}">${lib.billsLibName}</option>`;
                    billsLibSels.append(libOpt);
                }
            }
            setBillsLib(rstData.billsLibs);
            for(let i = 0; i < rstData.compilationList.length; i++){
                let compilation = rstData.compilationList[i];
                let comOpt = `<option value = "${compilation._id}">${compilation.name}</option>`;
                comSels.append(comOpt);
            }
        });
    }
    //html新增库
    //@param {Object}tbody {Object}lib @return {void}
    function addLibToView(tbody, lib){
        let type = lib.type && typeString[lib.type] ? typeString[lib.type] : ''
        let tr = `<tr id="${lib.ID}">
            <td><a href="/billsGuidance/guidance/?libID=${lib.ID}&locked=true">${lib.name}</a>
            <td>${lib.compilationName}</td>
            <td>${lib.billsLibName}</td>
            <td>${type}</td>
            <td>${lib.createDate.split(' ')[0]}</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 class="lock-btn-control disabled text-danger" href="javascript:void(0);" data-toggle="modal" data-target="#del" 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></tr>`;
        tbody.append(tr);
    }
    //获取清单指引库
    //@return {void}
    function getLibs(){
        CommonAjax.post('/billsGuidance/api/getBillsGuideLibs', {}, function (rstData) {
            guidanceLibs = rstData;
            const tbody = $('.main').find('tbody');
            tbody.empty();
            for(let lib of rstData){
                addLibToView(tbody, lib);
            }
        });
    }
    //是否已存在此库
    //@param {Object}findSet {Array}libs @return {Object}
    function existLib(findSet, libs) {
        for(let lib of libs){
            if(lib[findSet.k] === findSet.v){
                return lib;
            }
        }
        return null;
    }
    //监听事件
    //@return {void}
    function eventListener(){
        //新建库确认按钮事件
        $('#addY').click(function () {
            try{
                let cName = $('#createName').val();
                if(!cName || cName.trim() === ''){
                    throw '请输入名称!';
                }
                if(existLib({k: 'name', v: cName}, guidanceLibs)){
                    throw '已存在此库!';
                }
                let compilationId = $('#comSels').select().val();
                let compilationName = $('#comSels').select().children('option:selected').text();
                if(!compilationId){
                    throw '请选择编办!';
                }
                let billsLibId = $('#billsLibSels').select().val();
                let billsLibName = $('#billsLibSels').select().children('option:selected').text();
                if(!billsLibId){
                    throw '请选择清单规则库';
                }
                //库类型
                let addType = $('#add').find('input:checked');
                if(!addType){
                    throw '请选择库类型';
                }
                //新建
                $.bootstrapLoading.start();
                $('#addY').addClass('disabled');
                let createData = {type: parseInt(addType.val()), ID: uuid.v1(), name: cName, compilationId: compilationId, compilationName: compilationName, billsLibId: parseInt(billsLibId), billsLibName:billsLibName};
                let updateData = {updateType: updateType.create, updateData: createData};
                CommonAjax.post('/billsGuidance/api/updateBillsGuideLib', updateData, function (rstData) {
                    guidanceLibs.push(rstData);
                    addLibToView($('.main').find('tbody'), rstData);
                    $('#add').modal('hide');
                    $('#addY').removeClass('disabled');
                    $.bootstrapLoading.end();
                }, function () {
                    $('#addY').removeClass('disabled');
                    $.bootstrapLoading.end();
                });
            }
            catch(err){
                alert(err);
                $('#createName').focus();
            }
        });
        //新建模态框
        $('#add').on('hidden.bs.modal', function () {
           $('#createName').val('');
        });
        $('#add').on('shown.bs.modal', function () {
            $('#createName').focus();
        });
        //所有编辑按钮
        $('.main').find('tbody').on('click', '[data-target="#edit"]', function () {
            let tr = $(this).parent().parent();
            let selLib = existLib({k: 'ID', v: tr.attr('id')}, guidanceLibs);
            curLib = selLib;
            $('#edName').val(curLib.name);
            $('#edComSels').select().children('option:selected').text(curLib.compilationName);
            $('#edBillsLibSels').select().children('option:selected').text(curLib.billsLibName);
        });
        //编辑确认
        $('#editY').click(function(){
            try{
                let newName = $('#edName').val();
                if(newName.trim() === curLib.name){
                    $('#edit').modal('hide');
                    return;
                }
                if(!newName || newName.trim() === ''){
                    throw '名称不能为空!';
                }
                if(existLib({k: 'name', v: newName}, guidanceLibs)){
                    throw '该库已存在！';
                }
                let updateData = {updateType: updateType.update, findData: {ID: curLib.ID}, updateData: {name: newName}};
                CommonAjax.post('/billsGuidance/api/updateBillsGuideLib', updateData, function (rstData) {
                    curLib.name = newName;
                    $(`#${curLib.ID} td:first a`).text(newName);
                    $('#edit').modal('hide');
                });
            }
            catch(err){
                alert(err);
                $('#edName').focus();
            }
        });
        //编辑模态框
        $('#edit').on('shown.bs.modal', function () {
            $('#edName').focus();
        });
        //所有删除按钮
        $('.main').find('tbody').on('click', '[data-target="#del"]', function () {
            let tr = $(this).parent().parent();
            curLib = existLib({k: 'ID', v: tr.attr('id')}, guidanceLibs);
            console.log(curLib);
        });
        //删除确认
        $('#delY').click(function () {
            try{
                if(!curLib){
                    throw '不存在该库！';
                }
                if(preLib && preLib.ID !== curLib.ID){
                    deleteCount = 0;
                }
                deleteCount++;
                preLib = curLib;
                if(deleteCount === 3){
                    $('#del').modal('hide');
                    $.bootstrapLoading.start();
                    let updateData = {updateType: updateType.delete, findData: {ID: curLib.ID}, updateData: {deleted: true}};
                    CommonAjax.post('/billsGuidance/api/updateBillsGuideLib', updateData, function (rstData) {
                        $(`#${curLib.ID}`).remove();
                        curLib = null;
                        _.remove(guidanceLibs, function (lib) {
                            return lib.ID === updateData.findData.ID;
                        });
                        $.bootstrapLoading.end();
                    }, function () {
                        $.bootstrapLoading.end();
                    });
                }
            }
            catch(err){
                alert(err);
            }
        });
        //删除确认窗口关闭，重新计数
        $('#del').on('hidden.bs.modal', function () {
            deleteCount = 0;
        });
        // 锁定、解锁
        $('.main').find('tbody').on('click', '.lock', function () {
            lockUtil.handleLockClick($(this));
        });
    }

    return {getComBillsLibInfo, getLibs, eventListener};
})();

$(document).ready(function () {
    billsGuidanceMain.getComBillsLibInfo();
    billsGuidanceMain.getLibs();
    billsGuidanceMain.eventListener();
});