<template>
    <div>
        <el-card class="box-card">
            <el-form ref="form" :inline="true" :model="goodsData" label-position="right" label-width="120px">
                <!-- <div>
                    <el-form-item label="商品列表：">
                        <el-select v-model="goodsData.goods_id" placeholder="选择商品" filterable :disabled="true">
                            <el-option v-for="item in goodschoose" :key="item.id" :label="item.title" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div> -->
                <!-- <div>
                    <el-form-item label="商品图片：">
                        <el-upload class="avatar-uploader" action="#" :limit="1" :auto-upload="false"
                            :show-file-list="true" list-type="picture-card" :on-change="handleAvatarSuccess">
                            <img v-if="goodsData.goods.img_url" :src="goodsData.goods.img_url" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div> -->
                <div>
                    <!-- <el-form-item label="商品名称：">
                        <el-input placeholder="商品名称" v-model="goodsData.goods.title"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item label="商品编码：">
                        <el-input placeholder="商品编码" v-model="goodsData.goods.goods_code"></el-input>
                    </el-form-item> -->
                    <el-form-item label="商品品种/品类：">
                        <treeselect
                            :options="treeList"
                            style="width: 200px;"
                            :disable-branch-nodes="true"
                            :show-count="true"
                            :normalizer="normalizer"
                            placeholder="请选择品种"
                            v-model="goodsData.goods.type_id">
                            <div slot="value-label" slot-scope="{ node }">{{ parseLabel(node) }}</div>
                        </treeselect>
                    </el-form-item>
                    
                    <!-- <el-form-item label="商品品牌：">
                        <el-select v-model="goodsData.goods.brand_id" placeholder="商品品牌" filterable>
                            <el-option v-for="item in brand" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                </div>
                <div>
                    <el-form-item label="规格名称：">
                        <el-input placeholder="规格名称" v-model="goodsData.title"></el-input>
                    </el-form-item>
                    <el-form-item label="最终编码：">
                        <el-input v-model="goodsData.external_sku_id" placeholder="规格编码" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="颜色/特性：">
                        <el-input placeholder="颜色/特性" v-model="goodsData.attribute"></el-input>
                    </el-form-item>
                    <el-form-item label="商品状态：">
                        <el-select v-model="goodsData.status">
                            <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <div>
                        <!-- <el-form-item label="商品数量：">
                            <el-input v-model="goodsData.num" placeholder="商品数量">
                            </el-input>
                        </el-form-item> -->
                        <el-form-item label="商品成本：">
                            <el-input v-model="goodsData.cost" placeholder="商品成本">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="在售库存：">
                            <el-input v-model="goodsData.sale_stock" placeholder="在售库存">
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
                <!-- <div>
                    <el-form-item label="规格图片：">
                        <div class="shop-sku-img">
                            <div class="shop" v-for="item in goodsData.thumb_url" :key="item.shop_id">
                                <div class="shop-name">{{ item.shop_name }}</div>
                                <div>
                                    <el-upload class="avatar-uploader" action="/api/upload" :limit="1"
                                        accept="image/png,image/jpg,image/jpeg" :show-file-list="false"
                                        list-type="picture-card" :data="{ shop_id: item.shop_id }" name="uploadFile"
                                        :on-success="handleShopImgSuccess" :before-upload="beforeAvatarUpload">
                                        <img v-if="item.img_url" :src="item.img_url" class="avatar" />
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </div> -->
                <div class="btn">
                    <el-form-item label=" ">
                        <el-button type="primary" @click="Edititem()">保存</el-button>
                        <el-button plain @click="cancel()">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { checkGoods, goodsList, updateGoods, imgUpload } from '@/api/goods.js'
import { goods_types, Brand_goods_types } from '@/api/rankingData.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
    components: { Treeselect },
    data() {
        return {
            brand: [], // 品牌列表
            treeList: [], // 种类列表
            goodschoose: [], // 商品列表
            skuId: 0, // 商品id
            // 增加商品表单
            goodsData: {
                goods_id: "",
                title: "",
                status: "",
                num: "",
                cost: "",
                sale_stock: '',
                external_sku_id: "",
                thumb_url: [],
                attribute: '',
                goods: {
                    img_url: "",
                    title: "",
                    type_id: null,
                    brand_id: "",
                    goods_code: "",
                }
            },
            // 商品状态
            options: [
                {
                    id: "0",
                    label: "下架",
                },
                {
                    id: "1",
                    label: "在售",
                },
                {
                    id: "2",
                    label: "预警",
                },
            ],
            file: [],
            shopList: []
        };
    },
    methods: {
        getGoods_types() {
            let params = {
                parent_id: 0
            }
            goods_types(params).then((res) => {
                this.treeList = JSON.parse(JSON.stringify(res.data.data).replace(/name/g, "label"))
            })
        },
        getGoodsBrand() {
            Brand_goods_types({per_page: 999}).then((res) => {
                this.brandList = res.data.data
            })
        },
        //图片上传
        handleAvatarSuccess(res, files) {
            let formData = new FormData();
            files.forEach((file) => {
                formData.append("uploadFile", file.raw); //文件
            });
            let requestConfig = {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            };
            imgUpload(formData, requestConfig).then((res) => {
                this.goodsData.goods.img_url = res.data.resource;
            });
        },
        handleShopImgSuccess(res) {
            this.goodsData.thumb_url.forEach((val, key) => {
                if (val.shop_id == res.shop_id) {
                    this.goodsData.thumb_url[key].img_url = res.resource;
                }
            })
        },
        beforeAvatarUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error('上传头像图片大小不能超过 1MB!');
                return false;
            }
            const isSize = new Promise(function (resolve, reject) {
                let width = 1200;
                let height = 1200;
                let _URL = window.URL || window.webkitURL;
                let img = new Image();
                img.onload = function () {
                    let valid = img.width <= width && img.height <= height;
                    valid ? resolve() : reject();
                }
                img.src = _URL.createObjectURL(file);
            }).then(() => {
                return file;
            }, () => {
                this.$message.error('图片尺寸限制为1200 x 1200，大小不可超过1MB')
                return Promise.reject();
            });

            return isSize;
        },
        // 商品列表
        handleList() {
            goodsList().then((res) => {
                this.goodschoose = res.data.data;
            });
        },
        // 商品列表页进入带数据表单
        getGoodsSkuData() {
            checkGoods(this.skuId).then((res) => {
                this.goodsData = res.data.data
                this.goodsData.goods.type_id = this.goodsData.goods.type_id || null
            });
        },
        // 编辑确认请求
        Edititem() {
            let goods = {
                title: this.goodsData.goods.title,
                img_url: this.goodsData.goods.img_url,
                type_id: this.goodsData.goods.type_id || '',
                brand_id: this.goodsData.goods.brand_id,
                goods_code: this.goodsData.goods.goods_code,
            };
            let sku = {
                title: this.goodsData.title,
                external_sku_id: this.goodsData.external_sku_id,
                status: this.goodsData.status,
                num: this.goodsData.num,
                cost: this.goodsData.cost,
                sale_stock: this.goodsData.sale_stock,
                thumb_url: this.goodsData.thumb_url,
                attribute: this.goodsData.attribute
            };
            if (sku.status == "下架") {
                sku.status = 0;
            } else if (sku.status == "在售") {
                sku.status = 1;
            } else if (sku.status == "预警") {
                sku.status = 2;
            }
            let updateData = {
                goods_id: this.goodsData.goods_id,
                goods,
                sku,
            };
            updateGoods(this.skuId, updateData).then((res) => {
                this.$message({
                    type: "success",
                    message: "编辑成功"
                })
                this.$router.push("/GOODS_LIST");
            });
        },
        // 取消按钮
        cancel() {
            this.$router.push("/GOODS_LIST");
        },
        normalizer(node) {
            if ((!node.children || (node.children && node.children.length == 0)) && node.level == 1) {
            node.isDisabled = true
            }
            return node
        },
        parseLabel(node) {
            console.log(node)
            let text = ''
            text += node.parentNode ? node.parentNode.label + ' / ' : ''
            text += node.raw ? node.raw.label : ''
            return text
        }
    },
    created() {
        this.skuId = parseInt(this.$route.query.id);
    },
    mounted() {
        this.getGoods_types()
        this.getGoodsBrand()
        this.handleList();
        this.getGoodsSkuData();
    }
};
</script>

<style scoped>
.el-upload--picture-card {
    width: 50px;
    height: 50px;
}

/* 分割 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
}

.avatar {
    width: 148px;
    height: 148px;
    display: block;
}

.shop-sku-img {
    display: flex;

}

.shop-sku-img .shop {
    margin-right: 20px;
    margin-bottom: 20px;
}

.shop-sku-img .shop .shop-name {
    text-align: center;
}
</style>
