<template>
  <div class="goods-info">
    <el-form :model="goodsInfoForm" :rules="goodsInfoRules" ref="goodsInfoForm" label-width="150px" class="demo-goodsInfoForm" size="small">
      <el-form-item label="商品分类：" prop="categoryStr">
        <el-input style="width:400px;" v-model="goodsInfoForm.categoryStr" :disabled="true"></el-input>
<!--        <span class="type-text-span">{{ goodsInfoForm.categoryStr }}</span>-->
        <el-link class="edit-type-span el-icon-edit" type="primary" :underline="false" @click="editType">修改所在类目</el-link>
        <span class="tip-span">该商品所在类目须支持七天无理由退货</span>
      </el-form-item>

      <el-form-item label='商品标题：' prop="goodsName">
        <el-input v-model="goodsInfoForm.goodsName" placeholder="请输入商品标题" style="width:400px;"></el-input>
        <span class="tip-span ml20">商品名称限制在30字以内，不要填写与商品无关的词</span>
      </el-form-item>

      <el-form-item label="商品产地：" prop="producingArea">
        <el-select v-model="goodsInfoForm.producingArea" placeholder="请选择商品产地" style="width: 400px;">
          <el-option
            v-for="item in areaOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品发货地：" prop="fhd">
        <el-select v-model="goodsInfoForm.fhd" placeholder="请选择商品发货地" style="width: 400px;">
          <el-option
            v-for="item in areaOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属品牌：" prop="goodsBrand">
        <el-select v-model="goodsInfoForm.goodsBrand" placeholder="请选择商品品牌" style="width: 400px;">
          <el-option
            v-for="item in brandOptions"
            :key="item.id"
            :label="item.brand_cn"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toBrand">新增品牌</el-link>
      </el-form-item>

      <el-form-item label='市场参考价链接：'>
        <el-input v-model="goodsInfoForm.lj" placeholder="请输入京东或者淘宝的商品链接" style="width:400px;"></el-input>
      </el-form-item>

      <el-form-item label='商品编码：'>
        <el-input v-model="goodsInfoForm.spbm" placeholder="请输入商品编码（非必须）" style="width:400px;"></el-input>
      </el-form-item>

      <el-form-item label="商品图片：" prop="sptp">
        <span class="tip-span" style="display: block;line-height: 34px;">商品图片最多上传9张，默认第一张为主图 <span>单张图片需限制在2M以内，可上传png、jpg格式，尺寸要求为正方形</span></span>
        <el-upload
          class="upload-img"
          list-type="picture-card"
          action="#"
          :limit="1"
          :on-exceed="limitImg9"
          :http-request="uploadGoodsImg"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="goodsImgFileList"
        ><i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="goodsImgVisible">
          <img width="100%" :src="goodsImgUrlDialog" alt="">
        </el-dialog>
      </el-form-item>

    </el-form>

    <!-- 修改 商品分类目录 -->
    <el-dialog
      v-loading="loadingSSQ"
      class="add-workorder-dialog"
      title="修改商品分类"
      :visible.sync="editGoodsTypeDialog"
      :destroy-on-close="true"
      :before-close="cancelType"
      width="60%"
      center
    >

<!--        <p>当前所选类目：<span></span></p>-->
      <el-cascader-panel v-show="editGoodsTypeDialog" v-model="SSQGoodsList" :props='goodsprops' @change="SSQGoodsChange" ref="ssqGoodsCascader"></el-cascader-panel>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelType" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveType" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { GetCategory, GetFreight, UploadImg } from '@/api/module/goods'
  import { getAreaList } from '@/api/module/retreat/address';
  import { getBrandsInf } from '@/api/module/brand/brand'
  export default {
    name: 'goods',
    props: {
      goodsinfodata: {
        type: Object,
        required: true
      }
    },
    data() {
      let categoryIdCheck = (rule, value, callback) => {
        if (this.goodsImgFileList.length < 1) {
          callback(new Error("请上传商品图片"));
        } else {
          callback();
        }
      };
      return {
        //loading: false,
        // categoryStr: '',
        goodsInfoDataClone: {},
        areaOptions: [], // 地址 省
        brandOptions: [], // 商品品牌
        goodsInfoForm: {
          categoryStr: '', // 商品分类 地址拼接
          categoryList: [],
          goodsName: '',
          producingArea: [], // 产地
          fhd: [], // 发货地
          goodsBrand: [], // 品牌
          sptp: '' // 商品图片
        },
        goodsInfoRules: {
          categoryStr: [{required: true, message: '商品分类不能为空', trigger: 'blur'},],
          goodsName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 3, max: 30, message: '商品标题限制在30字以内', trigger: 'blur'}
          ],
          producingArea:[{required: true, message: '请选择商品产地', trigger: 'change'}],
          fhd: [{required: true, message: '请选择商品发货地', trigger: 'change'}],
          goodsBrand: [{required: true, message: '请选择商品品牌', trigger: 'change'}],
          sptp: [{required: true, message: '请上传商品图片', validator: categoryIdCheck}]
        },
        goodsImgFileList: [], // 商品图片地址 集合list
        goodsImgVisible: false, // 图片能否预览
        goodsImgUrlDialog: '',

        /* 修改 商品分类 */
        loadingSSQ: false,
        editGoodsTypeDialog: false,
        SSQGoodsList: [], // 省市区 子组件goods的
        goodsprops: {
          expandTrigger: 'click',
          lazy: true,
          lazyLoad: this.lazyLoad,
          value: "id",
          label: 'name',
          leaf: 'leaf'
        },

      } // return end
    },
    components: {},
    watch: {
      // serviceagsTags: {
      //   handler(val, oldVal) {
      //     this.$set(this.goodsInfoForm, 'serviceagsTags', val)
      //   },
      //   deep: true
      // },
    },
    created() {
      // 深拷贝一份最开始的数据，为初始化准备
      this.goodsInfoDataClone = this.deepClone(this.goodsinfodata);
      this.goodsInfoForm = this.goodsinfodata
      // console.log("父组件传过来的",this.goodsinfodata)
      // console.log("1111",this.goodsInfoForm)
      // 获取 省
      this.getArea();
      // 获取 商品品牌
      this.getBrands();

    },
    mounted() {
      // this.getCategory();
      // this.getFreight();
      // this.getBrands();
    },
    methods: {
      // 获取 省
      getArea() {
        let limboNode = {
          pid: 0
        };
        getAreaList(limboNode).then( res=> {
          if(res.data) {
            this.areaOptions = res.data;
          }else {
            this.areaOptions = [];
          }
        });
      },
      // 获取 商品品牌
      getBrands() {
        getBrandsInf().then( res => {
          if(res.data) {
            this.brandOptions = res.data.data;
          }else {
            this.brandOptions = [];
          }
        });
      },
      /* 修改 商品分类 类目 */
      editType() {
        this.SSQGoodsList = [];
        this.editGoodsTypeDialog = true;
        this.SSQGoodsList = this.goodsInfoForm.categoryList
        console.log(222,this.SSQGoodsList);
      },
      lazyLoad(node, resolve) {
        this.getSSQArea(node, resolve);
      },
      getSSQArea(node, resolve) {
        const level = node.level;
        let limboNode = {};
        if(level === 0) {
          //debugger
          limboNode = {pid: 0}
        }
        if(level === 1) {
          //debugger
          limboNode = { pid: node.value };
        }
        if(level === 2) {
          limboNode = { pid: node.value };
        }
        //this.loadingSSQ = true;
        getAreaList(limboNode).then(res => {
          let result = {};
          if (level === 0) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name;
              item.children=[];
              item.leaf = 0;  // 可以控制 是否有下级   值为true都不行，必须等于0
            })
          }
          if (level === 1) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.children=[];
              //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
              item.leaf = 0
            })
          }
          if (level === 2) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.leaf = 1;
            })
          }
          resolve(result)
          //this.loadingSSQ = false;
        });
      },
      SSQGoodsChange(value) {
        //this.SSQGoodsList = value;
      },
      // 确认 修改 商品分类
      saveType() {

      },
      // 取消 修改 商品分类
      cancelType() {
        this.editGoodsTypeDialog = false;
      },


      // 上传 商品图片，限制 9 张
      limitImg9() {
        this.$message({ message: '最多上传9张图片', type: 'warning' })
      },
      // 上传 商品图片
      uploadGoodsImg(param) {
        this.getBase64(param.file).then( res => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"image":this.Base64img};
          //console.log(213,data);

          UploadImg(data).then( res=> {
            console.log(217,res);
            let urlObj = {'url': ''};
            if(res.data) {
              urlObj.url = res.data.data.imageUrl;
              this.goodsImgFileList.push(urlObj);
              this.$message({type:'success',message:'图片上传成功'});
              // 只清除一次，不浪费哦
              if(this.goodsImgFileList.length === 1) {
                this.$refs.goodsInfoForm.clearValidate('sptp');
              }
            }
          });
        });
      },
      // 商品信息 子组件 form表单校验, 在父组件中被调用
      validateGoodsInfoForm () {
        let flag = null
        this.$refs['goodsInfoForm'].validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
        return flag
      },
      // 商品图片 预览
      handlePictureCardPreview(file) {
        this.goodsImgUrlDialog = file.url;
        this.goodsImgVisible = true;
      },
      // 删除 商品图片
      handleRemove(file) {
        for (let i = 0; i < this.goodsImgFileList.length; i++) {
          if (file.uid === this.goodsImgFileList[i].uid) {
            this.goodsImgFileList.splice(i, 1)
          }
        }
        if(this.goodsImgFileList.length === 0) {
          this.$refs.goodsInfoForm.validateField('sptp')
        }else {
          this.$refs.goodsInfoForm.clearValidate('sptp');
        }
      },

      // 维护品牌
      toBrand() {
        this.$router.push({path: '/system/shop/brand'});
      },

      // 通用 方法
      // 图片转换为 base64
      getBase64(file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function () {
            imgResult = reader.result;
          };
          reader.onerror = function (error) {
            reject(error);
          };
          reader.onloadend = function () {
            resolve(imgResult);
          };
        });
      },



    } // methods end
  }
</script>
<style scoped>
  ul {
    padding: 0;
  }
  .goods-info {
    padding: 15px 0px;
    margin-top: 18px;
  }
  .type-text-span {
    display: inline-block;
    width: 400px;
    /*margin: 0 20px 0;*/
  }
.edit-type-span {
  display: inline-block;
  cursor: pointer;
  margin: 0 20px;
}
/* 一般提示性文字 */
.tip-span {
  color: #909399;
  font-size: 12px;
}
  /deep/.el-form-item {
    margin-bottom: 20px;
  }
</style>
