/**
* date: 
* author: neeler 
*/

//test data start
// var data_getList = Mock.mock('/basicinfo/businesstype/getList.htm', {"rowCount":0,"pagesize":0,"pages":1,"page":0,"items":null,"list":[{"direct":"in","departname":null,"weighing":true,"companytype":0,"processKey":"business_process","planitem":false,"candidateGroups":"","departNo":null,"spNos":null,"id":2,"wuzis":"成品","name":"铝锭采购","factory":false,"rownumber":1,"businesstypeNo":"businesstype00001","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":3,"wuzis":null,"name":"产品销售","factory":false,"rownumber":2,"businesstypeNo":"businesstype00002","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":5,"wuzis":null,"name":"物资采购","factory":false,"rownumber":3,"businesstypeNo":"businesstype00003","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":6,"wuzis":null,"name":"物资采购退货","factory":false,"rownumber":4,"businesstypeNo":"businesstype00004","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":7,"wuzis":null,"name":"销售退货","factory":false,"rownumber":5,"businesstypeNo":"businesstype00005","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":8,"wuzis":null,"name":"外出维修出","factory":true,"rownumber":6,"businesstypeNo":"businesstype00006","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":9,"wuzis":null,"name":"外出维修入","factory":false,"rownumber":7,"businesstypeNo":"businesstype00007","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":12,"wuzis":null,"name":"内转半成品出","factory":false,"rownumber":8,"businesstypeNo":"businesstype00008","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":13,"wuzis":null,"name":"内转半成品入","factory":false,"rownumber":9,"businesstypeNo":"businesstype00009","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":14,"wuzis":null,"name":"内转木材出","factory":false,"rownumber":10,"businesstypeNo":"businesstype00010","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":15,"wuzis":null,"name":"内转木材入","factory":false,"rownumber":11,"businesstypeNo":"businesstype00011","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":16,"wuzis":null,"name":"铝废料内转出","factory":false,"rownumber":12,"businesstypeNo":"businesstype00014","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":17,"wuzis":null,"name":"铝废料内转入","factory":false,"rownumber":13,"businesstypeNo":"businesstype00015","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":18,"wuzis":null,"name":"废旧物资处理","factory":false,"rownumber":14,"businesstypeNo":"businesstype00016","note":null},{"direct":"out","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":19,"wuzis":null,"name":"内转外加工出","factory":false,"rownumber":15,"businesstypeNo":"businesstype00012","note":null},{"direct":"in","departname":null,"weighing":true,"companytype":null,"processKey":"business_process","planitem":true,"candidateGroups":"","departNo":null,"spNos":null,"id":20,"wuzis":null,"name":"内转外加工入","factory":false,"rownumber":16,"businesstypeNo":"businesstype00013","note":null}],"hint":null,"errmsg":null,"code":0})
// var data_doDel = Mock.mock('/basicinfo/businesstype/delItem.htm', {code: 0, errmsg: '此岗位正在使用中不能删除!'})
// var data_doSave = Mock.mock('/basicinfo/businesstype/saveItem.htm', {code: 0, errmsg: '此岗位正在使用中不能删除!'})
//test data end

var DIRECT = [{name: '进厂', value: 'in'}, {name: '出厂', value: 'out'}]//, {name: '进出', value: 'inout'}
var directName = {in: '进厂', out: '出厂'}//inout: '进出'
var TYPE = ['成品', '半成品', '其他']// '原料', '辅料', '木料',
var COMPANYTYPE = ['厂外公司', '厂内部门', '内转厂部门']    //0 厂外公司,1 厂内部门  2  内转厂部门

window.I = {
    PZ: 30,
    keyword: $('#keyword'),
    searchBtn: $('#searchBtn'),
    pageValue: !!$('#p').val() ? $('#p').val() - 1 : 0,
    keywordValue: $('#k').val(),
    newObj: $('#newObj'),
    modal: $('#modal'),
    save: $('#save'),
    departModal: $('#departModal'),
    departName: $('#departName'),
    saveDepart: $('#saveDepart')
}

var Obj = {
    id: '',
    processKey: '',
    name: '',
    businesstypeNo: '',
    note: '',
    candidateGroups: '',
    planitem: true,
    factory: false,
    direct: 'in',
    weighing: true,
    departNo: '',
    spNos: '',
    wuzis: TYPE[0],
    companytype: COMPANYTYPE[0],
    departname: ''
}

var ViewModel = function() {
    var self = this;
    self.o = ko.observable(ko.mapping.fromJS(Obj));

    self.keyword = ko.observable(I.keywordValue);
    self.list = ko.observableArray();
    self.dList = ko.observableArray(DIRECT);
    self.cList = ko.observableArray(COMPANYTYPE);
    self.tList = ko.observableArray(TYPE);
    self.sList = ko.observableArray();
    self.rList = ko.observableArray();
    self.dpList = ko.observableArray();

    self.edit = function(item) {
        doEdit(item);
    }
    self.del = function(item) {
        delConfirm(item);
    }
}

$(function () {
    window.vm = new ViewModel();
    ko.applyBindings(vm);
    getDepartList();
    // getShipmentgareaList();
    // doSearch();
    pageInit();

});

function pageInit() {
    I.saveDepart.click(function(event) {
        vm.o().departNo(I.selected.original.bianhao);
        vm.o().departname(I.selected.original.text);
    });
    I.departName.click(function(event) {
        I.departModal.modal('show');
    });
    I.save.click(function(event) {
        if (valid()) {
            doSave();
        }
    });
    I.newObj.click(function(event) {
        vm.o(ko.mapping.fromJS(Obj));
        getNewNo();
        I.modal.modal('show');
    });
    I.searchBtn.click(function(event) {
        doOpen();
    });
    I.modal.on('hidden.bs.modal', function (e) {
        clearError();
        $('#dp').val(vm.rList([])).trigger("chosen:updated");
    });
    I.keyword.on(ISIE ? 'keydown' : 'keyup', function (event) {
        if (event.keyCode == 13) {
            doOpen();
        }
    });
}

function doOpen() {
    var k = $.trim(vm.keyword());
    k = !!k ? '?keyword=' + k : '';
    window.open('businesstype.jsf' + k, '_self');
}

function doSearch() {
    getList(vm.keyword(), I.pageValue, I.PZ, 1);
}

function getList(keyword, page, pagesize, pages) {
    $.post('/basicinfo/businesstype/getList.htm', {
        keyword: keyword,
        page: page,
        pagesize: pagesize,
        pages: pages
    }, function(data, textStatus, xhr) {
        vm.list.removeAll();
        if (data.code >= 1) {
            // parent.showErrmsg(data.errmsg);
             swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
            return;
        }
        if (data.code == 0) {
            if (isList(data.list)) {
                $.each(data.list, function(index, val) {
                    val.directName = directName[val.direct];
                    val.companytype = COMPANYTYPE[val.companytype];
                    vm.list.push(val);
                });
            }
            if (!!pages) {
                pages = data.pages;
                $('#pagdiv').unbind('page').empty();
                if (pages > 1) {
                    $('#pagdiv').bootpag({total: pages, maxVisible: 10, page: page + 1}).on('page',function(event,num){
                        var k = !!I.keywordValue ? '&keyword=' + I.keywordValue : '';
                        window.open('businesstype.jsf?page=' + num + k, '_self');
                    });
                }
            }
            return;
        }
    }, 'json');
}

function valid(){
    var isValid = false;
    var iF = $('#form');
    iF.validate({
        rules: {
            'businesstypeNo': {
                required: true
            },
            'name': {
                required: true
            },
            'departname': {
                required: true
            }
        },
        messages: {
            'businesstypeNo': {
                required: '不能为空!'
            },
            'name': {
                required: '不能为空!'
            },
            'departname': {
                required: '不能为空!'
            }
        },
        errorPlacement: function (err, element) {
            var p = element.parents('.form-group').eq(0);
            var d = p.find('.text-error').eq(0);
            d.css('color', '#D9534F');
            err.appendTo(d);
        }
    })
    isValid = iF.valid();
    return isValid;
}

function doEdit(item) {
    vm.o(ko.mapping.fromJS(item));
    var arr = item.spNos != null ? item.spNos.split(',') : [];
    vm.rList(arr);
    $('#dp').val(vm.rList()).trigger("chosen:updated");
    I.modal.modal('show');
}

function delConfirm(item) {
    $("#modalContent").html('确定要删除【' + item.name + '】吗?');
    $("#dialog-confirm").removeClass('hide').dialog({
        resizable: false,
        width: '320',
        modal: true,
        title: "<div class='widget-header'><h4 class='smaller'><i class='ace-icon fa fa-exclamation-triangle red'></i>确认信息</h4></div>",
        title_html: true,
        position: { my: "center", at: "center", of: window },
        buttons: [
            {
                html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; 确定",
                "class" : "btn btn-danger btn-minier",
                click: function() {
                    $( this ).dialog( "close" );
                    doDel(item);
                }
            }
            ,
            {
                html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 取消",
                "class" : "btn btn-minier",
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        ]
    });
}

function doDel(item) {
    if (!!I.AjaxDelItem) return;
    I.AjaxDelItem = true;
    $.post('/basicinfo/businesstype/delItem.htm', {id: item.id}, function(data, textStatus, xhr) {
        I.AjaxDelItem = false;
        if (data.code >= 1) {
            // parent.showErrmsg(data.errmsg);
            swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
            return;
        }
        if (data.code == 0) {
            vm.list.remove(item);
            location.replace(location.href);
            return;
        }
    }, 'json');
}

function doSave() {
    if (!I.AjaxSaveItem &&valid()) {
        I.AjaxSaveItem = true;
        var o = ko.mapping.toJS(vm.o());
        o.planitem = $('#objPlanitemd').prop('checked');
        o.factory = $('#objFactory').prop('checked');
        o.weighing = $('#objWeighing').prop('checked');
        o.companytype = COMPANYTYPE.indexOf(vm.o().companytype());
        o.spNos = vm.rList().join(',');
        $.post('/basicinfo/businesstype/saveItem.htm', o, function(data, textStatus, xhr) {
            I.AjaxSaveItem = false;
            if (data.code >= 1) {
                // parent.showErrmsg(data.errmsg);
                swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
                return;
            }
            if (data.code == 0) {
                location.replace(location.href);
                return;
            }
        }, 'json');
    }
}

function clearError() {
    $('#form input').removeClass('error');
    $('#form .text-error').html('');
}


function getShipmentgareaList() {
    // $.post('/weight/shipmentgarea/getUsedList.htm', null,
    $.post('/weight/shipmentgarea/getList.htm', null,
     function(data, textStatus, xhr) {
        vm.sList.removeAll();
        if (data.code >= 1) {
            // parent.showErrmsg(data.errmsg);
            swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
            return;
        }
        if (data.code == 0) {
            if (isList(data.list)) {
                $.each(data.list, function(index, val) {
                    vm.sList.push(val);
                });
                $('.chosen-select').chosen({search_contains: true});
                doSearch();
            }
        }
    }, 'json');
}

function getDepartList(keyword, page, pagesize, pages) {
    $.post('/enterprise/depart/getList.htm', {
        keyword: keyword,
        page: page,
        pagesize: pagesize,
        pages: pages
    }, function(data, textStatus, xhr) {
        var allId = [];
        vm.dpList.removeAll();
        if (data.code >= 1) {
           // parent.showErrmsg(data.errmsg);
           swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
            return;
        }
        if (data.code == 0) {
            getShipmentgareaList();
            if (!!$('#jstree_Enterprise').jstree(true)) {
                $('#jstree_Enterprise').jstree(true).refresh();
            }
            I.DB_ep = {};
            I.DB_epnn = {};
            if (isList(data.list)) {
                var Arr = [];
                var level = 0;
                $.each(data.list, function(index, val) {
                    vm.dpList.push(val);
                    allId.push(val.id);
                    I.DB_ep[val.id] = val;
                    I.DB_epnn[val.name] = val.bianhao;
                    if (val.level === 2) {
                        Arr.push({
                            text: val.name,
                            bianhao: val.bianhao,
                            id: val.id,
                            children: [],
                            state: index === 0 ? {selected: true} : ''
                        });
                    } else {
                        var j = 3;
                        var children = Arr[Arr.length - 1].children;
                       while (j < val.level) {
                            children = children[children.length - 1].children;
                            j++;
                        }
                        children.push({
                            text: val.name,
                            bianhao: val.bianhao,
                            id: val.id,
                            children: []
                        })
                    }
                });
                // console.log(allId);
                if (allId.indexOf(I.dValue) != -1) {
                    vm.did(I.dValue);
                }
                $('#jstree_Enterprise')
                .jstree({
                    core: {
                        check_callback : true,
                        data: Arr
                    },
                    "plugins" : [
                      'search'
                    ]
                })
                .on("changed.jstree", function (e, data) {
                    if(data.selected.length) {
                        // console.log(data.instance.get_node(data.selected[0]));
                        var selected = data.instance.get_node(data.selected[0]);
                        I.selected = selected;
                    }
                })
            }
            return;
        }
    }, 'json');
}

function getNewNo() {
    $.post("/basicconfig/prefix/getNewNo.htm", {type: 'businesstype'},
        function (data, textStatus, jqXHR) {
            if (data.code >= 1) {
               // parent.showErrmsg(data.errmsg);
               swal({title:'',text:data.errmsg,type:'error',confirmButtonText:'确定'}); 
                return;
            }
            if (data.code == 0) {
                // vm.o().visitNo(data.number);
                $('#businesstypeNo').val(data.number);
                return;
            }
        },
        "json"
    );
}