<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="form" :inline="true" label-width="80px">
        <el-form-item label="产品名称">
          <el-input v-model="productName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存价格</el-button>
        </el-form-item>
      </el-form>
    </div>
      <el-card class="box-card">
        <el-form ref="form" label-width="80px">
          <el-form-item v-for="item in allSpecItems" :key="item.specId" :label="item.specName">
<!--            <el-checkbox-group v-model="item.selectedValues">-->
              <el-checkbox v-for="value in item.values " v-model="value.checked" :key="value.valueId" :label="value.valueId" @change="checkChange($event,item.specId,value.valueId)">{{value.valueName}}</el-checkbox>
<!--            </el-checkbox-group>-->
          </el-form-item>
        </el-form>
      </el-card>
    <el-form ref="formSkuInput" :rules="rules">
      <el-table :data="skuData.skus">
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column
        v-for="(item,index) in skuData.specItems"
        v-if="item.selectedValues.length > 0"
        :key="item.specId"
        :label="item.specName">
        <template slot-scope="{row}">
          {{row.skuName.split(',')[index]}}
        </template>
      </el-table-column>
      <el-table-column label="零售价">
        <template slot-scope="{row}">
          <el-input v-model="row.skuPrice" oninput = "value=value.replace(/[^\d.]/g,'')" placeholder="请输入数字" ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="idProduct" label="库存">
        <template slot-scope="{row}">
          <el-input v-model="row.skuQuantity" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字"></el-input>
        </template>
      </el-table-column>
    </el-table>
    </el-form>
  </div>
</template>

<script>
  import {
    getSkuInfo,
    saveProductSkuPrice
  } from '@/api/productFile/spec.js'

  export default {
    components: {
    },
    data() {
      const validatePrice = (rule, value, callback) => {
        console.log(value.replace(/[^\d.]/g, ''));
        if (value.replace(/[^\d.]/g,'')) {
          callback(new Error('请输入账号'))
        } else {
          callback()
        }
      }
      return {
        idProduct: '',
        productName:'',

        specItems:[],
        // checked:[],
        allSpecItems:[],

        skuData:{},
        oldSkuData:[],

        rules:{
          inputSkuPrice: [{required: false, trigger: 'blur', validator: validatePrice}],

    }
      }
    },
    computed:{
      checked(){
        console.log(_that.checked);
      }
    },
    mounted() {
      this.idProduct = this.$route.query.idProduct
      this.productName = this.$route.query.productName
      this.getInfo();
    },
    methods: {
      //获取列表
      getInfo() {
        const _that = this

        var data = {
          "idProduct": _that.idProduct
        }

        getSkuInfo(data).then(response => {
          console.log(response)
          const data = response.data
          _that.specItems = data.allSpecItems;
          (data.allSpecItems).forEach((spec,index)=>{
            var specItem = {};
            specItem.specId = spec.id;
            specItem.specName = spec.specName;
            specItem.sortNum = spec.sortNum;
            specItem.values = [];

            specItem.selectedValues = [];
            var list = spec.valueList;
            (spec.valueList).forEach((value,valueIndex)=>{
              // console.log(value);
                var specValue = {};
                specValue.categoryId = value.categoryId;
                specValue.specId = value.specId;
                specValue.valueId = value.id;
                specValue.specName = spec.specName;
                specValue.valueName = value.infoName;
                specValue.sortNum = value.sortNum;
                specValue.checked = _that.getSepcValueCheck(specItem, specValue, data.specItems);

                specItem.values.push(specValue);
              if (specValue.checked != "") {
                specItem.selectedValues.push(specValue);
              }
              })
            _that.allSpecItems.push(specItem);
            // console.log(_that.allSpecItems);
            var tempData = {allSpecItems: _that.allSpecItems};
            // var html = template('contentTemplate', tempData);
            // document.getElementById('wrapperContent').innerHTML = html;

            _that.skuData.specItems = _that.allSpecItems;
            _that.skuData.skus = response.data.skus;

            //记录最开始的sku信息
            _that.oldSkuData = JSON.parse(JSON.stringify(_that.skuData));


          })

        }).catch(err => {
          _that.$message.error(err)
        })
      },
      getSepcValueCheck(specItem, specValue, specItems) {
        var checked = false;
        specItems.forEach(( spec,index)=>{
          if (spec.specId == specItem.specId) {
            spec.selectedValues.forEach(( value,valueIndex)=> {
              if (value.valueId == specValue.valueId) {
                checked = true;
                return false;
              }
            });
            return false;
          }
        });

        return checked;
      },

      //多选框变化
      checkChange(e,specId, valueId){
        console.log(e);
          // console.log('specId',specId);
          // console.log('valueId',valueId);
        var _that = this;
        _that.allSpecItems.forEach((specItem,itemIndex)=>{
          // console.log(specItem);
          // console.log('specId',specId);
          if(specItem.specId == specId){
            //选中
            if(e){
              var bFind = false;
              (specItem.selectedValues).forEach((value,valueIndex)=>{
                if ((value.specId == specId) && (value.valueId == valueId)) {
                  bFind = true;
                  return false;
                }
              })
              if (!bFind) {
                (specItem.values).forEach((value,valueIndex)=>{
                  if ((value.specId == specId) && (value.valueId == valueId)) {
                    // console.log(value);
                    specItem.selectedValues.push(value);
                    return false;
                  }
                })
              }

              return false;
            }else {//取消选中
              (specItem.selectedValues).forEach((value,valueIndex)=>{
                if ((value.specId == specId) && (value.valueId == valueId)) {
                  specItem.selectedValues.splice(valueIndex, 1);
                  // return false;
                }
              })
            }
          }
        })
        _that.computeSku();
        // console.log(_that.allSpecItems);

      },

      //计算全部的选择的属性值数组，并调用笛卡尔乘积运算得到完整的sku条目
      computeSel() {
        var _that = this;
        var ori = [];
        _that.allSpecItems.forEach((specItem,itemIndex)=>{
          var selectValues = specItem.selectedValues
          if (selectValues.length > 0) {
            ori.push(selectValues);
          }
        })
        return _that.descartes(ori);
      },

      //求笛卡尔乘积
      descartes(list) {
        //parent上一级索引;count指针计数
        var point = {};
        var result = [];
        var pIndex = null;
        var tempCount = 0;
        var temp = [];
        //根据参数列生成指针对象
        for (var index in list) {
          if (typeof list[index] == 'object') {
            point[index] = {'parent': pIndex, 'count': 0}
            pIndex = index;
          }
        }
        //单维度数据结构直接返回
        if (pIndex == null) {
          return list;
        }
        //动态生成笛卡尔积
        while (true) {
          for (var index in list) {
            tempCount = point[index]['count'];
            temp.push(list[index][tempCount]);
          }
          //压入结果数组
          result.push(temp);
          temp = [];
          //检查指针最大值问题
          while (true) {
            if (point[index]['count'] + 1 >= list[index].length) {
              point[index]['count'] = 0;
              pIndex = point[index]['parent'];
              if (pIndex == null) {
                return result;
              }
              //赋值parent进行再次检查
              index = pIndex;
            }
            else {
              point[index]['count']++;
              break;
            }
          }
        }
      },


      //计算sku价格表数据
      computeSku() {
        var _that = this;
        var ret = _that.computeSel();
        console.log(ret);
        var newSkuData = {};
        var skus = [];
        for (var i = 0; i < ret.length; i++) {
          var sku = {skuName: "", skuCode: "", skuPrice: "", skuQuantity: 1, sortNum: 0};
          sku.values = [];
          var skuCode = "";
          var skuName = "";
          ret[i].forEach((item)=>{
            sku.values.push({specId: item.specId, valueId: item.valueId});
            if (skuCode == "") {
              skuCode = String(item.valueId);
            } else {
              skuCode = skuCode + "," + String(item.valueId);
            }
            if (skuName == "") {
              skuName = item.valueName;
            } else {
              skuName = skuName + "," + item.valueName;
            }
          });
          sku.skuCode = skuCode;
          sku.skuName = skuName;
          sku.sortNum = i + 1;
          var skuInfo = _that.findSkuData(sku.skuCode);
          if (skuInfo != null) {
            sku.skuPrice = skuInfo.skuPrice;
            sku.skuQuantity = skuInfo.skuQuantity;
          }
          if (skuInfo == null) {
            //在最开始的表里面找下记录
            skuInfo = _that.findOldSkuData(sku.skuCode);
            if (skuInfo != null) {
              sku.skuPrice = skuInfo.skuPrice;
              sku.skuQuantity = skuInfo.skuQuantity;
            }
          }
          skus.push(sku);
        }

        _that.skuData.specItems = _that.allSpecItems;
        _that.skuData.skus = skus;
console.log(_that.skuData);
      },

      findSkuData(skuCode){
        var _that =this;
        var skuInfo = null;
        (_that.skuData.skus).forEach((sku,index)=>{
          if (sku.skuCode == skuCode) {
            skuInfo = sku;
            return false;
          }
        })
        return skuInfo;
      },

      findOldSkuData(skuCode){
        var _that =this;
        var skuInfo = null;
        (_that.oldSkuData.skus).forEach((sku,index)=>{
          if (sku.skuCode == skuCode) {
            skuInfo = sku;
            return false;
          }
        })
        return skuInfo;
      },

      //保存价格
      save(){
        var _that = this;
        if (!_that.skuData.skus) {
          _that.$message.error("没有可保存的价格数据")
          return;
        }

        if (_that.skuData.skus.length <= 0) {
          _that.$message.error("没有可保存的价格数据")
          return;
        }
        var saveSkuData = {specItems: []};
        saveSkuData.skus = _that.skuData.skus;
        (_that.skuData.specItems).forEach((specItem,itemIndex)=>{
          var selectedValues = specItem.selectedValues;
          if (selectedValues.length > 0) {
            var spec = {};
            spec.specId = specItem.specId;
            spec.specName = specItem.specName;
            spec.sortNum = specItem.sortNum;
            spec.selectedValues = selectedValues;
            saveSkuData.specItems.push(spec);
          }
        })
        console.log(saveSkuData);
        var data={
          "idProduct": _that.idProduct,
          "skuData": JSON.stringify(saveSkuData)
        }

        saveProductSkuPrice(data).then(response => {
          if(response.httpCode == 200){
            _that.$message({
              message: '保存成功',
              type: 'success'
            });
          }else{
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }


    }
  }
</script>
<style>
  /*处理input type = number的上下箭头*/
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }
</style>
<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 15px;
  }
</style>
