<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" maxlength="300" show-word-limit
                  placeholder="请输入商品标题" style="width:420px;"></el-input>
        <span class="tip-span ml20">商品名称限制在300字以内，不要填写与商品无关的词</span>
      </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="toPage('brand')">新增品牌</el-link>
      </el-form-item>
      <el-form-item label="计量单位：" prop="metering_unit">
        <el-select v-model.trim="goodsInfoForm.metering_unit" placeholder="请选择商品计量单位" style="width: 420px;">
          <el-option v-for="item in unitList" :key="item.id" :label="item.title" :value="item.id"></el-option>
        </el-select>
        <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toPage('metering_unit')">新增计量单位</el-link>
      </el-form-item>
      <el-form-item label="包装单位：" prop="packaging_unit">
        <el-select v-model.trim="goodsInfoForm.packaging_unit" placeholder="请选择商品包装单位" style="width: 420px;">
          <el-option v-for="item in packageList" :key="item.id" :label="item.title" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="换算关系：" prop="conversion_unit">
        <el-input v-model.trim="goodsInfoForm.conversion_unit" placeholder="请输入换算关系都数量值" style="width:420px;"></el-input>
        <span class="tip-span ml20">1包装单位=n计量单位，如：1箱=10个，请填写数字10</span>
      </el-form-item>
      <el-form-item label="商品产地：" prop="producing_area_id_list">
        <el-cascader ref="producing_area" v-model.trim="goodsInfoForm.producing_area_id_list" :props="areaProps" placeholder="请选择"
                     style="width:420px;" size="mini" @change="matchIdName('producing_area')">
        </el-cascader>
      </el-form-item>

      <el-form-item label="商品发货地：" prop="deliver_area_id_list">
        <el-cascader ref="deliver_area" v-model.trim="goodsInfoForm.deliver_area_id_list" :props="areaProps" placeholder="请选择"
                     style="width:420px;" size="mini" @change="matchIdName('deliver_area')">
        </el-cascader>
      </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> -->
<!--      <div style="display: flex;justify-content: flex-start;flex-direction: row;">-->
<!--        <el-form-item label='税收分类：' prop="ssfl">-->
<!--          <el-input v-model.trim="goodsInfoForm.ssfl" :disabled="true" placeholder="请输入税收分类" style="width:160px;"></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label='税率：' prop="tax_rate" label-width="100px">-->
<!--          <el-select v-model.trim="goodsInfoForm.tax_rate" placeholder="请选择商品税率" style="width: 160px;">-->
<!--            <el-option-->
<!--              v-for="item in taxRateOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.value"-->
<!--              :value="item.id"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </div>-->
      <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: 10px;">主图要求为白底，建议尺寸要求为800*800px，拖拽图片可进行排序</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>

      <!--  更多设置  -->
<!--      <p class="more-settings-p" @click="switchMoreSetting">-->
<!--        <span>{{ !isMoreSetting ? "展开" : "收起"}}</span>更多设置-->
<!--        <i v-show="!isMoreSetting" class="el-icon-arrow-down"></i>-->
<!--        <i v-show="isMoreSetting" class="el-icon-arrow-up"></i>-->
<!--      </p>-->

      <transition name="fade">
<!--        <div v-show="isMoreSetting">-->
        <div v-show="true">
        <el-form-item label='市场参考价链接：'>
          <el-input v-model.trim="goodsInfoForm.web_url" placeholder="请输入京东或者淘宝的商品链接" style="width:420px;"></el-input>
        </el-form-item>

        <el-form-item label="商品分组：">
          <el-select v-model.trim="goodsInfoForm.group" placeholder="请选择商品分组" style="width: 420px;">
            <el-option v-for="item in goodsGroupList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toPage('group')">新增分组</el-link>
        </el-form-item>

        <el-form-item label="所属供应商：">
          <el-select v-model.trim="goodsInfoForm.supplier" placeholder="请选择供应商" style="width: 420px;">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
          <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toPage('supplier')">新增供应商</el-link>
        </el-form-item>

        <el-form-item label="所属仓库：">
          <el-select v-model.trim="goodsInfoForm.storehouse" v-el-select-loadmore="loadMoreTheme" class="w-600" placeholder="请选择仓库" style="width: 420px;">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-link class="edit-type-span el-icon-plus" type="primary" :underline="false" @click="toPage('warehouse')">新增仓库</el-link>
        </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='商品视频：'>
        <span class="tip-span" style="display: block;line-height: 34px;">
          最多上传一个视频（mp4格式），视频时长不超过30秒,
          <span style="margin-left: 20px;">视频大小不超过100M，默认视频在图片前面</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>
      </div>
      </transition>
    </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 { NewGetCategoryData, UploadImg, getByCategoryData, uploadVideo,synthesisList } from '@/api/module/goods'
  import { getBrandsInf } from '@/api/module/brand/brand'
  import { getAreaList } from '@/api/module/retreat/address'
  import { wareHoustList } from "@/api/system/wareHouse";
  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"
        };
      }
    },
    directives: {
      'el-select-loadmore': {
        bind(el, binding) {
          // 获取element-ui定义好的scroll盒子
          const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
          SELECTWRAP_DOM.addEventListener('scroll', function () {
            /**
             * scrollHeight 获取元素内容高度(只读)
             * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
             * clientHeight 读取元素的可见高度(只读)
             * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
             * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
             */
            const condition = this.scrollHeight - this.scrollTop <= this.clientHeight;
            if (condition) {
              binding.value();
            }
          });
        }
      }
    },
    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;
            if (arrLength > 5) {
              callback(new Error("商品关键词，不能超过5个"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        }
      }
      return {
        dialogVisible: false,
        dialogImageUrl: '',
        videoflag: false,
        //是否显示进度条
        videouploadpercent: "",
        //进度条的进度，
        isshowuploadvideo: false,
        //显示上传按钮
        videoform: {
          showvideopath: ''
        },
        goodsvedioFileList: [],
        taxRateOptions: [
          {id: 0,value: '0'}
        ], // 税率
        vediosrc: '',
        loadingapp: false,
        drag: false,
        currentDelBtn: -1,
        areaOptions: [], // 地址 省
        brandOptions: [], // 商品品牌
        goodsInfoForm: {
          goods_id: 0,
          categoryStr: '',     // 商品分类 地址拼接
          categoryList: [],    // 商品分类 id集合的数组
          goods_des: '',       // 商品标签
          goods_name: '',      // 商品标题
          category_id: '',
          producing_area_id_list: '',   // 产地id
          producing_area: '',   // 产地name
          deliver_area_id_list: '',     // 发货地id
          deliver_area: '',     // 发货地name
          goods_brand: '',      // 品牌
          brand_id: '',          // 品牌id
          metering_unit: '', // 计量单位
          packaging_unit: '', // 包装单位
          conversion_unit: '', // 换算关系
          // ssfl: '', // 税收分类
          // tax_rate: 0, // 税率
          web_url: '',          // 外部链接
          group: '',          // 商品分组
          supplier: '',          // 供应商
          storehouse: '',          // 仓库
          out_goods_id: '',     // 商品编码
          imgs: [],              // 商品图片
          video: ''
        },
        isMoreSetting: false, // true-展开状态；false-收起状态
        goodsInfoRules: {
          categoryStr: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 3, max: 50, message: '商品标题限制在3字符以上，50个字符以下', trigger: 'blur' }
          ],
          brand_id: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
          // ssfl: [{ required: true, message: '请选择商品税收分类', trigger: 'change' }],
          // goods_des: [{required: true, validator: goodsDecCheck, trigger: 'blur'}],
          producing_area_id_list:[{required: true, message: '请选择商品产地', trigger: 'change'}],
          deliver_area_id_list: [{ required: true, message: '请选择商品发货地', trigger: 'change' }],
          metering_unit: [{ required: true, message: '计量单位不能为空', trigger: 'change' }],
          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,
        areaProps: {
          checkStrictly: true ,
          expandTrigger: 'click',
          emitPath: true,
          lazy: true,
          lazyLoad: this.areaLazyLoad,
          value: "id",
          label: "name",
          leaf: "leaf"
        },
        unitList: [], // 计量单位
        packageList: [], // 包装单位
        goodsGroupList: [], //分组
        supplierList: [], // 供应商
        warehouseList: [], // 仓库
        pageDataTheme: {
          page: 1,
          limit: 20,
          // status: 1, // 已起用的
        },
        warehouseCount: 0, // 仓库总数量
      } // return end
    },
    watch: {
      // selectCity(arr){
      //   //处理回显问题
      //   setTimeout(()=>{
      //     this.$refs.ssqGoodsCascader.presentText = arr[0] +"/" + arr[1];// 首次手动复制
      //   },1000)
      // }
    },
    created() {
      // 获取 商品品牌
      this.getBrands();
      // 综合接口，获取仓库，供应商，商品分组，计量单位，默认返回第一页的数据
      this.getSynthesisList();
    },
    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;
        let categoryNameList = this.goodsinfodata.categoryStr.split("/");
        if (categoryNameList.length === 3) {
          this.goodsInfoForm.ssfl = categoryNameList[2]
        }
      }

      // 初始化 服务费率
      this.getByCategoryFee(this.goodsInfoForm.categoryList)
      this.SSQGoodsList = this.goodsInfoForm.categoryList
      this.getalllist(this.SSQGoodsList)
    },
    methods: {
      // 更多设置 初始化 数据
      resetMoreSetting() {
        let resetPartData = {
          web_url: '',
          group: '',
          supplier: '',
          storehouse: '',
          goods_des: '',
          video: ''
        };
        this.delvideo()
        Object.assign(this.goodsInfoForm,resetPartData)
      },
      // 产地
      areaLazyLoad(node, resolve) {
        this.getArea(node, resolve);
      },
      // 商品产地
      getArea(node, resolve) {
        const level = node.level
        let date = {}
        if (level === 0) {
          date = { pid: 0 }
        }else {
          date = { pid: node.value }
        }

        getAreaList(date).then(res => {
          let result = {}
          result = res.data
          if (level === 0) {
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.children=[]
              item.leaf = 0
            })
          }
          if (level === 1) {
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.children=[]
              //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
              item.leaf = 0
            })
          }
          if (level === 2) {
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
              item.leaf = 1
            })
          }
          resolve(result)
        })
      },
      // 产地查处id对应的中文地址
      matchIdName(typeName) {
        let areaLabelList = this.$refs[typeName].getCheckedNodes()[0].pathLabels;
        let areaLastName = 0;
        if (areaLabelList.length > 0) {
          areaLastName = areaLabelList.length - 1
          // 产地
          if (typeName === "producing_area") {
            this.goodsInfoForm.producing_area = areaLabelList[areaLastName]
          }
          // 发货地
          if (typeName === "deliver_area") {
            this.goodsInfoForm.deliver_area = areaLabelList[areaLastName]
          }
        }
      },

      handchange() {//图片拖动结束
        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) > 100;

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

        if (isImgSize) {
          this.$message({
            message: '上传视频大小不能超过100MB',
            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) => {

        });

      },
      vedioerror(err, file, fileList) {
      },
      onEnd() {
        // debugger
        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.data) {
            this.brandOptions = res.data.data ? res.data.data : [];
          }
        });
      },

      // 综合接口，获取仓库，供应商，商品分组，计量单位，默认返回第一页的数据
      getSynthesisList() {
        synthesisList().then(res=> {
          // 数据兼容
          if (res.code === 1 && res.data) {
            // 包装单位
            if (Array.isArray(res.data.goods_pack_list)) {
              this.packageList = res.data.goods_pack_list
            }
            // 计量单位
            if (Array.isArray(res.data.goods_unit_list)) {
              this.unitList = res.data.goods_unit_list
            }
            // 商品分组
            if (res.data.group_list && Array.isArray(res.data.group_list.list)) {
              this.goodsGroupList = res.data.group_list.list
            }
            // 供应商
            if (Array.isArray(res.data.operator_list)) {
              this.supplierList = res.data.operator_list
            }
            // 仓库
            if (res.data.warehouse_list && Array.isArray(res.data.warehouse_list.list)) {
              this.warehouseList = res.data.warehouse_list.list
              // 默认一次数据最多20条，如果这个接口，返回仓库数据小于20条，说明仓库已经没有数据了，不用再进行滚动懒加载；否则仓库总数量，
              // 可能多于20条，需要进行滚动懒加载
              if (this.warehouseList.length === 20) {
                this.loadMoreTheme()
              }
            }
          }else {
            this.$message({type: "error",message: res.message ? res.message : ""});
          }
        });
      },

      // 仓库 滚动加载
      loadMoreTheme() {
        if (this.warehouseList.length < this.warehouseCount) {
          this.pageDataTheme.page++;
          this.getWarehouseList();
        }
      },

      // 仓库列表
      getWarehouseList() {
        wareHoustList(this.pageDataTheme).then(res=> {
          if (res.data) {
            if (Array.isArray(res.data.list) && res.data.list.length > 0) {
              this.warehouseList = this.warehouseList.concat(res.data.list);
              this.warehouseCount = res.data.count;
            }
          }
        });
      },

      /* 修改 商品分类 类目 */
      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){
        this.SSQGoodsList = val
      },
      SSQGoodsChange(value) {
        this.valdata=[]
        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)
            })
          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
                    }
                  })
                }
              })
          }
        });
      },
      // 确认 修改 商品分类
      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.goodsInfoForm.ssfl = 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 = [];
      },

      // 更多设置
      switchMoreSetting() {
        this.isMoreSetting = !this.isMoreSetting
      },

      // 上传 商品图片，限制 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) {
        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');
        }
      },

      // 跳转到对应页面
      toPage(name) {
        switch (name) {
          case 'brand' : {
            // this.$router.push({ path: '/system/shop/brand' });
            this.$router.push({ path: '/system/goods/brand' });
            break;
          }
          case 'metering_unit' : {
            this.$router.push({ path: '/system/goods/commodityUnitd' });
            break;
          }
          case 'group' : {
            // this.$router.push({ path: '/system/settings/commodityGroup' });
            this.$router.push({ path: '/system/goods/commodityGroup' });
            break;
          }
          case 'supplier' : {
            this.$router.push({ path: '/system/supplier/supplier' });
            break;
          }
          case 'warehouse' : {
            this.$router.push({ path: '/system/warehouse/wareHouse' });
            break;
          }
        }
      },

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

        if (Array.isArray(cateList) && cateList.length > 0) {
          data.category_id = cateList[0];
        }
        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 0;
    background-color: #fff;
    /*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;
  }

  /*更多设置*/
  .more-settings-p {
    display: inline-block;
    margin: 20px 0;
    padding: 0 0 0 66px;
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;
    color: #1890ff;
  }

  .more-settings-p:hover {
    display: inline-block;
    color: #647dff;
  }

  /* 一般提示性文字 */
  .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;
 }

  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
  }

</style>
