<template>
  <div>
    <el-card class="box-card">
      <div class="goods" style="margin: 20px">
        <div class="add-item-info" style="margin-bottom: 10px; margin-left: 52px">
          <div>
            <div style="font-size: 14px">商品列表：</div>
            <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>
          </div>
          <span style="font-size: 14px">商品图片：
            <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="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </span>
        </div>

        <!-- 编辑按钮进入显示 -->
        <el-form ref="form" :inline="true" :model="form" v-if="goodsData != ''">
          <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="商品种类：">
              <el-select v-model="goodsData.goods.type_id" placeholder="商品种类" filterable>
                <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="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.sku_code" placeholder="商品编码">
              </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>
            </div>
          </div>
          <div class="btn">
            <el-form-item>
              <el-button type="primary" @click="Edititem()">保存</el-button>
              <el-button plain @click="cancel()">取消</el-button>
            </el-form-item>
          </div>
        </el-form>

        <!-- 新建商品进入显示 -->
        <el-form ref="form" :inline="true" :model="form" v-if="goodsData == ''">
          <div>
            <el-form-item label="商品名称：">
              <el-input placeholder="商品名称" v-model="form.title" :disabled="true" v-if="isShow"></el-input>
              <el-input placeholder="商品名称" v-model="form.title" v-else></el-input>
            </el-form-item>
            <el-form-item label="商品编码：">
              <el-input placeholder="商品编码" v-model="form.goods_code" :disabled="true" v-if="isShow"></el-input>
              <el-input placeholder="商品编码" v-model="form.goods_code" v-else></el-input>
            </el-form-item>
            <el-form-item label="商品种类：">
              <el-select v-model="form.type_id" placeholder="商品种类" filterable>
                <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>
                <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">
            <span style="margin-right: -15px">{{ i + 1 }}.</span>
            <el-form-item label="商品规格：">
              <el-input placeholder="商品规格" v-model="skus[i].title"></el-input>
            </el-form-item>
            <span class="addto" @click="handleAdd()">+</span>
            <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-button type="primary" @click="handleDelete(i)">删除</el-button>
            </div>
          </div>
          <div class="btn">
            <el-form-item>
              <el-button type="primary" @click="handleSave()">保存</el-button>
              <el-button plain @click="cancel()">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    addGoods,
    checkGoods,
    goodsList,
    updateGoods,
    imgUpload,
  } from "../../../api/goods.js";
  import { goods_types, Brand_goods_types } from "../../../api/rankingData.js";
  export default {
    data() {
      return {
        imgs: [],
        gallery: "",
        imageUrl: "",
        lid: "", // 选择的商品列表id
        gid: "", // 商品id
        brand: [], // 品牌列表
        cate: [], // 种类列表
        goodschoose: [], // 商品列表
        goodsID: "", //进入页面是否有商品id
        goodsData: [], //编辑按钮进入获取的商品数据
        // 规格列表
        skus: [
          {
            title: "",
            sku_code: "",
            status: "0",
            num: "0",
            cost: "0",
            reserve: "0",
          },
        ],

        // 增加商品表单
        form: {
          goods_id: "",
          title: "",
          img_url: "",
          type_id: "",
          brand_id: "",
          goods_code: "",
        },
        // 商品状态
        options: [
          {
            id: "0",
            label: "下架",
          },
          {
            id: "1",
            label: "在售",
          },
          {
            id: "2",
            label: "预警",
          },
        ],
        file: [],
        isShow: false,
        URL: "",
      };
    },

    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;
          if (this.goodsData.length !== 0) {
            this.goodsData.goods.img_url = res.data.resource;
          }
        });
      },

      // 查看一个商品
      handleUpdate() {
        this.gid = this.$route.query;
        if (this.gid.id) {
          checkGoods(this.gid.id).then((res) => {
            const data = res.data.data;
            const sku = this.skus[0];
            const list = {};
            Object.keys(data).map((key) => {
              Object.keys(sku).map((i) => {
                if (key == i) {
                  list[i] = data[key];
                }
              });
            });
          });
        }
      },

      // 商品列表
      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.updateForm();
            this.$router.push("/GOODS_LIST");
          }
        });
      },

      // 修改成功后重置表单
      updateForm() {
        this.form = {
          title: "",
          img_url: "abc.jpg",
          type_id: "",
          brand_id: "",
          goods_code: "",
        };
        this.skus = [
          {
            title: "",
            sku_code: "",
            status: "",
            num: "",
            cost: "",
          },
        ];
      },

      // 增加一个商品规格
      handleAdd() {
        this.skus.push({
          title: "",
          sku_code: "",
          status: "0",
          num: "",
          cost: "",
        });
      },

      // 删除一个商品规格
      handleDelete(index) {
        this.skus.splice(index, 1);
      },


      // 商品列表页进入带数据表单
      getgoodsidData() {
        let id = this.bigID;
        checkGoods(id).then((res) => {
          this.goodsData = res.data.data;
        });
      },

      // 编辑确认请求
      Edititem() {
        let id = this.bigID;
        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,
          sku_code: this.goodsData.sku_code,
          status: this.goodsData.status,
          num: this.goodsData.num,
          cost: this.goodsData.cost,
        };
        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(id, updateData).then((res) => {
          this.$router.push("/GOODS_LIST");
          this.$message({
            message: "商品编辑成功！",
            type: "success",
          });
        });
      },

      // 取消按钮
      cancel() {
        this.$router.push("/GOODS_LIST");
      },

      onchange(value) {
        if (value !== "") {
          this.isShow = true;
        }
        if (value === "") {
          this.isShow = false;
          this.form = {};
        }
      },
    },

    created() {
      this.goodsID = sessionStorage.getItem("商品ID");
      this.bigID = sessionStorage.getItem("ID");
    },

    mounted() {
      this.gid = this.$route.query;
      // 获取商品种类
      goods_types().then((res) => {
        this.cate = res.data.data;
      });
      // 获取商品品牌
      Brand_goods_types().then((res) => {
        this.brand = res.data.data;
      });
      this.handleList();
      this.handleUpdate();
      this.getgoodsidData();
    },

    beforeDestroy() {
      sessionStorage.removeItem("商品ID"); //销毁内存中的商品ID
      sessionStorage.removeItem("ID"); //销毁内存中的ID
    },
  };
</script>

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

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

  .addto {
    display: inline-block;
    width: 30px;
    height: 30px;
    background-color: blue;
    color: #fff;
    font-size: 25px;
    text-align: center;
    line-height: 30px;
    border-radius: 5px;
    margin-top: 4px;
  }

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