<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.trim="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.trim="goodsInfoForm.goods_name" placeholder="请输入商品标题" style="width:420px;"></el-input>
        <span class="tip-span ml20">商品名称限制在50字以内，不要填写与商品无关的词</span>
      </el-form-item>
      <!-- <el-form-item label='商品关键词：' prop="goods_des">
        <el-input v-model.trim="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.trim="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.trim="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.trim="goodsInfoForm.unit" placeholder="请输入商品单位" style="width:420px;"></el-input>
      </el-form-item> -->
      <el-form-item label="所属品牌：" prop="brand_id">
        <el-select v-model.trim="goodsInfoForm.brand_id" 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.trim="goodsInfoForm.web_url" placeholder="请输入京东或者淘宝的商品链接" style="width:420px;"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label='商品编码：' prop="out_goods_id">
        <el-input v-model.trim="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 }} / 7</i>
          商品图片最多上传7张，默认第一张为主图
          <span style="margin-left: 20px;">单张图片需限制在2M以内，可上传png、jpg格式，尺寸要求为800 * 800</span>
        </span>
        <draggable :list="goodsImgFileList" group="article" class="dragArea" @end="handchange($event)">
          <div v-for="(element,index) in goodsImgFileList" :key="index" class="list-complete-item"
            style="float:left;margin:0 10px;">
            <div style="width:98px;height:98px;position: relative;" class="" @mouseover="showDelBtn(index)"
              @mouseleave="hiddenDelBtn">
              <img v-if="element" :src="element.url" width="98" height="98" />
              <span class="iconcur" v-show="index==currentDelBtn" style="width:100%;height:100%;line-height: 98px;text-align: center; position:absolute;top:0;left:0;background-color: rgba(0,0,0,0.5);
              transition: opacity .3s;">
                <i class="el-icon-zoom-in iconcur" style="font-size:20px;color:#fff;" @click="lookimg(element)"></i>
                <i class="el-icon-delete iconcur" style="font-size:20px;color:#fff;"
                  @click="deleImg(element,index)"></i>
              </span>
            </div>
            <p v-if="index==0" style="margin:0;padding:0;text-align:center;background:#ccc;color:#fff;">主图</p>
          </div>
        </draggable>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <!-- {{goodsImgFileList}} -->
        <el-upload class="upload-img" list-type="picture-card" action="#" :limit="7" :on-exceed="limitImg5"
          :before-upload="beforeUpGoodsImg" :http-request="uploadGoodsImg" :show-file-list="false"
          :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-item label='商品视频：'>
        <span class="tip-span" style="display: block;line-height: 34px;">
          最多上传一个视频（mp4格式），视频时长不超过30秒,
          <span style="margin-left: 20px;">视频大小不超过10M，默认视频在图片前面</span>
        </span>

        <video v-if="vediosrc" style="width:300px;height:150px;float:left;margin:0 10px 0 0;" v-bind:src="vediosrc"
          class="avatar video-avatar" controls="controls">
          您的浏览器不支持视频播放
        </video>
        <i @click="delvideo" v-if="vediosrc" class="el-icon-circle-close iconcur"
          style="color:red;font-size: 18px;"></i>
        <el-upload v-if="!vediosrc" class="upload-img" ref="videoref" action="#" :limit="1" list-type="picture-card"
          :before-upload="beforeUpGoodsvedio" :http-request="uploadGoodsvedio" :show-file-list="false"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-error="vedioerror"
          :file-list="goodsvedioFileList"><i class="el-icon-plus" />
          <!-- v-if="videoform.showvideopath !='' && !videoflag" -->
        </el-upload>
      </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 opendow" title="修改商品分类" :visible.sync="editGoodsTypeDialog" :close-on-click-modal="false"
      :before-close="cancelType"   center>
      <el-cascader-panel style="width:80%;" v-show="editGoodsTypeDialog" v-model.trim="SSQGoodsList" :props='goodsprops'
        :options="fuckoptions" @change="handGoodsChang" @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,NewGetCategoryData, GetFreight, UploadImg, getByCategoryData, uploadVideo } from '@/api/module/goods'
  import { getBrandsInf } from '@/api/module/brand/brand'
  import { getAreaList } from '@/api/module/retreat/address'
  import draggable from 'vuedraggable'
  export default {
    name: 'goods',
    props: {
      goodsinfodata: {
        type: Object,
        required: true
      }
    },
    components: {
      draggable
    },
    computed: {//这一部分直接拿过来用的
      dragOptions() {
        return {
          valdata:[],
          animation: 200,
          group: "description",
          disabled: false,
          ghostClass: "ghost"
        };
      }
    },
    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 {
        dialogVisible: false,
        dialogImageUrl: '',
        videoflag: false,
        //是否显示进度条
        videouploadpercent: "",
        //进度条的进度，
        isshowuploadvideo: false,
        //显示上传按钮
        videoform: {
          showvideopath: ''
        },
        goodsvedioFileList: [],
        vediosrc: '',
        loadingapp: false,
        drag: false,
        currentDelBtn: -1,
        areaOptions: [], // 地址 省
        brandOptions: [], // 商品品牌
        goodsInfoForm: {
          goods_id: 0,
          categoryStr: '',     // 商品分类 地址拼接
          categoryList: [],    // 商品分类 id集合的数组
          goods_des: '',       // 关键词
          goods_name: '',      // 商品标题
          category_id: '',
          producing_area: '',   // 产地
          deliver_area: '',     // 发货地
          unit: '',             // 单位
          goods_brand: '',      // 品牌
          brand_id: '',          // 品牌id
          web_url: '',          // 外部链接
          out_goods_id: '',     // 商品编码
          imgs: [],              // 商品图片
          video: ''
        },
        goodsInfoRules: {
          categoryStr: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 3, max: 50, message: '商品标题限制在3字符以上，50个字符以下', 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: 'title',
          // leaf: 'leaf',
          children: 'children',
          // checkStrictly: true
        },
        fuckoptions: [],
        catefee: 0,
      } // return end
    },
    watch: {
      // selectCity(arr){
      //   //处理回显问题
      //   setTimeout(()=>{
      //     this.$refs.ssqGoodsCascader.presentText = arr[0] +"/" + arr[1];// 首次手动复制
      //   },1000)
      // }
    },
    created() {
      // 获取 商品品牌
      this.getBrands();
      // 获取类目
      // this.getSSQArea();
    },
    mounted() {
      if (this.goodsinfodata.goods_id) {
        this.goodsInfoForm = this.goodsinfodata;
        this.vediosrc = this.goodsinfodata.video
        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;
      }
      // 初始化 服务费率
      this.getByCategoryFee(this.goodsInfoForm.categoryList)
      this.SSQGoodsList = this.goodsInfoForm.categoryList
      this. getalllist(this.SSQGoodsList)
    },
    methods: {
      handchange() {//图片拖动结束
        console.log(this.goodsImgFileList)
        this.goodsInfoForm.imgs = []
        this.goodsImgFileList.forEach(item => {
          this.goodsInfoForm.imgs.push(item.url)
        })
      },
      delvideo() {
        this.vediosrc = ''
        this.goodsvedioFileList = []
      },
      // 上传 视频 之前
      beforeUpGoodsvedio(file) {
        // debugger
        let isImgSize = (file.size / 1024 / 1024) > 10;

        if (file.type !== "video/mp4") {
          this.$message({
            message: '上传视频格式只支持 mp4 格式',
            type: "warning"
          });
          return false;
        }

        if (isImgSize) {
          this.$message({
            message: '上传视频大小不能超过10MB',
            type: "warning"
          });
          return false;
        }
      },
      // 上传 商品视频
      uploadGoodsvedio(param) {
        const formData = new FormData()
        formData.append('file', param.file)
        uploadVideo(formData).then(res => {

          if (res.data && res.code == 1) {
            let urlObj = { 'url': '' };
            urlObj.url = res.data.url;
            this.goodsvedioFileList.push(urlObj);
            this.vediosrc = res.data.url
            this.goodsInfoForm.video = res.data.url
            this.$message({ type: 'success', message: '视频上传成功' });
          } else {
            this.goodsvedioFileList = []
            this.vediosrc = ''
            this.$notify.error({
              title: '错误',
              message: res.message
            });
          }
        }).catch((err) => {

          console.log(err)
        });

      },
      vedioerror(err, file, fileList) {
        console.log(err, file, fileList)
      },
      onEnd() {
        // debugger
        console.log(this.goodsImgFileList)
        this.drag = false
      },
      //显示删除图片的图标
      showDelBtn(index) {

        this.currentDelBtn = index
      },
      //隐藏删除图片的图标
      hiddenDelBtn() {
        this.currentDelBtn = -1
      },
      // 删除图片
      deleImg(data, index) {
        this.goodsImgFileList.splice(index, 1)
        this.goodsInfoForm.imgs.splice(index, 1);
      },
      lookimg(data) {
        this.dialogVisible = true
        this.dialogImageUrl = data.url
      },
      // 数据初始化
      initInfo() {
        this.$refs.goodsInfoForm.resetFields();
        this.goodsImgFileList = [];
      },

      // 获取 商品品牌
      getBrands() {
        // 增加入参
        let data = {
          status: 1
        }
        getBrandsInf(data).then(res => {
          if (res.code == 1) {
            this.brandOptions = res.data.data ? res.data.data : [];
          } else {
            this.brandOptions = [];
          }
        });
      },
      /* 修改 商品分类 类目 */
      editType() {
        // this.SSQGoodsList = [];
        this.fuckoptions =  this.setTreeData(this.fuckoptions)
        this.editGoodsTypeDialog = true;
        
      },
      getalllist(itemarr){
        // debugger
        let limboNode
        itemarr.forEach((item,index)=>{
          if(index==0){
            limboNode = { parent_id:0  }
          }
          if(index>0){
            limboNode = { parent_id:itemarr[index-1]  }
         
      }
      NewGetCategoryData(limboNode).then(res => {
          let date = res.data.forEach(item=>{
            if(item.level!==2){
              item['children'] = []
            }
          })
          this.fuckoptions.push.apply(this.fuckoptions,res.data)
        });
        })
      
        
      },
      getSSQArea() {
        let limboNode = { id: 0 };
        NewGetCategoryData(limboNode).then(res => {
          this.fuckoptions = res.data;
        });
      },
      setTreeData(arr) {
					//  删除所有 children,以防止多次调用
					arr.forEach(function(item) {
						// delete item.children;
					});
					let map = {}; // 构建map
					arr.forEach(i => {
						map[i.id] = i; // 构建以third_id为键 当前数据为值
					});
					let treeData = [];
					arr.forEach(child => {
						const mapItem = map[child.parent_id]; // 判断当前数据的parent_id是否存在map中
						if (mapItem) { // 存在则表示当前数据不是最顶层数据
							// 注意: 这里的map中的数据是引用了arr的它的指向还是arr，当mapItem改变时arr也会改变,踩坑点
							(mapItem.children || (mapItem.children = [])).push(child); // 这里判断mapItem中是否存在children, 存在则插入当前数据, 不存在则赋值children为[]然后再插入当前数据
						} else { // 不存在则是组顶层数据
							treeData.push(child);
						}
					});
				
					return treeData;
				},
      // 类目修改
      handGoodsChang(val){
        console.log(val,'newval')
        this.SSQGoodsList = val
      },
      SSQGoodsChange(value) {
        this.valdata=[]
        console.log(value,'ccc')
        let limboNode = {
          parent_id:value[value.length - 1]
        }
        NewGetCategoryData(limboNode).then(res => {
          // debugger
          res.data.forEach(val=>{
              if(val.level!==2){
                val['children'] = []
              }
              this.valdata.push(val)
            })
            console.log(this.valdata)
          if(value.length==1){
            this.fuckoptions.forEach((item,index)=>{
        
                if(item.id == value[value.length - 1]){
                  // debugger
                  this.fuckoptions[index].children = this.valdata
                  // debugger
                }
              })
          }  
          if(value.length==2){
            this.fuckoptions.forEach((item,index)=>{
                if(item.id == value[0]){
                  this.fuckoptions[index].children.forEach((iten,indexs)=>{
                    if(iten.id ===value[1]){
                      this.fuckoptions[index].children[indexs].children =this.valdata
                    }
                  })
                }
              })
          }    
        });
        console.log(this.SSQGoodsList,'aaaaa')
      },
      // 确认 修改 商品分类
      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: '修改成功' });
          // 修改类目后更新 服务费率
          this.getByCategoryFee(this.goodsInfoForm.categoryList)
        } else {
          this.$message({ type: 'warning', message: '请选择完整三级类目' });
        }
      },
      // 取消 修改 商品分类
      cancelType() {
        this.editGoodsTypeDialog = false;
        this.SSQGoodsList = [];
      },


      // 上传 商品图片，限制 7 张
      limitImg5() {
        this.$message({ message: '最多上传7张图片', 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' });
      },

      /** 根据类目 获取服务费率
       * 传一级类目
       * */
      getByCategoryFee(cateList) {
        let data = {
          category_id: ''
        }
        this.cateFee = 0;

        if (Array.isArray(cateList) && cateList.length > 0) {
          data.category_id = cateList[0];
        }
        // console.log(8888,data);
        getByCategoryData(data).then(res => {
          if (res.code == 1) {
            this.cateFee = res.data.service_fee_ratio ? res.data.service_fee_ratio : ''
            this.$store.commit('SET_CATEFEE', this.cateFee);
          }
        });
      },

      // 图片转换为 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;
  }

  .list-complete-item {
    display: inline-block;
  }

  .imgSty {
    margin: 0 10px;
  }

  .iconcur {
    cursor: pointer;
  }

  /*/deep/.el-cascader-menu {*/
  /*  height:600px;*/
  /*}*/
 /deep/ .el-cascader-menu{
   max-width: 250px !important;
   min-width: 250px !important;

 }
 /deep/  .el-cascader-menu__wrap{
   width:auto !important;
   max-width: 250px !important;
   min-width: 250px !important;

 }
 .opendow /deep/ .el-dialog{
   width:800px;
 }
</style>