<template>
  <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="商品品种/品类：">
          <treeselect
            :options="treeList"
            style="width: 200px;"
            :disable-branch-nodes="true"
            :show-count="true"
            :normalizer="normalizer"
            placeholder="请选择品种"
            v-model="form.type_id">
            <div slot="value-label" slot-scope="{ node }">{{ parseLabel(node) }}</div>
          </treeselect>
        </el-form-item>
        
        <!-- <el-form-item label="商品品牌：">
            <el-select v-model="form.brand_id" placeholder="商品品牌" filterable :disabled="disabled">
                <el-option v-for="item in brandList" :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="item.title"></el-input>
        </el-form-item>
        <el-form-item label="颜色/特性：">
          <el-input placeholder="颜色/特性" v-model="item.attribute"></el-input>
        </el-form-item>
        <el-form-item label="商品状态：">
          <el-select v-model="item.status" placeholder="下架（默认）">
            <el-option v-for="it in options" :key="it.id" :label="it.label" :value="it.id">
            </el-option>
          </el-select>
          <el-form-item label="商品成本：">
            <el-input v-model="item.cost" placeholder="商品成本">
            </el-input>
          </el-form-item>
        </el-form-item>
        <div>
          <!-- <el-form-item label="商品数量：">
            <el-input v-model="item.num" placeholder="商品数量">
            </el-input>
          </el-form-item> -->
          
          <el-form-item label="可售库存：">
            <el-input v-model="item.sale_stock" placeholder="可售库存">
            </el-input>
          </el-form-item>
          <el-form-item label="最终编码：">
            <el-input v-model="item.external_sku_id" placeholder="不输入自动生成"></el-input>
          </el-form-item>
          <el-button type="danger" @click="handleDelete(i)" icon="el-icon-delete">删除</el-button>
        </div>
      </div>

      <el-form-item>
        <el-button type="success" @click="toAddSku()" icon="el-icon-plus">增加规格</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>
</template>

<script>
  import { addGoods, goodsList, 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 {
        lid: "",
        gid: "",
        brandList: [],
        treeList: [],
        goodschoose: [],
        // 规格列表
        skus: [],
        // 增加商品表单
        form: {
          goods_id: "",
          title: "",
          img_url: "",
          type_id: null, // Treeselect组件要求空值为null
          brand_id: "",
          goods_code: ""
        },
        // 商品状态
        options: [
          { id: 0, label: "下架" },
          { id: 1, label: "在售" }
        ],
        file: [],
        disabled: false
      }
    },
    mounted() {
      this.getGoods_types()
      this.getGoodsBrand()
      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: {
      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.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
        }
        updata.type_id = updata.type_id || ''
        addGoods(updata).then((res) => {
          if (res.statusText === "OK") {
            this.$message({
              message: "商品添加成功！",
              type: "success",
            });
            this.$router.push("/GOODS_LIST");
          }
        })
      },
      toAddSku() {
        if(!this.form.type_id) {
          this.$message({ message: "请选择商品品种/品类", type: "error" })
          return
        }
        this.handleAdd()
      },
      // 增加一个商品规格
      handleAdd() {
        let sku = {
          title: '',
          external_sku_id: '',
          status: 0,
          num: 0,
          cost: 0,
          sale_stock: 9999,
          reserve: 0,
          attribute: ''
        };
        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 = {};
        }
      },
      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
      }
    }
  }
</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>
