<template>
    <div>
        <el-card class="box-card">
            <!-- 新增商品进入显示 -->
            <el-form ref="form" :inline="true" :model="form">
                <div>
                    <el-form-item label="商品列表：">
                        <el-select v-model="lid" placeholder="选择商品" @change="onchange" filterable>
                            <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-image v-if="disabled" style="width: 148px; height: 148px" :src="form.img_url" fit="cover">
                        </el-image>
                        <el-upload v-else class="avatar-uploader" action="#" :limit="1" :auto-upload="false"
                            :show-file-list="false" list-type="picture-card" :on-change="handleAvatarSuccess">
                            <img v-if="form.img_url" :src="form.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="form.title" :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="商品编码：">
                        <el-input placeholder="商品编码" v-model="form.goods_code" :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="商品种类：">
                        <el-select v-model="form.type_id" placeholder="商品种类" filterable :disabled="disabled">
                            <el-option v-for="item in cate" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品品牌：">
                        <el-select v-model="form.brand_id" placeholder="商品品牌" filterable :disabled="disabled">
                            <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 v-for="(item, i) in skus" :key="i" class="skuBox">
                    <div class="tit">规格{{ i + 1 }}</div>
                    <el-form-item label="商品规格：">
                        <el-input placeholder="商品规格" v-model="skus[i].title"></el-input>
                    </el-form-item>
                    <el-form-item label="规格编码：">
                        <el-input v-model="skus[i].sku_code" placeholder="商品编码">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="商品状态：">
                        <el-select v-model="skus[i].reserve" placeholder="下架（默认）">
                            <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="skus[i].num" placeholder="商品数量">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="商品成本：">
                            <el-input v-model="skus[i].cost" placeholder="商品成本">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="在售库存：">
                            <el-input v-model="skus[i].sale_stock" placeholder="在售库存">
                            </el-input>
                        </el-form-item>
                        <el-button type="danger" @click="handleDelete(i)">删除</el-button>
                    </div>
                </div>

                <el-form-item>
                    <el-button type="success" @click="handleAdd()">增加规格</el-button>
                </el-form-item>
                
                <div style="margin-top: 30px;">
                    <el-form-item>
                        <el-button type="primary" @click="handleSave()">保存</el-button>
                        <el-button plain @click="cancel()">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { addGoods, goodsList, imgUpload } from "../../../api/goods.js";
import { goods_types, Brand_goods_types } from "../../../api/rankingData.js";
export default {
    data() {
        return {
            lid: "", // 选择的商品列表id
            gid: "", // 商品id
            brand: [], // 品牌列表
            cate: [], // 种类列表
            goodschoose: [], // 商品列表
            // 规格列表
            skus: [],
            // 增加商品表单
            form: {
                goods_id: "",
                title: "",
                img_url: "",
                type_id: "",
                brand_id: "",
                goods_code: "",
            },
            // 商品状态
            options: [
                {
                    id: "0",
                    label: "下架",
                },
                {
                    id: "1",
                    label: "在售",
                },
                {
                    id: "2",
                    label: "预警",
                },
            ],
            file: [],
            disabled: false,
        };
    },
    mounted() {
        let page = {
            per_page: 999,
        };
        // 获取商品种类
        goods_types(page).then((res) => {
            this.cate = res.data.data;
        });
        // 获取商品品牌
        Brand_goods_types(page).then((res) => {
            this.brand = res.data.data;
        });
        this.handleList();
        this.handleAdd();
    },
    watch: {
        lid: {
            handler(newVal, oldVal) {
                if (newVal) {
                    this.goodschoose.forEach((item) => {
                        if (item.id == newVal) {
                            this.form = { ...item };
                        }
                    });
                }
            },
            deep: true, // 深度监听
            immediate: true, // 第一次改变就执行
        },
    },
    methods: {
        //图片上传
        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.form.img_url = res.data.resource;
            });
        },
        // 商品列表
        handleList() {
            goodsList().then((res) => {
                this.goodschoose = res.data.data;
                this.goodschoose = [
                    {
                        title: "",
                        id: "",
                    },
                    ...this.goodschoose,
                ];
            });
        },
        // 添加商品
        handleSave() {
            const goods = this.form;
            const skus = this.skus;
            const updata = {
                ...goods,
                goods_id: this.lid,
                skus: skus,
            };
            addGoods(updata).then((res) => {
                if (res.statusText === "OK") {
                    this.$message({
                        message: "商品添加成功！",
                        type: "success",
                    });
                    this.$router.push("/GOODS_LIST");
                }
            });
        },
        // 增加一个商品规格
        handleAdd() {
            let sku = {
                title: "",
                sku_code: "",
                status: "0",
                num: "0",
                cost: "0",
                sale_stock: 0,
                reserve: "0",
            };
            this.skus.push(sku);
        },
        // 删除一个商品规格
        handleDelete(index) {
            this.skus.splice(index, 1);
        },
        // 取消按钮
        cancel() {
            this.$router.push("/GOODS_LIST");
        },
        onchange(value) {
            this.disabled = value !== "";
            if (!this.disabled) {
                this.disabled = false;
                this.form = {};
            }
        },
    },
};
</script>

<style scoped lang="scss">
.skuBox{
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    padding: 15px 0;
    margin-bottom: 15px;
    background-color: #f3f3f3;
    .tit{
        padding-left: 40px;
        font-weight: 600;
        font-size: 15px;
        margin-bottom: 15px;
    }
}
.el-upload--picture-card {
    width: 50px;
    height: 50px;
}

.el-form-item {
    margin-left: 40px;
}

/* 分割 */
.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;
}
</style>
