$(function () {
    $("#jqGrid").jqGrid({
        url: '../store/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '商户编号', name: 'merchSn', index: 'merch_sn', width: 80},
            {label: '商户名称', name: 'merchName', index: 'merch_name', width: 60, align: 'center'},
            {label: '第三方商户编号', name: 'thirdPartyMerchCode', index: 'thirdPartyMerchCode', width: 60, align: 'center'},
            {label: '第三方商户名称', name: 'thirdPartyMerchName', index: 'thirdPartyMerchName', width: 60, align: 'center'},
            {label: '门店名称', name: 'storeName', index: 'store_name', width: 80, align: 'center'},
            {label: '门店编号', name: 'storeNumber', index: 'store_number', width: 80, align: 'center'},
            {label: '门店地址', name: 'storeAddress', index: 'store_address', width: 80, align: 'center'},
            {label: '省份', name: 'provinceName', index: 'province_name', width: 60, align: 'center'},
            {label: '城市', name: 'cityName', index: 'city_name', width: 60, align: 'center'},
            {label: '区', name: 'countyName', index: 'county_name', width: 60, align: 'center'},
            {label: '纬度', name: 'latitude', index: 'latitude', width: 80, align: 'center'},
            {label: '经度', name: 'longitude', index: 'longitude', width: 80, align: 'center'},
            // {label: '配送半径（km）', name: 'coverRadius', index: 'cover_radius', width: 60, align: 'center'},
            {label: '备注', name: 'remark', index: 'remark', width: 40, align: 'center'},

            {label: '是否显示', name: 'isValid', index: 'is_valid', width: 60, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '显示';
                    } else if (value == '1') {
                        return '禁用';
                    }
                    return '';
                }},
            {
                label: '操作', width: 150, align: 'center', sortable: false, formatter: function (value, col, row) {
                    let htmlStr = "-";
                    if (row.isValid == 0) {
                        htmlStr = "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.qrcodeCanvas(" + row.id + ")'><i class='fa fa-qrcode'></i>二维码</button>";
                    }else{
                        htmlStr = "<span style='color: red;font-weight: bolder'>门店禁用则没有生成二维码权限</span>";
                    }
                    return htmlStr;
                }
            }],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        store: {isValid: ''},
        ruleValidate: {
            storeName: [
                {required: true, message: '门店名称不能为空', trigger: 'blur'}
            ],
            storeNumber: [
                {required: true, message: '门店编号不能为空', trigger: 'blur'}
            ],
            thirdPartyMerchCode: [
                {required: true, message: '第三方商户编号不能为空', trigger: 'blur'}
            ],
            thirdPartyMerchName: [
                {required: true, message: '第三方商户名称不能为空', trigger: 'blur'}
            ],
        },
        q: {
            storeName: '',
            storeNumber: ''
        },
        merchList: [],
        thirdMerchantBizList: [],
        mkDistList: []
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.store = {isValid: 0,exprAgreementType:'00',distId:''};
            vm.merchList = [];
            vm.getMerchList();
        },
        update: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.merchList = [];
            vm.thirdMerchantBizList = [];
            vm.getMerchList();
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            let url = vm.store.id == null ? "../store/save" : "../store/update";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.store),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../store/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        showMerchInfo:function(opt){
            var merchSn = opt.value;
            vm.getThirdMerchantBizList(merchSn);
        },
        getMerchList: function() {
            $.get("../merch/queryAll", function (r) {
                vm.merchList = r.list;
            });
        },
        getThirdMerchantBizList: function(merchSn) {
            $.get("../thirdmerchantbiz/queryAll?merchSn=" + merchSn, function (r) {
                vm.thirdMerchantBizList = r.list;
            });
        },
        // getMkDistList: function (opt) {
        //     var thirdPartyMerchCode = opt.value;
        //     $.get("../mkdist/queryAll?thirdMerchantCode="+thirdPartyMerchCode, function (r) {
        //         vm.mkDistList = r.list;
        //     });
        // },
        getInfo: function (id) {
            $.get("../store/info/" + id, function (r) {
                vm.store = r.store;
                // vm.getThirdMerchantBizList(r.store.merchSn);
            });
        },
        reloadSearch: function () {
            vm.q = {
                storeName: '',
                storeNumber: ''
            }
            vm.reload();
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'storeName': vm.q.storeName, 'storeNumber': vm.q.storeNumber},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        qrcodeCanvas: function(storeId) {
            $("#qrcodeCanvas").html("");
            $.get("../store/qrcodeCanvas/" + storeId, function (r) {
                // console.log(r.url);
                var qrcSrc = r.url;
                $("#qrcImg .qrcImg").attr("src", qrcSrc);
                // $("#qrcImg").show();//隐藏canvas部分

                $("#qrcodeCanvas").html($("#qrcImg").html());

                openWindow({
                    title: "二维码",
                    area: ['450px', '450px'],
                    content: jQuery("#qrcode"),
                    btn: ["打印"],
                    btn1: function (index) {
                        $("#qrcImg").show();
                        $("#qrcImg").print({});
                        $("#qrcImg").hide();
                        layer.close(index);
                    }
                });
            });

            $("#qrcImg").hide();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});