$(function() {
    $("#jqGrid").Grid({
        url: '../goods/list',
        rownumWidth: 60,
        multiboxonly: true,
        colModel: [
            { label: 'id', name: 'id', index: 'id', key: true, hidden: true },
            { label: '商品名称', name: 'name', index: 'name', width: 160 },
            { label: '商品描述', name: 'goodsSimpleDesc', index: 'goodsSimpleDesc', width: 160 },
            { label: '购买链接', name: 'realShopUrl', index: 'realShopUrl', width: 160 },
            { label: '商品分类', name: 'categoryName', index: 'category_id', width: 80 },
            { label: '直播间名称', name: 'brandName', index: 'brand_id', width: 120 },
            {
                label: '录入日期',
                name: 'addTime',
                index: 'add_time',
                width: 80,
                formatter: function(value) {
                    return transDate(value, 'yyyy-MM-dd');
                }
            },
            // {label: '属性类别', name: 'attributeCategoryName', index: 'attribute_category', width: 80},
            { label: '零售价格', name: 'retailPrice', index: 'retail_price', width: 80 },
            { label: '商品库存', name: 'goodsNumber', index: 'goods_number', width: 80 },
            { label: '销售量', name: 'sellVolume', index: 'sell_volume', width: 80, formatoptions: { defaultValue: '0' } },
            { label: '市场价', name: 'marketPrice', index: 'market_price', width: 80 },
            {
                label: '上架',
                align: 'center',
                name: 'isOnSale',
                index: 'is_on_sale',
                width: 50,
                formatter: function(value) {
                    return transIsNot(value);
                }
            }
            // {
            //     label: '热销', name: 'isHot', index: 'is_hot', width: 80, formatter: function (value) {
            //         return transIsNot(value);
            //     }
            // }
        ]
    });
    $('#goodsDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        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 guigeDetailHeader = [{
        name: '库存',
        id: 'goodsNumber'
    },
    {
        name: '规格编码',
        id: 'goodsSn'
    },
    {
        name: '市场价',
        id: 'marketPrice'
    },
    {
        name: '销售价',
        id: 'retailPrice'
    },

]

var val1 = [{
        val: '20码',
        id: '20m'
    },
    {
        val: '30码',
        id: '30m'
    }
]

var val2 = [{
        val: '10寸',
        id: '10c'
    },
    {
        val: '20寸',
        id: '20c'
    },
]

var val3 = [{
        val: '毛坯房',
        id: 'mp'
    },
    {
        val: '精装房',
        id: 'jz'
    }
]

var isFrist = true

var vm = new Vue({
    el: '#rrapp',
    data: function() {
        const validateBrandIdCheck = function(rule, value, callback) {
            if (value === '' || !value) {
                callback(new Error('直播间不能为空'));
            } else {
                callback();
            }
        };


        const validateCategoryNameCheck = function(rule, value, callback) {
            if (isFrist) {
                isFrist = false
                return
            }
            if (value === '' || !value || value === '一级分类') {
                callback(new Error('请选择商品类型'));
            } else {
                callback();
            }
        };

        const validateNameCheck = function(rule, value, callback) {
            if (value === '' || !value) {
                callback(new Error('名称不能为空'));
            } else if (value.length > 15) {
                callback(new Error('商品名称不能超过15个字符'));
            } else {
                callback();
            }
        };

        const validaterealShopUrlCheck = function(rule, value, callback) {
            if (value === '' || !value) {
                callback();
            } else if (value.length > 500) {
                callback(new Error('网站链接不能超过500个字符'));
            } else if (!(value.indexOf('item.jd') > -1 || value.indexOf('item.m.jd') > -1)) {
                callback(new Error('目前不支持添加其他网站链接'));
            } else {
                callback();
            }
        };


        const validateDescCheck = function(rule, value, callback) {
            if (value === '' || !value) {
                callback(new Error('商品描述不能为空'));
            } else if (value.length > 30) {
                callback(new Error('商品描述不能超过30个字符'));
            } else {
                callback();
            }
        };

        const validateinputArr = function(rule, value, callback) {
            console.log(rule, value)
            if (value === '' || !value) {
                callback(new Error('规格明细不能为空'));
            } else if (value.length > 30) {
                callback(new Error('规格明细不能超过30个字符'));
            } else {
                callback();
            }
        };

        const validatelistPicUrlCheck = function(rule, value, callback) {
            if (value.length <= 0 || !value) {
                callback(new Error('商品列表图不能为空'));
            } else {
                callback();
            }
        };

        const validateprimaryPicUrlCheck = (rule, value, callback) => {
            return new Promise((resolve, reject) => {
                if (value === '' || !value) {
                    reject('商品主图不能为空');
                } else {
                    resolve();
                }
            });
        };

        const validateGuigeCheck = (rule, value, callback) => {
            callback();
        };

        const validateGuigemingxiCheck = (rule, value, callback) => {
            callback();
        };


        let user = JSON.parse(localStorage.getItem('userInfo'))

        return {
            ggheader: guigeDetailHeader,
            userInfo: user,
            ggContent: "",
            showList: true,
            title: null,
            uploadList: [],
            defaultList: [],
            imgName: '',
            visible: false,
            picList: [],
            goods: {
                primaryPicUrl: '',
                listPicUrl: [],
                categoryId: '',
                isOnSale: 1,
                isNew: 1,
                realShopUrl: '',
                isAppExclusive: 0,
                isLimited: 0,
                isHot: 0,
                categoryName: '',
                guigeArr: []
            },
            ruleValidate: {
                inputArr: [
                    { required: true, validator: validateinputArr, trigger: 'change' }
                ],
                categoryName: [
                    { required: true, validator: validateCategoryNameCheck, trigger: 'change' }
                ],
                goodsSn: [
                    { required: true, message: '商品序列号不能为空', trigger: 'blur' }
                ],
                name: [
                    { required: true, validator: validateNameCheck, trigger: 'blur' }
                ],
                goodsSimpleDesc: [
                    { required: true, validator: validateDescCheck, trigger: 'blur' }
                ],
                realShopUrl: [
                    { validator: validaterealShopUrlCheck, trigger: 'blur' }
                ],
                brandId: [
                    { required: true, validator: validateBrandIdCheck, trigger: 'change' }
                ],
                primaryPicUrl: [
                    { required: true, validator: validateprimaryPicUrlCheck, trigger: 'blur' }
                ],
                listPicUrl: [
                    { required: true, validator: validatelistPicUrlCheck, trigger: 'blur' }
                ],
                guigeArr: [
                    { required: true, validator: validateGuigeCheck, trigger: 'change' }
                ],
                ggContent: [
                    { required: true, validator: validateGuigemingxiCheck, trigger: 'change' }
                ]
            },
            q: {
                name: '',
                brandId: ''
            },
            showguigearr: false,
            brands: [], //品牌
            macros: [], //商品单位
            attributeCategories: [], //属性类别
            specifications: [],
            ggname: [],
            guigeArr: [{
                name: '',
                val: [{
                    name: '',
                    picUrl: ''
                }]
            }],
            currenIdx: '',
            currenI: '',
            inputArr: [],
            goodsSpecificationList: []
        }
    },
    methods: {
        handleSuccessBrandPicUrl: function(res, file) {
            this.loading = false
            file.url = res.url + window.fixImg + 'm_fixed,w_400,h_400';
            file.name = res.url + window.fixImg + 'm_fixed,w_400,h_400';
            //  file.url = res.url
            //  file.name = res.url

            vm.goods.listPicUrl = this.$refs.goodupload.fileList
            vm.picList = this.$refs.goodupload.fileList
            console.log(vm.picList)
        },

        getInputArr: function() {
            let uuidLink = []
            var arr = []

            function pushArr(arr, uuidLink, inputVal) {
                let item = vm.inputArr.find(item => item.uuidLink === uuidLink)
                console.log(item)
                if (item) {
                    arr.push(item)
                } else {
                    let item = {
                        goodsNumber: inputVal.goodsNumber,
                        goodsSn: inputVal.goodsSn,
                        retailPrice: inputVal.retailPrice,
                        marketPrice: inputVal.marketPrice,
                        uuidLink: uuidLink
                    }
                    arr.push(item)
                }
            }
            this.ggContent.forEach(function(item) {
                uuidLink = []

                uuidLink.push(item.uuid)
                if (item.subItems) {
                    item.subItems.forEach(function(sub) {
                        uuidLink[1] = sub.uuid
                        if (sub.subItems) {
                            sub.subItems.forEach(function(last) {
                                uuidLink[2] = last.uuid
                                if (!last.subItems) {
                                    pushArr(arr, uuidLink.join('_'), last.inputVal)
                                    uuidLink.pop()
                                }
                            })
                        } else {
                            pushArr(arr, uuidLink.join('_'), sub.inputVal)
                            uuidLink.pop()
                        }
                    })
                } else {
                    pushArr(arr, uuidLink.join('_'), item.inputVal)
                    uuidLink.pop()
                }
            })
            this.inputArr = arr
        },
        transToGuigeArr: function(arr) {
            let temp = []
            let tepName = arr.map(function(item) {
                return item.specificationName
            })
            console.log(arr, 'arr')
            tepName = []
            arr.forEach(function(item) {
                if (!~tepName.indexOf(item.specificationName)) {
                    tepName.push(item.specificationName)
                    temp.push({
                        name: item.specificationName,
                        val: [{
                            name: item.value,
                            picUrl: item.picUrl,
                            uuid: item.uuid,
                            id: item.id
                        }]
                    })
                } else {
                    temp.forEach(function(sub) {
                        if (sub.name === item.specificationName) {
                            sub.val.push({
                                name: item.value,
                                picUrl: item.picUrl,
                                uuid: item.uuid,
                                id: item.id
                            })
                        }
                    })

                }

            })

            this.guigeArr = temp
            this.showArr()
        },
        validateInput: function() {
            var pass = true
            vm.inputArr && vm.inputArr.forEach(function(item) {
                if (!isNumber(item.retailPrice) || !isNumber(item.marketPrice) || !isNumber(item.goodsNumber)) {
                    pass = false
                    return pass
                }

                if (!(item.retailPrice && item.retailPrice >= 0.01) || !(item.marketPrice && item.marketPrice >= 0.01)) {
                    pass = false
                }

                if (item.goodsNumber && item.goodsNumber < 1) {
                    pass = false
                }

            })

            return pass
        },
        handleInputChange: function(item, key, i) {
            if (key == 'goodsNumber') {
                item[key] = item[key].replace(/[^\d]/g, '')
            } else {
                item[key] = item[key].replace(/[^\d\.]/g, '')
            }
            vm.$set(vm.inputArr, i, item)
        },
        validateGuigeArr: function() {
            var pass = true
            if (this.guigeArr.length <= 0) {
                layer.alert("请先添加规格项目", { icon: 5 });
                pass = false
                return pass
            }
            this.guigeArr.forEach(function(item) {
                item.val && item.val.forEach(function(i) {
                    if (!i.name) {
                        layer.alert("规格值请填写完整", { icon: 5 });
                        pass = false
                    }
                })
            })
            return pass
        },
        showArr: function() {
            if (!this.validateGuigeArr()) {
                return
            }
            let tmp = []
            let itm = []
            let goodsSpecificationList = []
            this.ggname = []
            this.guigeArr.forEach(function(item, idx) {
                itm = []
                item.val.forEach(function(sub, i) {
                    let tt = {
                        value: sub.name,
                        picUrl: sub.picUrl || '',
                        uuid: sub.uuid || ((idx + 1) + '-' + (i + 1)),
                        specificationId: item.specificationId,
                        inputVal: {
                            goodsNumber: '',
                            goodsSn: '',
                            retailPrice: '',
                            marketPrice: ''
                        }
                    }
                    sub.uuid = sub.uuid || ((idx + 1) + '-' + (i + 1))
                    itm.push(tt)
                    goodsSpecificationList.push(tt)
                })
                vm.ggname.push({
                    name: item.name
                })
                tmp.push(itm)
            })
            console.log(this.guigeArr)


            tmp[0].forEach(function(i1) {
                if (tmp[1]) {
                    i1['subItems'] = tmp[1]
                    i1['subItems'].forEach(function(i2) {
                        if (tmp[2]) {
                            i2['subItems'] = tmp[2]
                        }
                    })
                }

            })
            this.ggContent = tmp[0]
            this.goodsSpecificationList = goodsSpecificationList
            this.getInputArr()
        },
        handleItem: function(idx, sub) {
            this.$set(this.guigeArr[idx], 'name', sub.name)
            this.$set(this.guigeArr[idx], 'picUrl', '')
            this.$set(this.guigeArr[idx], 'specificationId', sub.id)
            this.$set(this.guigeArr[idx], 'show', false)
        },

        handleBigItem: function(item) {
            this.guigeArr.splice(item, 1)
        },
        handleCurrentIdx: function(i, idx) {
            vm.currenIdx = idx
            vm.currenI = i

        },
        handleItemPicUrl: function(res, file) {
            vm.$set(vm.guigeArr[vm.currenI]['val'][vm.currenIdx], 'picUrl', file.response.url)
            this.guigeArr = vm.guigeArr
        },
        onfocus: function(idx) {
            this.$set(this.guigeArr[idx], 'show', true)
        },
        onblur: function(idx) {
            this.$set(this.guigeArr[idx], 'show', false)
        },
        delguige: function(item, parent) {
            parent.splice(item, 1)
        },
        addguige: function(item) {
            item.val.push({
                name: '',
                picUrl: ''
            })

        },
        addGoodsItem: function() {
            if (!this.guigeArr) {
                this.guigeArr = []
            }
            if (this.guigeArr.length >= 3) {
                window.alert('抱歉，最多只能添加三个规格')
                return
            }
            this.guigeArr.push({
                name: '',
                val: [{
                    name: '',
                    picUrl: ''
                }]
            })
        },
        query: function() {
            vm.reload();
        },
        getSpecification: function() {
            Ajax.request({
                url: "../specification/queryAll",
                async: true,
                successCallback: function(r) {
                    vm.specifications = r.list;
                }
            });
        },
        add: function() {
            vm.showList = false;
            vm.title = "新增";
            vm.uploadList = [];
            vm.defaultList = []
            vm.picList = []
            vm.goods = {
                primaryPicUrl: '',
                listPicUrl: [],
                categoryId: '',
                isOnSale: 1,
                isNew: 1,
                isAppExclusive: 0,
                isLimited: 0,
                isHot: 0,
                goodsNumber: 1,
                retailPrice: '',
                marketPrice: '',
                categoryName: ''
            };
            $('#goodsDesc').editable('setHTML', '');
            vm.getCategory();
            vm.brands = [];
            vm.macros = [];
            vm.attributeCategories = [];
            vm.ggname = []
            vm.guigeArr = [{
                name: '',
                val: [{
                    name: '',
                    picUrl: ''
                }]
            }]
            vm.ggContent = ""
            vm.currenIdx = ''
            vm.currenI = ''
            vm.inputArr = []
            vm.goodsSpecificationList = []
                // vm.attribute = [];
            vm.getBrands();
            vm.getMacro();
            vm.getAttributeCategories();
            vm.getSpecification();
            // vm.getAttributes('');
        },
        update: function(event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.uploadList = [];
            vm.showguigearr = false
            vm.getInfo(id);
            vm.getMacro();
            vm.getAttributeCategories();
            vm.getGoodsGallery(id);
        },
        /**
         * 获取品牌
         */
        getBrands: function() {
            // Ajax.request({
            //     url: "../brand/queryAll",
            //     async: true,
            //     successCallback: function(r) {
            //         vm.brands = r.list;
            //         r.list.forEach(item => {
            //             if (item.id == vm.goods.brandId) {
            //                 vm.goods.brandName = item.name
            //             }
            //         })
            //     }
            // });

            let deptId = JSON.parse(localStorage.getItem('userInfo')).deptId
            Ajax.request({
                url: "../brand/brandBindList?deptId=" + deptId + "&limit=999999&page=1",
                type: 'get',

                contentType: "application/json",
                successCallback: function(r) {
                    console.log(vm.brands)
                    vm.brands = r.list;
                    r.list.forEach(item => {
                        if (item.id == vm.goods.brandId) {
                            vm.goods.brandName = item.name
                        }
                    })
                }
            });
        },

        /**
         * 获取单位
         */
        getMacro: function() {
            Ajax.request({
                url: "../sys/macro/queryMacrosByValue?value=goodsUnit",
                async: true,
                successCallback: function(r) {
                    vm.macros = r.list;
                }
            });
        },
        getGoodsGallery: function(id) { //获取商品顶部轮播图
            Ajax.request({
                url: "../goodsgallery/queryAll?goodsId=" + id,
                async: true,
                successCallback: function(r) {
                    vm.uploadList = r.list;
                }
            });
        },
        getAttributeCategories: function() {
            Ajax.request({
                url: "../attributecategory/queryAll",
                async: true,
                successCallback: function(r) {
                    vm.attributeCategories = r.list;
                }
            });
        },
        saveOrUpdate: function(event) {
            var url = vm.goods.id == null ? "../goods/save" : "../goods/update";
            vm.goods.goodsDesc = $('#goodsDesc').editable('getHTML');

            vm.goods.goodsImgList = vm.uploadList;

            vm.goods['goodsSpecificationList'] = vm.goods.id == null ? vm.guigeArr : vm.goodsSpecificationList
            vm.goods['productList'] = vm.inputArr

            vm.goods['guigeArr'] = JSON.stringify(vm.guigeArr)

            vm.goods['ggContent'] = JSON.stringify(vm.ggContent)
                // 修改市场价和零售价，库存
            vm.goods.goodsNumber = 0
            let temparr = []

            if (vm.goods.listPicUrl.length > 0 && vm.goods.listPicUrl instanceof Array) {
                temparr = vm.goods.listPicUrl.map(item => {
                    return item.url
                })
            }

            vm.goods['productList'].forEach(function(item, index) {
                vm.goods.goodsNumber += Number(item.goodsNumber)
                if (index === 0) {
                    vm.goods.retailPrice = item.retailPrice
                    vm.goods.marketPrice = item.marketPrice
                } else {
                    if (item.retailPrice < vm.goods.retailPrice) {
                        vm.goods.retailPrice = Number(item.retailPrice)
                    }
                    if (item.marketPrice < vm.goods.marketPrice) {
                        vm.goods.marketPrice = Number(item.marketPrice)
                    }
                }
            })

            vm.goods.updateUserDeptId = vm.userInfo.deptId
            vm.goods.updateUserId = vm.userInfo.userId
            vm.goods.createUserId = vm.userInfo.userId
            vm.goods.createUserDeptId = vm.userInfo.deptId

            vm.goods.listPicUrl = temparr.length > 0 ? temparr.join('#$#') : ''

            if (vm.goods['guigeArr'] == '[]' || vm.goods['ggContent'] == '""') {
                return layer.alert("商品规格和规格明细不能为空", { icon: 5 });
            }

            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.goods),
                successCallback: function(r) {
                    vm.goods.listPicUrl = []

                    alert('操作成功', function(index) {
                        vm.reload();
                    });
                }
            });
        },
        enSale: function() {
            // var id = getSelectedRow("#jqGrid");
            var ids = getSelectedRows("#jqGrid");


            if (ids == null) {
                return;
            }
            confirm('确定要上架选中的商品？', function() {
                Ajax.request({
                    type: "POST",
                    url: "../goods/enSale",
                    params: ids.join(','),
                    contentType: "application/json",
                    successCallback: function() {
                        alert('提交成功', function(index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        openSpe: function() {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '商品规格',
                content: '../shop/goodsspecification.html?goodsId=' + id
            })
        },
        openPro: function() {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '产品设置',
                content: '../shop/product.html?goodsId=' + id
            });
        },
        unSale: function() {
            var ids = getSelectedRows("#jqGrid");

            if (ids == null) {
                return;
            }

            function filterUnsale(ids) {
                return ids.filter(function(id) {
                    return $("#jqGrid").jqGrid('getRowData', id).isOnSale.indexOf('是') !== -1
                })
            }
            ids = filterUnsale(ids)
            if (ids.length === 0) {
                alert('商品已下架')
                return
            }
            confirm('确定要下架选中的商品？', function() {

                Ajax.request({
                    type: "POST",
                    url: "../goods/unSale",
                    contentType: "application/json",
                    params: ids.join(','),
                    successCallback: function(r) {
                        alert('操作成功', function(index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        del: function(event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function() {
                Ajax.request({
                    type: "POST",
                    url: "../goods/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function(r) {
                        alert('操作成功', function(index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        countProductSort: function(uuidLink) {
            if (!uuidLink) {
                return
            }
            var sort = uuidLink.split('_')
            var length = sort.length
            var val = 0
            sort.forEach(function(item, index) {
                var arr = item.split('-')
                val += arr[1] * Math.pow(10, length - index)
            })
            return val
        },
        getInfo: function(id) {

            vm.defaultList = []

            Ajax.request({
                url: "../goods/info/" + id,
                async: true,
                successCallback: function(r) {
                    vm.goods = r.goods;
                    var productList = r.goods.productList.sort(function(a, b) {
                        var a_uuid_sort = vm.countProductSort(a.uuidLink)
                        var b_uuid_sort = vm.countProductSort(b.uuidLink)
                        return a_uuid_sort - b_uuid_sort

                    })
                    vm.inputArr = productList
                    vm.goodsSpecificationList = r.goods.goodsSpecificationList
                    vm.guigeArr = JSON.parse(r.goods.guigeArr) || []
                    vm.ggContent = JSON.parse(r.goods.ggContent)
                    vm.ggname = []

                    vm.guigeArr.forEach(function(item) {
                        vm.ggname.push({
                            name: item.name
                        })
                    })
                    if (r.goods.listPicUrl) {
                        let temp = r.goods.listPicUrl.split('#$#')
                        let tmpArr = temp.map(item => {
                            return {
                                url: item,
                                name: item,
                                status: 'finished'
                            }
                        });
                        vm.goods.listPicUrl = tmpArr
                        vm.picList = tmpArr
                        vm.defaultList = tmpArr
                    } else {
                        vm.goods.listPicUrl = [];
                        vm.picList = [];
                    }

                    $('#goodsDesc').editable('setHTML', vm.goods.goodsDesc);
                    vm.getCategory();
                    vm.getSpecification();
                }
            });
        },
        reload: function(event) {
            this.getBrands();
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            let params = { 'name': vm.q.name }
            if (vm.q.brandId) {
                params['brandId'] = vm.q.brandId
            }
            $("#jqGrid").jqGrid('setGridParam', {
                postData: params,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        getCategory: function() {
            //加载分类树
            Ajax.request({
                url: "../category/queryAll",
                async: true,
                successCallback: function(r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    if (vm.goods.categoryId) {
                        var node = ztree.getNodeByParam("id", vm.goods.categoryId);
                        if (node) {
                            ztree.selectNode(node);
                            vm.goods.categoryName = node.name;
                        } else {
                            node = ztree.getNodeByParam("id", 0);
                            ztree.selectNode(node);
                            vm.goods.categoryName = node.name;
                        }
                    }

                }
            });
        },
        categoryTree: function() {
            openWindow({
                title: "选择类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function(index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级菜单
                    if (node[0].children) {
                        alert('请选择商品类型', function() {});
                    } else {
                        vm.goods.categoryId = node[0].id;
                        vm.goods.categoryName = node[0].name;
                        layer.close(index);
                    }
                }
            });
        },
        handleView: function(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove1(file) {
            let name = file.name
            let delIdx = ''
            this.goods.listPicUrl.forEach((item, i) => {
                    if (item.name == name) {
                        delIdx = i
                    }
                })
                // this.$refs.upload.fileList.splice(delIdx, 1);
            this.goods.listPicUrl.splice(delIdx, 1);
            this.picList.splice(delIdx, 1);
        },
        handleRemove: function(file) {
            // 从 upload 实例删除数据
            const fileList = this.uploadList;
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess: function(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.imgUrl = res.url;
            file.name = res.url;
            vm.uploadList.add(file);
        },
        handleBeforeUpload15() {
            const check = this.$refs.goodupload.fileList.length < 15;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 15 张图片。'
                });
            }
            return check;
        },
        handleBeforeUpload: function() {
            const check = this.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。'
                });
            }
            return check;
        },
        handleSubmit: function(name) {
            vm.showguigearr = !vm.validateInput()
            console.log(vm.showguigearr)
            vm.validateData(name, vm.saveOrUpdate)
        },
        validateData: function(name, cb) {
            handleSubmitValidate(vm, name, function() {
                var pass = true
                var item = vm.guigeArr.find(function(item) {
                    if (!item.name) {
                        pass = false
                        alert('商品规格请填写完整')
                    }
                    return !item.name
                })
                if (item) {
                    return pass && cb()
                }


                vm.guigeArr.forEach(function(item) {
                    item.val.forEach(function(i) {
                        if (!i.name || !i.picUrl) {
                            if (pass) {
                                alert('商品规格请填写完整')
                                pass = false
                            }
                        }
                    })
                });
                (pass && (!vm.showguigearr)) && cb()
            });
        },
        handleFormatError: function(file) {
            this.loading = false
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function(file) {
            this.loading = false
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大。'
            });
        },
        handleReset: function(name) {
            handleResetForm(this, name);
        },
        handleSuccessPicUrl: function(res, file) {
            // vm.goods.primaryPicUrl = file.response.url
            vm.goods.primaryPicUrl = file.response.url + window.fixImg + 'm_fixed,w_300,h_300';

        },
        handleSuccessListPicUrl: function(res, file) {
            vm.goods.listPicUrl = file.response.url;
        },

        eyeImageItemPicUrl: function(url) {
            eyeImage(url);
        },
        eyeImagePicUrl: function() {
            var url = vm.goods.primaryPicUrl;
            eyeImage(url);
        },
        eyeImageListPicUrl: function() {
            var url = vm.goods.listPicUrl;
            eyeImage(url);
        },
        eyeImage: function(e) {
            eyeImage($(e.target).attr('src'));
        }
    },
    mounted: function() {
        // this.transToGuigeArr()
        this.uploadList = this.$refs.upload.fileList;
        this.$nextTick(() => {
            this.getBrands()

        })
    }
});