<template>
  <div class="goods-parameter">
    <div v-show="isradioguide==1">
      <!-- <p style="margin: 10px 0;color: #333;font-size: 14px;font-weight: 400;">默认</p> -->
      <el-table
        border
        size="small"
        :data="singleSpecTable"
        style="width: 80%;margin-right:10%;"
      >
        <el-table-column align="center" prop="js_price" label="协议价" >
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.js_price" placeholder="请输入协议价" ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sl_price" label="结算价">
          <template slot-scope="scope">
            <span>{{ settleSLPriceFormatter(scope.row.js_price) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="指导价">
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.price" placeholder="请输入指导价"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sc_price" label="市场价">
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.sc_price" placeholder="请输入市场价"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="stock" label="库存量">
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.stock" placeholder="请输入库存量"></el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="weight" label="重量">
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.weight" placeholder="请输入重量"></el-input>
          </template>
        </el-table-column>

        <!--        <el-table-column align="center" prop="imgs9" label="图片">-->
        <!--          <template slot-scope="scope">-->
        <!--            &lt;!&ndash;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&ndash;&gt;-->
        <!--            <el-upload-->
        <!--              action="/"-->
        <!--              class="uploadData50"-->
        <!--              list-type="picture-card"-->
        <!--              :limit="5"-->
        <!--              :on-exceed="limit5"-->
        <!--              :file-list="singleSpecImgList"-->
        <!--              :http-request="(file)=> { return upLoadSingleSpecImg(file,scope.row) }"-->
        <!--              :on-remove=" (file) => { return removeSingleSpeImg(file,scope.row)}"-->
        <!--            ></el-upload>-->
        <!--            &lt;!&ndash;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&ndash;&gt;-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
    </div>
   
    <div v-if="parameterdata.specs&&parameterdata.specs.length > 0&&isradioguide==2"  class="single-spe-con">
      <!-- {{parameterdata.specs_group}} -->
      <el-table
        border
        size="small"
        :data="parameterdata.specs_group"
         :span-method="objectSpanMethod1"
        style="width: 80%"
        :key="keyvalue"
      >
        <el-table-column
        header-align="center"
        align="center"
        v-for="(item, index) in parameterdata.specs"
        :key="index"
        :prop="item.spec_name"
        :label="item.spec_name"
      >
      <!-- <template slot-scope="scope">
      </template> -->
    </el-table-column>
        <el-table-column align="center" prop="js_price" label="协议价">
          <template slot="header">
            <span>协议价</span>
            <el-tooltip placemetn="top">
              <span slot="content">点击可批量设置价格</span>
              <span class="spe-ali-icon0435 iconfont icon-iconset0435" @click="applyAllTable('js_price')"></span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.js_price" placeholder="请输入协议价"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sl_price" label="结算价">
          <template slot-scope="scope">
            <span class="sl-price-span-input">{{ settleSLPriceFormatter(scope.row.js_price) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="指导价">
          <template slot="header">
            <span>指导价</span>
            <el-tooltip placemetn="top" >
              <span slot="content">点击可批量设置价格</span>
              <span class="spe-ali-icon0435 iconfont icon-iconset0435" @click="applyAllTable('price')"></span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.price" placeholder="请输入指导价"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sc_price" label="市场价">
          <template slot="header">
            <span>市场价</span>
            <el-tooltip placemetn="top" >
              <span slot="content">点击可批量设置价格</span>
              <span class="spe-ali-icon0435 iconfont icon-iconset0435" @click="applyAllTable('sc_price')"></span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.sc_price" placeholder="请输入市场价"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="stock" label="库存量">
          <template slot="header">
            <span>库存量</span>
            <el-tooltip placemetn="top" >
              <span slot="content">点击可批量设置价格</span>
              <span class="spe-ali-icon0435 iconfont icon-iconset0435" @click="applyAllTable('stock')"></span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.stock" placeholder="请输入库存量"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="weight" label="重量">
          <template slot="header">
            <span>重量</span>
            <el-tooltip placemetn="top" >
              <span slot="content">点击可批量设置价格</span>
              <span class="spe-ali-icon0435 iconfont icon-iconset0435" @click="applyAllTable('weight')"></span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input size="mini" style="width:90%" v-model.trim="scope.row.weight" placeholder="请输入重量"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="thumb" label="图片">
          <template slot-scope="scope">
              <span
                v-show="!scope.row.thumb"
                class="span-img"
                @click="upPreSpeImg(scope.$index,scope.row)"
              ></span>
            <span v-show="scope.row.thumb" class="span-img-con">
                <img
                  class="spec-img"
                  :src="scope.row.thumb"
                  alt=""
                  @click="changeSpeImg(scope.$index,scope.row)"
                />
                <span class="span-img-del el-icon-delete del-span-block" @click="delSingleSpecImg(scope.$index,scope.row)"></span>
              </span>
          </template>
        </el-table-column>
      </el-table>
      <input type="file" style="display: none;" ref="guideupimg" accept="image/*"
      @change="changeIMG()">
    </div>
  </div>
</template>

<script>
  import { UploadImg } from '@/api/module/goods';
export default {
  name: 'goodsparameter',
    props: {
    parameterdata: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isradioguide:'',
      upimgindex:'',
      keyvalue:1,
      spacArr:[],
      orgGoodsPam: {},
      preTableTitle: [],
      isHoverSpeImg: false,
      /** 无规格 数据 */
      singleSpecTable: [
        {
          js_price: '', // 协议价
          sl_price: '', // 结算价
          price: '',    // 指导价
          sc_price: '', // 市场价
          stock: '',    // 库存
          weight: '',   // 重量 g
        }
      ],
      singleSpecImgList: [],
      isViewPriceExp: false,
      cateFee: 0,
      spanArr: [],
      pos: "",
      spanArr1: [],
      pos1: "",
      tablearr: [],
      spanArrS: {
        spanArr0: [],
        spanArr1: [],
      },
      posS: {
        pos0: "",
        pos1: "",
      },
    } // return end
  },
  watch:{
    'parameterdata': function(val) {
      this.orgGoodsPam = val;
      if(val.pamNameList){
        this.spacArr = val.pamNameList
      }
    },
  },
  created() {
    this.cateFee = this.$store.state.user.cateFee;
  },
  mounted() {
    this.isradioguide = this.parameterdata.isradioguide ? this.parameterdata.isradioguide:1
    console.log(this.parameterdata)
    this.getSpanArr(this.parameterdata);
    this.keyvalue++
      if(this.parameterdata.singleSpecTable && this.parameterdata.singleSpecTable.length === 1 ) {
        this.singleSpecTable  = this.parameterdata.singleSpecTable
      }
  },
  methods: {
    parentMsg(val){
      console.log(val,'guangbo')
      this.isradioguide = val
    },
    /** 初始化 商品售价 数据 */
    initInfo() {
      this.orgGoodsPam = {};
      //this.singleSpecTable =
    },
    // ------  无规格，上传图片相关  ------
    limit5() {
      this.$message({type: 'warning',message: '只能上传5张图片'});
    },
    // 上传 无规格组合 的图片
    upLoadSingleSpecImg(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 => {
          if (res && res.code == 1) {
            this.singleSpecImgList.push({ url: res.data.image_url });
            this.singleSpecTable[0].imgs9 = [];
            this.singleSpecImgList.forEach(item=> {
              this.singleSpecTable[0].imgs9.push(item.url)
            })

            this.$message({ message:'上传成功',type:'success'});
          }else {
            this.singleSpecImgList = [];
            this.$message({ message:'上传失败，请重新上传',type:'error'});
          }
        })
      });
    },
    // 删除 无规格组合 的图片
    removeSingleSpeImg(file) {
      if(file.status === "success") {
        for(let i = 0; i < this.singleSpecImgList.length; i++) {
          if(file.uid === this.singleSpecImgList[i].uid) {
            this.singleSpecImgList.splice(i,1);
            this.singleSpecTable[0].imgs9.splice(i,1);
          }
        }
        this.$message({ type: 'success', message: '删除成功!' });
      }
    },

    /** 规格组合 上传图片 */
    // 上传图片
    upPreSpeImg(index, row) {
      this.upimgindex = index
      this.$refs.guideupimg.value = '';
     
      this.$refs.guideupimg.dispatchEvent(new MouseEvent('click'))
    },

    // 更换 某一个规格的图片
    changeSpeImg(index, row) {
      this.upPreSpeImg(index,row);
    },
    // 真正的上传图片方法，原生input
    changeIMG(index, row) {
      let curRow = row;
 
      let file =  this.$refs.guideupimg.files[0];
      if( file.size > 1024 * 1024 * 3 ) {
        this.$message({ type: 'error',message: '规格图片不能大于 3 M'});
        return;
      }
      this.getBase64(file).then((res) => {
        let result = res.split(",");
        this.Base64img = result[1];
        let data = {"img_data": this.Base64img}
        UploadImg(data).then(res => {
          // this.loading = false;
          if (res && res.code == 1) {
            this.parameterdata.specs_group[this.upimgindex].thumb = res.data.image_url;
            // this.singleSpecImgList.push({'url': res.data.image_url})
            this.$message({ message:'上传成功',type:'success'});
          }else {
            this.$message({ message:'上传失败，请重新上传',type:'error'});
          }
        })
      });

    },
    /**如果保存失败，将乘以100的价格还原
     * 当多规格数据时候，才调用
     * */
    priceReduce() {
      // debugger
      if(this.parameterdata.pamTableList && this.parameterdata.pamTableList.length > 0) {
        this.parameterdata.pamTableList.forEach((item)=> {
          if(item[0].js_price) {
            item[0].js_price = item[0].js_price / 100;
          }
          if(item[0].price) {
            item[0].price = item[0].price / 100;
          }
          if(item[0].sc_price) {
            item[0].sc_price = item[0].sc_price / 100;
          }
          if(item[0].sl_price) {
            item[0].sl_price = item[0].sl_price / 100;
          }
        })
      }
      // else {
      //   if(this.singleSpecTable[0].js_price) {
      //     this.singleSpecTable[0].js_price = this.singleSpecTable[0].js_price / 100
      //   }
      //   if(this.singleSpecTable[0].price) {
      //     this.singleSpecTable[0].price = this.singleSpecTable[0].price / 100
      //   }
      //   if(this.singleSpecTable[0].sc_price) {
      //     this.singleSpecTable[0].sc_price = this.singleSpecTable[0].sc_price / 100
      //   }
      //   if(this.singleSpecTable[0].sl_price) {
      //     this.singleSpecTable[0].sl_price = this.singleSpecTable[0].sl_price / 100
      //   }
      // }
    },
    /** 一键应用所有 */
    applyAllTable(key) {
      // js_price: '', // 协议价
      //     sl_price: '', // 结算价
      //     price: '',    // 指导价
      //     sc_price: '', // 市场价
      //     stock: '',    // 库存
      //     weight: '',   // 重量 g
      let text = ''
      let pacee = ''
      if(key == 'js_price'){
        text = '批量设置协议价'
        pacee = '请输入协议价'
      }
      if(key == 'price'){
        text = '批量设置指导价'
        pacee = '请输入指导价'
      }
      if(key == 'sc_price'){
        text = '批量设置市场价'
        pacee = '请输入市场价'
      }
      if(key == 'stock'){
        text = '批量设置库存量'
        pacee = '请输入库存量'
      }
      if(key == 'weight'){
        text = '批量设置重量'
        pacee = '请输入重量'
      }
      this.$prompt('', text, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/ ,
          inputErrorMessage: '金额须大于零',
          inputPlaceholder:pacee,
          center: true
        }).then(({ value }) => {
            this.parameterdata.specs_group.map(item => {
                item[key] = value
              })
          this.$message({
            type: 'success',
            message: '设置成功' 
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
     
    },

    // 删除 单个规格的图片
    delSingleSpecImg(index,row) {
      if( row.thumb ) {
        row.thumb = '';
        this.$message({type: 'success',message: '删除成功'});
      }
    },
    speImgHover(index,row) {
      this.isHoverSpeImg = true;
    },
    speImgLeave(index, row) {
      this.isHoverSpeImg = false;
    },
    renderHeaderJSPrice(h) {
      return h(
        <div>
          <span>协议价</span>
          <span>点击1</span>
        </div>
      )
    },
    // -- 通用 方法 --
    /** 图片转换为 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);
        };
      });
    },

    /** 结算价格计算 */
    settleSLPriceFormatter(jsPriceVal) {
      this.cateFee = this.$store.state.user.cateFee ? this.$store.state.user.cateFee : 0;

      let slPriceNum = ""

      if (jsPriceVal > 0) {
        if (this.cateFee == 0) {
          slPriceNum = jsPriceVal
        }
        if (this.cateFee > 0) {
          slPriceNum = (1000 - this.cateFee) * (jsPriceVal * 1000) /1000000
        }
      }else if (jsPriceVal == 0) {
        slPriceNum = 0;
      }else {
        slPriceNum = ''
      }

      return slPriceNum
    },
      //计算位置的方法
      getSpanArr(data) {
      this.spanArrS = {};
      this.spanArr = [];
      this.pos = "";
      this.spanArr1 = [];
      this.pos1 = "";

      if(data.specs && data.specs.length > 0) {
        for (let s = 0; s < data.specs.length; s++) {
          this.spanArrS["spanArr" + s] = [];
          for (var i = 0; i < data.specs_group.length; i++) {
            if (i === 0) {
              this.spanArrS["spanArr" + s].push(1);
              this.posS["pos" + s] = 0;
            } else {
              // 判断当前元素与上一个元素是否相同
              if (
                data.specs_group[i][data.specs[s].spec_name] ==
                data.specs_group[i - 1][data.specs[s].spec_name]
              ) {
                this.spanArrS["spanArr" + s][this.posS["pos" + s]] += 1;
                this.spanArrS["spanArr" + s].push(0);
              } else {
                this.spanArrS["spanArr" + s].push(1);
                this.posS["pos" + s] = i;
              }
            }
          }
        }
      }
    },
     // 合并行数
     objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      if(this.parameterdata.specs_group && this.parameterdata.specs_group.length > 0) {
        for (let s = 0; s < this.parameterdata.specs.length; s++) {
          if (columnIndex == s) {
            const _row = this.spanArrS["spanArr" + s][rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col,
            };
            // columnIndex === 1 找到第二列，合并他的列数
          }
        }
      }


      // columnIndex === 0 找到第一列，实现合并随机出现的行数
      // if (columnIndex === 0) {
      //   const _row = this.spanArr[rowIndex];
      //   const _col = _row > 0 ? 1 : 0;
      //   return {
      //     rowspan: _row,
      //     colspan: _col
      //   };
      //   // columnIndex === 1 找到第二列，合并他的列数
      // } else if (columnIndex === 1) {
      //   const _row = this.spanArr1[rowIndex];
      //   const _col = _row > 0 ? 1 : 0;
      //   return {
      //     rowspan: _row,
      //     colspan: _col
      //   };
      // }
    },
  } // methods end
}
</script>
<style lang="scss" type="text/stylus" scoped>

  .span-img {
    margin: 0;
    padding: 0;
    display : inline-block;
    width:50px;
    height:50px;
    position: relative;
    top:4px;
    cursor: pointer;
    border-radius: 6px;
    border: 1px dashed #c0ccda;
    background-color : #fbfdff;
  }
  .span-img:hover {
    border: 1px dashed #1890ff;
  }

  .spec-img {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    border: none;
  }
  .span-img-con {
    margin: 0;
    padding: 0;
    display : inline-block;
    width:50px;
    height:50px;
    position: relative;
    top:4px;
    cursor: pointer;
    border-radius: 6px;
    border: 1px solid #c0ccda;
  }
  .span-img-del {
    position: absolute;
    display : inline-block;
    width: 18px;
    height: 18px;
    font-size: 18px;
    color: #333;
    line-height : 18px;
    top: 50%;
    left: 50%;
    margin-top: -9px;
    margin-left: -9px;
  }

  .spe-ali-icon0435 {
    color: red;
    vertical-align: middle;
    margin-left: 3px;
  }

  .del-span-block {
    display : none;
  }
  .span-img-del:hover {
    color: #F56C6C;
  }

  .span-img-con:hover > .del-span-block {
    display : block;
  }


p {
  margin: 0;
  padding: 0;
}

.tip-p {
  margin: 0 0 20px 0;
}
.goods-parameter {
  padding: 20px;

}

.edit-type-span {
  display: inline-block;
  cursor: pointer;
  margin: 0 20px;
}

.single-spe-con {
  margin: 25px 0;
}

.sl-price-span-input {
  display: inline-block;
  width: 90%;
  height: 28px;
  padding: 0 15px;
  line-height : 28px;
  border-radius : 4px;
  border : 1px solid #DCDFE6;
  vertical-align : bottom;
}

/* 一般提示性文字 */
.tip-span {
  color: #909399;
  font-size: 12px;
}

.pre-price-tip {
  color: #F56C6C;
  font-size: 12px;
}

// 上传图片样式
.uploadData50 {
  display: inline-block;

  /deep/ .el-upload--picture-card {
    width: 50px;
    height: 50px;
  }

  /deep/ .el-upload {
    width: 50px;
    height: 50px;
    line-height: 50px;
  }

  /deep/ .el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
    line-height: 50px;
  }

  /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 50px;
    height: 50px;
    line-height: 50px;
  }

  /deep/ .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
