$(function () {
    initialPage();
    getGrid();
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

function getGrid() {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, '../mkdisthier/queryAll', colunms, {'distHierName': vm.q.distHierName,'pdistId':vm.q.pdistId});
    table.setExpandColumn(2);
    table.setIdField("distHierId");
    table.setCodeField("distId");
    table.setParentCodeField("parentId");
    table.setExpandAll(false);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}
var TreeGrid = {
    id: "jqGrid",
    table: null,
    layerIndex: -1
};
/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '编号', field: 'distHierId', visitable: false, align: 'center', valign: 'middle', width: '50px'},
        // {title: '编号', field: 'distId', visitable: false, align: 'center', valign: 'middle', width: '50px'},
        // {title: 'parentId', field: 'parentId',  align: 'center', valign: 'middle', width: 50},
        {title: '上级分销商', field: 'parentName', width: 80},
        {title: '子级分销商', field: 'name', width: 80},
        {title: '级别', field: 'hierLvl', width: '50px', align: 'center',
            formatter: function (item) {
                if (item.hierLvl != '') {
                    return item.hierLvl+'级';
                }
                return '';
            }},
        {title: '分销渠道名称', field: 'distFlag', width: 80},
        {title: '分销层级名称', field: 'distHierName', width: 140},
        {title: '分销层级昵称', field: 'distHierNname', width: 80},
        {title: '所属供应商', field: 'childSupplierName', width: 80},
        {title: '是否有效', field: 'isValid',  width: '80px',
            formatter: function (item) {
                if (item.isValid == '0') {
                    return '有效';
                } else if (item.isValid == '1') {
                    return '无效';
                }
                return '';
            }},
        {title: '排序', field: 'sortOrder', width: '50px'},
        {title: '创建人编号', field: 'createrSn',  width: '90px'},
        {title: '创建时间', field: 'createTime',  width: 100,
            formatter: function (item) {
                return transDate(item.createTime, 'yyyy-MM-dd hh:mm:ss');
            }},
        {title: '修改人编号', field: 'moderSn', width: '90px'},
        {title: '修改时间', field: 'modTime', width: 100,
            formatter: function (item) {
                return transDate(item.modTime, 'yyyy-MM-dd hh:mm:ss');
            }}
        ]
    return columns;
};

let vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
		mkDistHier: {},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
		q: {
            distHierName: '',
            pdistId:''
		},
        suppliers:[],
		mkDistList:[],
		mkDistChnlList:[],
        mkChildDistList:[],
        mkUpDistList:[],
        lvlEntitieyList: [],
        isOperatorShow: false,
        hierLvl: '',
        queryMkDistList:[]
    },
	methods: {
		query: function () {
            // $('#jqGrid').treegrid('load', {'distHierName': vm.q.distHierName,'distId':vm.q.distId});
            // TreeGrid.table.refresh({'distHierName': vm.q.distHierName,'distId':vm.q.distId});
            // TreeGrid.table.refresh();
			vm.reload();
		},
		add: function () {
			vm.showList = false;
			vm.title = "新增";
			vm.suppliers = [];
            vm.mkDistList = [];
            vm.mkDistChnlList = [];
			vm.mkDistHier = {isValid:0};
            vm.isOperatorShow = false;
			// vm.showSupplier();
			// vm.getMkDistList();
			vm.getMkDistChnlList();
			vm.getLvlList();
		},
		update: function (event) {
            // let distHierId = getSelectedRow();
			// if (distHierId == null) {
			// 	return;
			// }

            var id = TreeGrid.table.getSelectedRow();
            if (id.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            let distHierId = id[0].id;
            vm.showList = false;
            vm.title = "修改";
            vm.isOperatorShow = true;

            // vm.showSupplier();
            // vm.getMkDistList();
            vm.getMkDistChnlList();
            vm.getInfo(distHierId);
            vm.getLvlList();
		},
		saveOrUpdate: function (event) {
            let url = vm.mkDistHier.distHierId == null ? "../mkdisthier/save" : "../mkdisthier/update";
			$.ajax({
				type: "POST",
			    url: url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.mkDistHier),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
			});
		},
		del: function (event) {
            // let distHierIds = getSelectedRows();
			// if (distHierIds == null){
			// 	return;
			// }
            var distHierId = TreeGrid.table.getSelectedRow(), distHierIds = [];
            if (distHierId.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            $.each(distHierId, function (idx, item) {
                distHierIds[idx] = item.id;
            });

			confirm('确定要删除选中的记录？', function () {
				$.ajax({
					type: "POST",
				    url: "../mkdisthier/delete",
				    contentType: "application/json",
				    data: JSON.stringify(distHierIds),
				    success: function (r) {
						if (r.code == 0) {
							alert('操作成功', function (index) {
                                vm.reload();
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(distHierId){
			$.get("../mkdisthier/info/"+distHierId, function (r) {
                vm.mkDistHier = r.mkDistHier;
                vm.upDist(vm.mkDistHier.pdistId);
            });
		},
        showSupplier: function (supplierId) {
            $.get("../supplier/queryAll?supplierId="+supplierId, function (r) {
                vm.suppliers = r.list;
            });
        },
        // changeLvl: function (opt) {
        //     var distId = opt.value;
        //     if(distId){
        //         $.get("../mkdisthier/queryNextLvlByDistId?distId="+distId+"&isOperatorShow="+vm.isOperatorShow, function (r) {
        //             console.log(r.lvlEntitieyList)
        //             if(r.lvlEntitieyList){
        //                 vm.lvlEntitieyList = r.lvlEntitieyList;
        //             }else{
        //                 vm.getLvlList();
        //             }
        //             console.log(vm.lvlEntitieyList)
        //         });
        //     }
        // },
        getLvlList: function () {
            $.get("../mkdisthier/queryAllConfig", function (r) {
                vm.lvlEntitieyList = r.lvlEntitieyList;
            });
        },
        changeDist: function (option) {
		    var distChnlId = option.value;
		    if(distChnlId){
                $.get("../mkdistchnl/info/"+distChnlId, function (r) {
                    var thirdMerchSn = r.mkDistChnl.thirdMerchSn;
                    var supplierId = r.mkDistChnl.supplierId;
                    vm.getMkDistList(thirdMerchSn,supplierId);
                    vm.showSupplier(supplierId);
                });
            }
        },
        getMkDistList: function (thirdMerchSn,supplierId) {
            $.get("../mkdist/queryAll?thirdMerchSn="+thirdMerchSn+"&supplierId="+supplierId, function (r) {
                vm.mkDistList = r.list;
            });
        },
        upDist: function (distId) {
		    if(distId){
                $.get("../mkdist/queryAllById?distId="+distId, function (r) {
                    vm.mkUpDistList = r.list;
                });
            }
        },
        changeChildDist: function (option) {
		    var distId = option.value;
            $.get("../mkdist/queryChildAll?childDistId="+distId, function (r) {
                vm.mkChildDistList = r.list;
            });
        },
        getMkDistChnlList: function () {
            $.get("../mkdistchnl/queryAll", function (r) {
                vm.mkDistChnlList = r.list;
            });
        },
        reloadSearch: function() {
            vm.q = {
                distHierName: '',
                pdistId:''
            }
            vm.reload();
		},
		reload: function (event) {
            vm.showList = true;
            // TreeGrid.table.refresh();
            initialPage();
            getGrid();
			/*vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {'distHierName': vm.q.distHierName,'distId':vm.q.distId},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');*/
		},
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
	},
    mounted() {
        $.get("../mkdist/queryAllByHier", function (r) {
            vm.queryMkDistList = r.list;
        });
    }
});