<template>
  <div class="app-container">
    <div>
      <!-- <div slot="header" class="clearfix">
        <span>商品规格</span>
        <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
    </div> -->
      <el-checkbox v-model="checked">启用商品规格</el-checkbox>
      <p style='font-size:14px;'>启用商品规格后，商品的价格及库存以商品规格为准</p>
      <p style='font-size:14px;'>
        操作顺序：添加新规格 (<span style="color: red">必填</span>) -&gt;
        添加规格项 (<span style="color: red">必填</span>) -&gt; 生成产品规格表
        -&gt; 修改数值 -&gt; 保存商品规格
        <span style="color: red">注意：商品价格金额必须小于指导价格</span>
      </p>
      <ul class="tab_list" v-if="checked">
        <li
          class="ullist"
          v-for="(item, index) in shopType"
          :key="index"
          v-dragging="{ list: shopType, item: item, group: 'knowTab' }"
        >
          <div class="tab_list_left">
            <div style="margin-top: 15px">
              <el-input placeholder="请输入内容" v-model="item.specName" >
                <template slot="append">
                  <el-button
                    type="primary"
                    class="addbtn"
                    @click="addlistguied(index)"
                    ><i class="el-icon-plus"></i>添加规格项</el-button
                  >
                </template>
              </el-input>
              <el-button
                type="danger"
                icon="el-icon-delete"
                class="eldelbtn"
                @click="deletearrinput(index)"
              ></el-button>
            </div>
            <el-row :gutter="20" class="tab_list childlist">
              <el-col
                :span="4"
                v-for="(items, indexs) in item.specValue"
                :key="indexs"
                v-dragging="{
                  list: item.specValue,
                  item: items,
                  group: 'itemchild',
                }"
                style="margin: 5px 0; min-width: 205px"
              >
                <el-input
                  placeholder=""
                  v-model="items.value"
                  @input="guidInput"
                  style="
                    width: 100%;
                    min-width: 200px;
                    padding: 0;
                    text-align: center;
                  "
                >
                  <template slot="append">
                    <!-- <img :src="nopeimg" alt="" style="width:29px;height:29px;display:inline-block;"/> -->
                    <!--  -->
                    <el-button
                      type="primary"
                      class="dfbtn"
                      icon="el-icon-delete"
                    >
                      <input
                        style="
                          display: none;
                          width: 29px;
                          height: 29px;
                          position: absolute;
                          left: 0;
                          top: 0;
                        "
                        @change="inputimg()"
                        accept="image/*"
                        :id="imagesid(index, indexs)"
                        type="file"
                      />
                      <img
                        v-if="!items.img"
                        :src="nopeimg"
                        alt=""
                        style="
                          width: 25px;
                          height: 25px;
                          position: absolute;
                          left: 2px;
                          top: 2px;
                        "
                        @click="updateimg(index, indexs)"
                      />
                      <img
                        v-if="items.img"
                        :src="items.img"
                        alt=""
                        style="
                          width: 33px;
                          height: 33px;
                          position: absolute;
                          left: 0;
                          top: 0;
                        "
                      />
                    </el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-delete"
                      @click="deleteinput(index, indexs)"
                    ></el-button>
                    <el-button type="primary" icon="el-icon-rank"></el-button>
                  </template>
                </el-input>
              </el-col>
            </el-row>
          </div>
        </li>
      </ul>
      <el-button
        type="primary"
        v-if="checked"
        icon="el-icon-search"
        @click="addguild()"
        >添加新规格</el-button
      >
      <el-button
        type="primary"
        v-if="checked"
        icon="el-icon-search"
        @click="processing()"
        >生成产品规格表</el-button
      >

      <div class="table_box" v-if="checked">
      <!--  <div class="mark">
          操作顺序：添加新规格 (<span style="color: red">必填</span>) -&gt;
          添加规格项 (<span style="color: red">必填</span>) -&gt; 生成产品规格表
          -&gt; 修改数值 -&gt; 保存商品规格
          <span style="color: red">注意：商品价格金额必须小于指导价格</span>
        </div> -->
        <!-- 我记得有个scope属性的 -->
        <el-table
          :data="tableData7"
          :span-method="objectSpanMethod1"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            header-align="center"
            align="center"
            v-for="(item, index) in tablearr"
            :key="index"
            :prop="item"
            :label="item"
          ></el-table-column>

          <el-table-column prop="moany" label="市场价" align="center">
            <template slot="header" slot-scope="scope">
              <p class="table_p">市场价</p>
              <el-input placeholder="" v-model="scPrice"
                ><el-button
                  slot="append"
                  @click="scPriceall"
                  icon="el-icon-bottom"
                ></el-button
              ></el-input>
            </template>
            <template slot-scope="scope" align="center">
              <el-input placeholder="" v-model="scope.row.scPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="moany" label="指导价" align="center">
            <template slot="header" slot-scope="scope">
              <p class="table_p">指导价</p>
              <el-input placeholder="" v-model="price"
                ><el-button
                  slot="append"
                  @click="priceall"
                  icon="el-icon-bottom"
                ></el-button
              ></el-input>
            </template>
            <template slot-scope="scope" align="center">
              <el-input placeholder="" v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="moany" label="结算价" align="center">
            <template slot="header" slot-scope="scope">
              <p class="table_p">结算价</p>
              <el-input placeholder="" v-model="jsPrice"
                ><el-button
                  slot="append"
                  @click="jsPriceall"
                  icon="el-icon-bottom"
                ></el-button
              ></el-input>
            </template>
            <template slot-scope="scope" align="center">
              <el-input placeholder="" v-model="scope.row.jsPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="kucun" label="库存" align="center">
            <template slot="header" slot-scope="scope">
              <p class="table_p">库存</p>
              <el-input placeholder="" v-model="goodsNowStock"
                ><el-button
                  slot="append"
                  @click="goodsNowStockall"
                  icon="el-icon-bottom"
                ></el-button
              ></el-input>
            </template>
            <template slot-scope="scope" align="center">
              <el-input
                placeholder=""
                v-model="scope.row.goodsNowStock"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="moany" label="重量（克）" align="center">
            <template slot="header" slot-scope="scope">
              <p class="table_p">重量（克）</p>
              <el-input placeholder="" v-model="weight"
                ><el-button
                  slot="append"
                  @click="weightall"
                  icon="el-icon-bottom"
                ></el-button
              ></el-input>
            </template>
            <template slot-scope="scope" align="center">
              <el-input placeholder="" v-model="scope.row.weight"></el-input>
            </template>
          </el-table-column>
        </el-table>

        <el-button style="margin-top: 20px;">重 置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import descartes from "@/utils/dikaerjs.js";
// import { onlodaimg } from "@/api/date";
 import { UploadImg } from '@/api/module/goods'
export default {
  name: "goods",
   props: {
    guidedata: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      arrtdall:[],
      nopeimg: require("@/assets/image/nopic100.jpg"),
      checked: false,
      type: "",
      imgname: "",
      indeximg: "",
      indexsimg: "",
      shopType: [],
      shopTypes: [],
      newList: [],
      newData: [],
      tableData7: [], // 规格列表表格
      goodsNowStock: "",
      jsPrice: "", //协议价
      price: "", //指导价
      scPrice: "", //市场价
      weight: "",
      spanArr: [],
      pos: "",
      spanArr1: [],
      pos1: "",
      tablearr: [],
      spanArrS: {
        spanArr0: [],
        spanArr1: [],
      },
      posS: {
        pos0: "",
        pos1: "",
      },
    };
  },
  components: {
    hello: {
      render: function (createElement) {
        return createElement("h" + this.level, this.$se);
      },
    },
  },
  mounted() {
    // this.driver = new Driver()
    this.$dragging.$on("dragged", (value) => {
      //因为我这在排序的时候不需要做处理，所以空着就行
    });
  },
  watch:{
    tableData7:{
      handler(val, oldVal){
        let arrlist = JSON.stringify(val);
        let listarr = JSON.parse(arrlist);
        this.processguidelist(listarr);
        this.$emit('guideclicks',this.arrtdall,this.shopType)

            // this.$emit('parameterclicks',val)
        },
        deep:true
    },
    // 父组件传给 子组件的  值
    guidedata(curVal,oldVal){

      if(curVal){
        if(curVal.goodsSpec){
          this.checked = true;
        }else {
          this.checked = false;
        }

        if(curVal.specName && curVal.specName.length > 0) {
          this.shopType = curVal.specName;
          this.shopType.forEach((item, index) => {
            this.shopType[index]['specValue'] = []
            if(curVal.specValue) {
              curVal.specValue.forEach((itemName, nindex) => {
                if(itemName.specNameId == item.id){
                  this.shopType[index]['specValue'].push(itemName)
                }
              })
            }
          })

          this.clgoodspace(curVal);
          //笛卡尔积值
          this.tableData7 = curVal.specOption;
        }










      }
    },
  },
  methods: {
    guidInput(val){
      this.$forceUpdate()
    },
    // 处理回显数据
    clgoodspace(goodsspace){
      this.shopTypes = JSON.parse(JSON.stringify(this.shopType));
      let specName = goodsspace.specName;
      let specValue = goodsspace.specValue;
      let specOption = goodsspace.specOption;

      if(specName) {
        specName.forEach((item)=>{
          this.tablearr.push(item.specName)
          specValue.forEach((itemchild)=>{
            if(item.id ==itemchild.specNameId){
              itemchild['specName'] =item.specName
            }
          })
        })
      }

      if(specOption) {
        specOption.forEach(item=>{
          let goodsarr = item.specValueIds.split('_')
          goodsarr.forEach(itemchild=>{
            specValue.forEach(itemgoodschild=>{
              if(itemchild == itemgoodschild.id){
                item[itemgoodschild.specName] = itemgoodschild.value
              }
            })

          })
        })
      }

      this.tableData7 = specOption;
      this.getSpanArr(this.tableData7);
    },

    // 不能删
    descartes,

    processguidelist(obj) {
      let arrtdall = []
      if(obj) {
        obj.forEach((item, index) => {
          let objtd = {}
          let arrtd = []
          for(let key in item){
            if(key=='goodsNowStock'||key=='jsPrice'||key=='price'||key=='scPrice'||key=='wlPrice'||key=='pywlPrice'||key=='weight'){
              objtd[key] = item[key]
            }else{
              arrtd.push(item[key])
              objtd['specValues'] = arrtd
            }
          }
          arrtdall.push(objtd)

        });
      }

      this.arrtdall = arrtdall
    },
    deletearrinput(index) {
      this.shopType.splice(index, 1);
    },
    jsPriceall() {
      this.tableData7.forEach((element, index) => {
        this.tableData7[index].jsPrice = this.jsPrice;
      });
    },
    priceall() {
      this.tableData7.forEach((element, index) => {
        this.tableData7[index].price = this.price;
      });
    },
    scPriceall() {
      this.tableData7.forEach((element, index) => {
        this.tableData7[index].scPrice = this.scPrice;
      });
    },
    // 一键 库存
    goodsNowStockall() {
      this.tableData7.forEach((element, index) => {
        this.tableData7[index].goodsNowStock = this.goodsNowStock;
      });
    },
    // 一键 重量
    weightall() {
      this.tableData7.forEach((element, index) => {
        this.tableData7[index].weight = this.weight;
      });
    },
    //删除规格项
    deleteinput(index, indexs) {
      this.shopType[index].specValue.splice(indexs, 1);
      this.$forceUpdate()
    },
    //添加规格项
    addlistguied(index) {
      let childlist = {
        value: "",
        img: "",
      };

      this.$set(this.shopType[index].specValue,this.shopType[index].specValue.length,childlist);
      this.$forceUpdate()
    },
    // 添加新规格
    addguild() {
      let arrchild = {
        specName: "",
        score: "",
        specValue: [],
      };
      this.$set(this.shopType, this.shopType.length, arrchild);
    },
    guide() {
      this.driver.defineSteps(steps);
      this.driver.start();
    },
    imagesid(index, indexs) {
      return index.toString() + indexs.toString() + "ss";
    },
    updateimg(index, indexs) {
      let id = index.toString() + indexs.toString() + "ss";
      this.imgname = id;
      this.indeximg = index;
      this.indexsimg = indexs;
      document.getElementById(id).value = "";
      document.getElementById(id).click();
    },
    inputimg() {
      let file = document.getElementById(this.imgname).files[0];
      //  let formdata=new FormData()
      if (file.size > 1024 * 1024 * 3) {
        return false;
      } else {
        //  formdata.append("file", file);
      }
      // var image = new Image();
      // image.src = window.URL.createObjectURL(file);
      // console.log(image);
      // image.onload = () => {
      //   console.log(this.getBase64Img(image));
      //   //this.getBase64Img(image)即为转换为base64格式的图片形式
      //   let date={
      //     imgData:this.getBase64Img(image)
      //   }
      //   onlodaimg(date).then(res=>{
      //   })
      // };
       this.getBase64(file).then((res) => {
         var result = res.split(",");
         let Base64img = result[1];
         let data = {"image": Base64img}
         UploadImg(data).then((res) => {
           if (res.data.code == 1) {
             this.shopType[this.indeximg].specValue[this.indexsimg].img =
               res.data.data.imageUrl
                this.$forceUpdate()
           }
         });


       });



    },
    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);
              };
            });
          },
    getBase64Img(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    },
    //返回所属规格名字
    retName(index) {
      // if (index == 1) {
      //   if (this.shopType.length > 1) {
      //     return this.shopType[0].name;
      //   }
      // } else if (index == 2) {
      //   if (this.shopType.length > 1) {
      //     return this.shopType[1].name;
      //   }
      // } else if (index == 3) {
      //   if (this.shopType.length > 1) {
      //     return this.shopType[2].name;
      //   }
      // } else {
      //   return "";
      // }
    },
    //处理数据
    processing() {
      this.newData = [];
      this.tablearr = [];
      this.shopTypes = JSON.parse(JSON.stringify(this.shopType));

      if(this.shopTypes && this.shopTypes.length > 0) {
        for (let i = 0; i < this.shopTypes.length; i++) {
          var newlist = [];
          for (
            let index = 0;
            index < this.shopTypes[i].specValue.length;
            index++
          ) {
            newlist.push(this.shopTypes[i].specValue[index].value);
          }
          this.newData.push(newlist);
        }
      }
      this.getList();
    },
    //转换数据
    getList() {
      this.tableData7 = [];
      this.newList = this.descartes(this.newData);

      if(this.shopTypes && this.shopTypes.length > 0) {
        for (let i = 0; i < this.shopTypes.length; i++) {
          this.tablearr.push(this.shopTypes[i].specName);
        }
      }

      for (let index = 0; index < this.newList.length; index++) {
        var listobj = {};
        for (let i = 0; i < this.shopTypes.length; i++) {
          if(this.shopTypes.length>1){
            listobj[this.shopTypes[i].specName] = this.newList[index][i];
          }
          if(this.shopTypes.length==1){
            listobj[this.shopTypes[i].specName] = this.newList[index];
          }
          listobj["goodsNowStock"] = "";
          listobj["jsPrice"] = "";
          listobj["price"] = "";
          listobj["scPrice"] = "";
          listobj["weight"] = "";
        }
        this.tableData7.push(listobj);
      }
      this.getSpanArr(this.tableData7);
      let arrlist = JSON.stringify(this.tableData7); //可以将json对象转换成json对符串
      let listarr = JSON.parse(arrlist); //可以将json字符串转换成json对象
      this.processguidelist(listarr);
    },
    //计算位置的方法
    getSpanArr(data) {
      this.spanArrS = {};
      this.spanArr = [];
      this.pos = "";
      this.spanArr1 = [];
      this.pos1 = "";

      if(this.shopTypes && this.shopTypes.length > 0) {
        for (let s = 0; s < this.shopTypes.length; s++) {
          this.spanArrS["spanArr" + s] = [];
          for (var i = 0; i < data.length; i++) {
            if (i === 0) {
              this.spanArrS["spanArr" + s].push(1);
              this.posS["pos" + s] = 0;
            } else {
              // 判断当前元素与上一个元素是否相同
              if (
                data[i][this.shopTypes[s].specName] ==
                data[i - 1][this.shopTypes[s].specName]
              ) {
                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;
              }
            }
          }
        }
      }

      // for (var i = 0; i < data.length; i++) {
      //   if (i === 0) {
      //     this.spanArr1.push(1);
      //     this.pos1 = 0;
      //   } else {
      //     //如果笛卡尔积一直递增下去的话 这是一个很蠢的方法 由于我的要求层数是已知的 这里偷懒了 不然应该用for循环
      //     if (data[i].cailiao === data[i - 1].cailiao) {
      //       this.spanArr1[this.pos1] += 1;
      //       this.spanArr1.push(0);
      //     } else {
      //       this.spanArr1.push(1);
      //       this.pos1 = i;
      //     }
      //   }
      // }
    },
    // 合并行数
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      if(this.shopTypes && this.shopTypes.length > 0) {
        for (let s = 0; s < this.shopTypes.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
      //   };
      // }
    },
  },
};
</script>
<style scoped>
ul,
li {
  list-style: none;
  margin: 0;
  padding: 0;
}
.ullist {
  border: 1px solid #e7eaec;
  padding: 10px;
  margin-bottom: 10px;
}
.el-input-group {
  width: calc(100% - 60px);
}
.table_box .el-input-group {
  width: 100%;
}
.addbtn {
  background-color: #5bc0de !important;
  color: #fff !important;
  border-radius: 0 4px 4px 0;
}
.eldelbtn {
  height: 30px;
  padding: 5px 20px !important;
  margin-left: -3px;
}
.childlist {
  margin-top: 10px;
}
.childlist .el-input-group--append .el-input__inner {
  padding: 0;
}
.el-button--medium {
  padding: 10px 12px;
}
.dfbtn {
  position: relative;
}
.table_p {
  margin: 0;
  text-align: center;
}
.mark {
  background-color: #fcf8e3;
  padding: 5px;
  /* font-size: 12px; */
  margin-top: 20px;
}
</style>
