$(function () {
    $("#jqGrid").jqGrid({
        url: '../productstorerela/list',
        datatype: "json",
        colModel: [
            {label: 'ID', name: 'id', index: 'id', hidden: true, key: true},
            {label: '商品商户编号', name: 'goods_merch_sn', index: 'goods_merch_sn', hidden: true},
            {label: '所属商户', name: 'merchName', index: 'merchName', width: 100, align: 'center'},
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 80, align: 'center'},
            {label: '商品类型', name: 'categoryName', index: 'categoryName', width: 80, align: 'center'},
            {
                label: '货品业务类型', name: 'goodsBizType', index: 'goods_biz_type', width: 70, align: 'center',
                formatter: function (value) {
                    if (value == '00') {
                        return '保税备货';
                    } else if (value == '02') {
                        return '保税展示补货';
                    } else if (value == '10') {
                        return '保税展示跨境';
                    }
                    return '普通货物';
                }
            },
            {label: '商品编码', name: 'goodsSn', index: 'goodsSn', width: 80, align: 'center'},
            {label: '名称', name: 'goodsName', index: 'goodsName', width: 160, align: 'left'},
            {label: '产品编码', name: 'productSn', index: 'productSn', width: 80, align: 'center'},
            {label: '库存是否共享', name: 'isStockShare', index: 'isStockShare', width: 80, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '否';
                    } else if (value == '1') {
                        return '是';
                    }
                    return '-';
                }},
            {label: '门店库存', name: 'stockNum', index: 'stockNum', width: 80, align: 'center'},
            {label: '零售价格', name: 'retailPrice', index: 'retailPrice', width: 80, align: 'center'},
            // {label: '市场价', name: 'marketPrice', index: 'marketPrice', width: 80, align: 'center'},
            // {label: '库存价格', name: 'stockPrice', index: 'stockPrice', width: 80},
            {
                label: '销售量',
                name: 'sellVolume',
                index: 'a.sell_volume',
                width: 80,
                sortable: true, align: 'center',
                onSortCol: function (index, colindex, sortorder) {
                    //列排序事件
                    jQuery("#jqGrid").jqGrid('setGridParam', {page: $('#XtoPage').val()});
                }
            },
            {
                label: '操作', width: 60, align: 'center', sortable: false, formatter: function (value, col, row) {
                let htmlStr = '';
                if (row.goodsBizType == '02' || row.goodsBizType == '10') {
                    htmlStr = "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.qrcodeCanvas(" + row.goodsId + ",\""+ row.storeId +"\",\""+row.goodsMerchSn+"\",\""+row.merchSn+"\")'><i class='fa fa-qrcode'></i>二维码</button>";
                }
                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"});
        }
    });
    $('#goodsDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: '500px', //高度
        minHeight: '200px',
        language: "zh_cn",
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../sys/oss/upload',
        imageUploadParams: {id: "edit"},
        imagesLoadURL: '../sys/oss/queryAll'
    })
});

var ztree;

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        uploadList: [],
        imgName: '',
        visible: false,
        productStoreRela: { stockNum: '', retailPrice: '', marketPrice: '', categoryId:'', brandId:'', specification:'', storeId:'', goodsBizType:'' },
        ruleValidate: {
            /*storeId: [
                {required: true, message: '门店不能为空'}
            ]*/
        },
        q: {
            storeId: '',
            goodsName: '',
            productSn: '',
            goodsSn: '', category: '', categoryTwo: '', goodsBizType:''
        },
        stores: [],
        macros: [],//商品单位
        goodss: {},
        products: [],
        showInput: false,
        showInputSpecification: false,
        categories: [],//一级分类
        categoriesTwo: [],
        brands: [],
        attributeEntityList: [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}],
        attributes: [],
        queryCategories: [],//一级分类
        queryCategoriesTwo: [],
        categoryId: '',
        freights: [],
        storeId: 0,
        specification: '',
        isOperator: '',
        isStockShare: false,
        isOperatorShow: false
    },
    methods: {
        changeGoods: function (opt) {
            var goodsId = opt.value;
            if (null != goodsId && '' != goodsId) {
                $.get("../goods/info/" + goodsId, function (r) {
                    vm.showInput = true;
                    // console.log(r.goods.goodsBizType);
                    if (r.goods.goodsBizType == 11) {
                        vm.showInputSpecification = true;
                    } else {
                        vm.showInputSpecification = false;
                    }

                    $.get("../thirdmerchantbiz/infoByCode?thirdMerchantCode=" + r.goods.thirdPartyMerchCode, function (rr) {
                        if(rr.thirdMerchantBiz==null){
                            alert('请先维护第三方商户，门店商户是否共享字段');
                            vm.isStockShare = true;
                            return;
                        }
                        if(rr.thirdMerchantBiz.isStockShare==null){
                            alert('请先维护商品信息，第三方商户代码字段');
                            vm.isStockShare = true;
                            return;
                        }

                        if(r.goods.goodsBizType == '00' && rr.thirdMerchantBiz.isStockShare == 1){//共享
                            vm.isStockShare = true;
                        }else{
                            vm.isStockShare = false;
                        }
                    });
                });
            }
        },
        changeQueryCategories: function (opt) {
            var value = opt.value;
            $.get("../category/getCategorySelectByParent?parentId=" + value, function (r) {
                vm.queryCategoriesTwo = r.list;
            });
        },
        reloadSearch: function () {
            vm.q = {
                storeId: '',
                goodsName: '',
                productSn: '',
                goodsSn: '', category: '', categoryTwo: '', goodsBizType:''
            }
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        add: function (event) {
            vm.showList = false;
            vm.title = "新增";
            vm.isOperator = 'add';
            vm.isOperatorShow = false;
            vm.uploadList = [];
            vm.freights = [];
            vm.brands = [];
            vm.productStoreRela = { stockNum: '', retailPrice: '', marketPrice: '', categoryId:'', brandId:'',specification:'', storeId:'' };
            vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
            vm.getMacro();
            vm.showInput = false;
            vm.showInputSpecification = false;
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.isOperator = 'update';
            vm.isOperatorShow = true;
            vm.uploadList = [];
            vm.getInfo(id);
            var opt = {};
            opt.value = vm.productStoreRela.categoryId;
            opt.flag = 1;
            vm.getAttributes(opt);
            vm.getMacro();
            if (vm.productStoreRela.goodsBizType == 11) {
                vm.showInput = true;
                vm.showInputSpecification = true;
            }else{
                vm.showInput = false;
                vm.showInputSpecification = false;
            }
        },
        /**
         * 获取单位
         */
        getMacro: function () {
            $.get("../sys/macro/queryMacrosByValue?value=goodsUnit", function (r) {
                vm.macros = r.list;
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.productStoreRela.id == null ? "../productstorerela/save" : "../productstorerela/update";
            vm.productStoreRela.attributeEntityList = vm.attributeEntityList;
            console.log(vm.productStoreRela);
            console.log(vm.productStoreRela.specification);
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.productStoreRela),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../productstorerela/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get("../productstorerela/info/" + id, function (r) {
                vm.productStoreRela = r.productStoreRela;
                vm.categoryId = r.productStoreRela.categoryId;
                // vm.getCategory();
                var opt = {};
                opt.value = vm.productStoreRela.attributeCategory;
                vm.changeCategories(opt);
                if (r.productStoreRela.attributeEntityList.length > 0) {
                    vm.attributeEntityList = r.productStoreRela.attributeEntityList;
                } else {
                    vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
                }
                vm.specification = vm.productStoreRela.specification;
                vm.storeId = vm.productStoreRela.storeId;
            });
        },
        getGoods: function (opt) {
            var storeId = opt.value;
            var merchSn = "";
            for (var i = 0; i < vm.stores.length; i ++ ) {
                if(vm.stores[i].id == storeId)
                    merchSn = vm.stores[i].merchSn;
            }
            vm.storeId = storeId;
            if(vm.isOperator == 'add'){
                $.get("../goods/queryAll?merchSn=" + merchSn + "&storeId=" +storeId, function (r) {
                    vm.goodss = r.list;
                });
            }else{
                $.get("../goods/queryAll?merchSn=" + merchSn, function (r) {
                    vm.goodss = r.list;
                });
            }
            vm.getCategories(storeId);
            vm.getFreights(storeId);
        },
        changeCategories: function (opt) {
            var value = opt.value;
            vm.getBrand(value);
            if(value){
                $.get("../category/getCategorySelectByParent?isShow=1&parentId=" + value, function (r) {
                    vm.categoriesTwo = r.list;
                });
            }
        },
        getCategoryByStore: function (opt) {
            var value = opt.value;
            vm.getCategories(value);
            vm.getFreights(value);
        },
        getCategories: function (storeId) {
            $.get("../category/getCategorySelect?isShow=1&storeId=" + storeId, function (r) {
                vm.categories = r.list;
            });
        },
        getBrand: function (categoryId) {
            $.get("../brand/queryAll?categoryId=" + categoryId, function (r) {
                vm.brands = r.list;
            });
        },
        getAttributes: function (opt) {
            var value = opt.value;
            if(value){
                $.get("../attribute/query?attributeCategoryId=" + value + "&storeId="+vm.storeId, function (r) {
                    vm.attributes = r.list;
                });

                if (opt.flag != 1 && !(value === vm.categoryId)) {
                    if (vm.attributeEntityList.length > 0 && vm.attributeEntityList[0].attributeId != '') {
                        for (var i = 0; i < vm.attributeEntityList.length; i++) {
                            if (!(vm.attributeEntityList[0].attributeId === '')) {
                                vm.attributeEntityList[i].isDelete = 1;
                            }
                        }

                        var goodsId = '';
                        if (vm.goodss) {
                            goodsId = vm.goodss.id;
                        }
                        vm.attributeEntityList.unshift({'id': '', 'goodsId': goodsId, 'attributeId': '', 'value': '', 'isDelete': 0});
                    }
                }
            }
        },
        getFreights: function(storeId) {
            $.get("../freight/queryAll?storeId=" + storeId, function (r) {
                vm.freights = r.list;
            });
        },
        addAttrRow: function () {
            let goodsId = '';
            if (vm.goods) {
                goodsId = vm.goods.id;
            }
            vm.attributeEntityList.push({'id': '', 'goodsId': goodsId, 'attributeId': '', 'value': '', 'isDelete': 0});
        },
        delAttrRow: function (index) {
            //最后一行时禁止删除
            if (vm.attributeEntityList.length == 1) {
                return;
            }
            vm.attributeEntityList[index].isDelete = 1;
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    storeId: vm.q.storeId,
                    goodsName: vm.q.goodsName,
                    goodsSn: vm.q.goodsSn,
                    productSn: vm.q.productSn, category: vm.q.category, categoryTwo: vm.q.categoryTwo, goodsBizType:vm.q.goodsBizType
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        uploadExcelSuccess: function () {
            alert('上传成功', function (index) {
                $("#jqGrid").trigger("reloadGrid");
            });
        },
        uploadExcelError: function () {
            alert('上传出现异常');
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            // 从 upload 实例删除数据
            const fileList = this.uploadList;
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.imgUrl = res.url;
            file.name = res.url;
            vm.uploadList.add(file);
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。'
                });
            }
            return check;
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        qrcodeCanvas: function(id,storeId,goodsMerchSn,merchSn) {
            if(merchSn != goodsMerchSn){
                alert("商品所属商户与门店商品所属商户不一致，请修改为一致后再生成二维码！");
                return;
            }
            $("#qrcodeCanvas").html("");
            $("#qrcodeCanvas").qrcode({
                render : "canvas",    //设置渲染方式，有table和canvas，使用canvas方式渲染性能相对来说比较好
                text : "emato../goods/goods?id=" + id +"&storeId="+storeId,    //扫描二维码后显示的内容,可以直接填一个网址，扫描二维码后自动跳向该链接
                width : "100",               //二维码的宽度
                height : "100",              //二维码的高度
                background : "#ffffff",       //二维码的后景色
                foreground : "#000000",        //二维码的前景色
                src: '../../statics/img/logo.jpg'             //二维码中间的图片
            });

            var qrcSrc = $("canvas")[0].toDataURL();
            console.log(qrcSrc);
            $("#qrcImg .qrcImg").attr("src", qrcSrc);
            var upLogSrc = "../../statics/img/logo.jpg";
            $("#qrcImg .upLogo").attr("src", upLogSrc);
            $("#qrcImg").show();//隐藏canvas部分

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

            $("#qrcImg").hide();
        }
    },
    mounted() {
        $.get("../category/getCategorySelect", function (r) {
            vm.queryCategories = r.list;
        });
        $.get("../store/queryAll", function (r) {
            vm.stores = r.list;
        });
        $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
            vm.macros = r.list;
        });
    }
});