<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:420px;" v-model="goodsInfoForm.categoryStr" :disabled="true"></el-input>
        <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="goods_name">
        <el-input v-model="goodsInfoForm.goods_name" placeholder="请输入商品标题" style="width:420px;"></el-input>
        <span class="tip-span ml20">商品名称限制在30字以内，不要填写与商品无关的词</span>
      </el-form-item>

      <el-form-item label='商品关键词：' prop="goods_des">
        <el-input v-model="goodsInfoForm.goods_des" placeholder="请输入商品关键词" style="width:420px;"></el-input>
        <span class="tip-span ml20">关键词之间用 <strong>英文逗号</strong> 分开，最多可以添加5个</span>
      </el-form-item>

      <el-form-item label="商品产地：" prop="producing_area">
        <el-select v-model="goodsInfoForm.producing_area" placeholder="请选择商品产地" style="width: 420px;">
          <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="deliver_area">
        <el-select v-model="goodsInfoForm.deliver_area" placeholder="请选择商品发货地" style="width: 420px;">
          <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="unit">
        <el-input v-model="goodsInfoForm.unit" placeholder="请输入商品单位" style="width:420px;"></el-input>
<!--        <span class="tip-span ml20">关键词之间用逗号分开，最多可以添加5个</span>-->
      </el-form-item>

      <el-form-item label="所属品牌：" prop="goods_brand">
        <el-select v-model="goodsInfoForm.goods_brand" placeholder="请选择商品品牌" style="width: 420px;">
          <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='市场参考价链接：' prop="web_url">
        <el-input v-model="goodsInfoForm.web_url" placeholder="请输入京东或者淘宝的商品链接" style="width:420px;"></el-input>
      </el-form-item>

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

      <el-form-item label="商品图片：" prop="imgs">
        <span class="tip-span" style="display: block;line-height: 34px;">
          <i style="margin: 10px;">{{ goodsImgFileList.length }} / 5</i>
          商品图片最多上传5张，默认第一张为主图
          <span style="margin-left: 20px;">单张图片需限制在2M以内，可上传png、jpg格式，尺寸要求为800 * 800</span>
        </span>
        <el-upload
          class="upload-img"
          list-type="picture-card"
          action="#"
          :limit="5"
          :on-exceed="limitImg5"
          :before-upload="beforeUpGoodsImg"
          :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-cascader-panel v-model="SSQList" :props='props' @change="SSQChange" ref="ssqCascader"></el-cascader-panel>-->
    <el-dialog
      v-loading="loadingSSQ"
      class="add-workorder-dialog"
      title="修改商品分类"
      :visible.sync="editGoodsTypeDialog"
      :before-close="cancelType"
      destroy-on-close
      width="60%"
      center
    >
      <el-cascader-panel v-show="editGoodsTypeDialog" v-model="SSQGoodsList" :props='goodsprops' :options="fuckoptions" @active-item-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 { NewGetCategory, GetFreight, UploadImg } from '@/api/module/goods'
  import { getBrandsInf } from '@/api/module/brand/brand'
  import { getAreaList } from '@/api/module/retreat/address'
  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();
        }
      };
      let goodsDecCheck = (rule, value, callback) => {
        if(!value) {
          callback(new Error("商品关键词，不能为空"));
        } else {
          if( value.indexOf('，') > -1 ) {
            callback(new Error("商品关键词，不能有中文状态下的逗号，请再次检查"));
          }
          // 如果包含了，英文逗号，说明有多个，就校验个数
          if( value.indexOf(',') > -1 ) {
            let arrLength = value.split(',').length;
            console.log(value.split(','));
            if(arrLength > 5) {
              callback(new Error("商品关键词，不能超过5个"));
            }else {
              callback();
            }
          }else {
            callback();
          }
        }
      }
      return {
        //loading: false,
        // categoryStr: '',
        goodsInfoDataClone: {},
        areaOptions: [], // 地址 省
        brandOptions: [], // 商品品牌
        goodsInfoForm: {
          goods_id: 0,
          categoryStr: '',     // 商品分类 地址拼接
          categoryList: [],    // 商品分类 id集合的数组
          goods_des: '',       // 关键词
          goods_name: '',      // 商品标题
          category_id: '',
          producing_area: '',   // 产地
          deliver_area: '',     // 发货地
          unit: '',             // 单位
          goods_brand: '',      // 品牌
          web_url: '',          // 外部链接
          out_goods_id: '',     // 商品编码
          imgs: []              // 商品图片
        },
        goodsInfoRules: {
          categoryStr: [{required: true, message: '商品分类不能为空', trigger: 'blur'}],
          goods_name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 3, max: 30, message: '商品标题限制在3字符以上，30个字符以下', trigger: 'blur'}
          ],
          // goods_des: [{required: true, validator: goodsDecCheck, trigger: 'blur'}],
          // producing_area:[{required: true, message: '请选择商品产地', trigger: 'change'}],
          deliver_area: [{required: true, message: '请选择商品发货地', trigger: 'change'}],
          unit: [{required: true, message: '商品单位不能为空', trigger: 'blur'}],
          goods_brand: [{required: true, message: '请选择商品品牌', trigger: 'change'}],
          imgs: [{required: true, message: '请上传商品图片', validator: categoryIdCheck}]
        },
        goodsImgFileList: [], // 商品图片地址 集合list
        goodsImgVisible: false, // 图片能否预览
        goodsImgUrlDialog: '',
        /* 修改 商品分类 */
        loadingSSQ: false,
        editGoodsTypeDialog: false,
        SSQGoodsList: [], // 经营类目
        goodsprops: {
          expandTrigger: 'click',
          // lazy: true,
          // lazyLoad: this.lazyLoad,
          value: "id",
          label: 'label',
          // leaf: 'leaf',
          children: 'children',
          // checkStrictly: true
        },
        fuckoptions: [],

      } // return end
    },
    components: {},
    watch: {
      // selectCity(arr){
      //   //处理回显问题
      //   setTimeout(()=>{
      //     this.$refs.ssqGoodsCascader.presentText = arr[0] +"/" + arr[1];// 首次手动复制
      //   },1000)
      // }
    },
    created() {
      // 获取 省
      this.getArea();
      // 获取 商品品牌
      this.getBrands();
      // 获取类目
      this.getSSQArea();
    },
    mounted() {
      //深拷贝一份最开始的数据，为初始化准备
      //this.goodsInfoDataClone = this.deepClone(this.goodsinfodata);
      if(this.goodsinfodata.goods_id) {
        this.goodsInfoForm = this.goodsinfodata;
        if( this.goodsInfoForm.imgs.length > 0 ) {
          this.goodsInfoForm.imgs.forEach( (item )=> {
            let objImg = { 'url': '' }
            objImg.url = item;
            this.goodsImgFileList.push(objImg);
          })
        }
      }else {
        this.goodsInfoForm.categoryStr = this.goodsinfodata.categoryStr;
        this.goodsInfoForm.categoryList = this.goodsinfodata.categoryList;
      }
    },
    methods: {
      // 数据初始化
      initInfo() {
        this.$refs.goodsInfoForm.resetFields();
        this.goodsImgFileList = [];
      },
      // 获取 省
      getArea() {
        let limboNode = {
          pid: 0
        };
        getAreaList(limboNode).then( res => {
          if( res.data && res.data.length > 0) {
            this.areaOptions = res.data;
          }else {
            this.areaOptions = [];
          }
        });
      },
      // 获取 商品品牌
      getBrands() {
        getBrandsInf().then( res => {
          if(res.data) {
            this.brandOptions = res.data.data;
          }else {
            this.brandOptions = [];
          }

          // let num_goods_brand = Number(this.goodsInfoForm.goods_brand);
          //
          // if( this.goodsInfoForm.goods_brand !== '') {
          //   let result = this.brandOptions.find( item => {
          //     return item.id === num_goods_brand;
          //   });
          //   //console.log(315,result)
          //   if( result == undefined) {
          //     this.goodsInfoForm.goods_brand = '';
          //   }
          // }

        });
      },
      /* 修改 商品分类 类目 */
      editType() {
        this.SSQGoodsList = [];
        this.editGoodsTypeDialog = true;
        this.SSQGoodsList = this.goodsInfoForm.categoryList
        //console.log('点击修改类目数据：',this.SSQGoodsList);
      },

      getSSQArea(node, resolve) {
        let limboNode = {id: 0};
        NewGetCategory(limboNode).then(res => {
          this.fuckoptions = res.data;
        });
      },
      // 类目修改
      SSQGoodsChange(value) {
        this.SSQGoodsList = value;
      },
      // 确认 修改 商品分类
      saveType() {
        if(this.SSQGoodsList && this.SSQGoodsList.length === 3) {
          let ssqLabelList = this.$refs['ssqGoodsCascader'].getCheckedNodes()[0].pathLabels;
          this.goodsInfoForm.categoryList = this.SSQGoodsList;
          this.goodsInfoForm.categoryStr = ssqLabelList[0] + '/' + ssqLabelList[1] + '/' + ssqLabelList[2];
          this.editGoodsTypeDialog = false;
          this.$message({type:'success',message:'修改成功'});
        }else {
          this.$message({type: 'warning',message: '请选择完整三级类目'});
        }
      },
      // 取消 修改 商品分类
      cancelType() {
        this.editGoodsTypeDialog = false;
        this.SSQGoodsList = [];
      },


      // 上传 商品图片，限制 5 张
      limitImg5() {
        this.$message({ message: '最多上传5张图片', type: 'warning' })
      },
      // 上传 商品图片 之前
      beforeUpGoodsImg (file) {
        let isImgSize = (file.size / 1024 / 1024 ) > 2;

        if(file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持 jpg / png 格式',
            type: "warning"
          });
          return false;
        }

        if(isImgSize) {
          this.$message({
            message: '上传图片大小不能超过2MB',
            type: "warning"
          });
          return false;
        }

        // 图片宽高尺寸限制 800*800
        return new Promise(function(resolve, reject){
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function(){
            // 图片是否是正方形 宽高比为 1
            file.width = img.width;
            file.height = img.height;
            let valid = (img.width === 800) && (img.height === 800);
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(()=>{
          return file;
        }, ()=>{
          this.$message({
            message:'商品图片尺寸必须为800 * 800像素，请重新选择!',
            type: 'warning'
          });
          return Promise.reject();
        });

      },
      // 上传 商品图片
      uploadGoodsImg(param) {
        //console.log(327,param);
        this.getBase64(param.file).then( res => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data":this.Base64img};
          UploadImg(data).then( res=> {
            let urlObj = {'url': ''};
            if(res.data) {
              urlObj.url = res.data.image_url;
              this.goodsImgFileList.push(urlObj);
              this.goodsInfoForm.imgs = []; // 1009 hxz 初始化img
              this.goodsImgFileList.forEach(item=> {
                this.goodsInfoForm.imgs.push(item.url)
              })
              this.$message({type:'success',message:'图片上传成功'});
              // 只清除一次，不浪费哦
              if(this.goodsImgFileList.length === 1) {
                this.$refs.goodsInfoForm.clearValidate('imgs');
              }
            }
          });
        });
      },
      // 商品信息 子组件 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)
            this.goodsInfoForm.imgs.splice(i, 1);
          }
        }
        if(this.goodsImgFileList.length === 0) {
          this.$refs.goodsInfoForm.validateField('imgs')
        }else {
          this.$refs.goodsInfoForm.clearValidate('imgs');
        }
      },

      // 维护品牌
      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: 20px;
    /*margin-top: 18px;*/
  }
  .type-text-span {
    display: inline-block;
    width: 420px;
    /*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;
  }

  /*/deep/.el-cascader-menu {*/
  /*  height:600px;*/
  /*}*/
</style>
