<template>
  <div v-if="multiSku === 1" style="padding: 16px 0px">
    <el-form ref="spec" :model="{ specList }" label-width="80px">
      <div v-for="(spec, index) in specList" :key="index" style="margin-bottom: 20px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="8">
            <el-form-item :label="`规格项${index + 1}`" :prop="`specList.${index}.name`" :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }">
              <el-input v-model="spec.name" :disabled="!spec.edit" @keyup.enter.native="spec.edit = false" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-button v-if="spec.edit" type="text" style="margin-left: 10px" @click="spec.edit = false">确定</el-button>
            <template v-else>
              <el-button type="text" style="margin-left: 10px" @click="spec.edit = true">编辑</el-button>
              <el-button type="text" class="del" style="margin-left: 10px" @click="specList.splice(index, 1)">删除</el-button>
            </template>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item :prop="`specList.${index}.vals`" :rules="{ required: true, message: '请完善规格值', trigger: 'blur' }">
            <el-col :span="24">
              <el-tag v-for="(tag, index) in spec.vals" :key="index" closable style="margin-right: 10px" @close="spec.vals.splice(index, 1)">{{ tag }}</el-tag>
              <el-input v-if="spec.editVals" v-model="specValTmp" style="display: inline-block;width: 120px; margin-right: 10px" size="mini" @keyup.enter.native="checkSpecVal(spec)" />
              <el-button v-if="!spec.edit&&!spec.editVals" type="text" style="margin-left: 10px" icon="el-icon-plus" size="small" @click="spec.editVals = true">添加规格值</el-button>
              <el-button v-if="spec.editVals" type="text" @click="checkSpecVal(spec)">确认</el-button>
            </el-col>
          </el-form-item>
        </el-row>
      </div>
    </el-form>
    <el-button type="primary" size="small" plain @click="specList.push({ name: '', vals: [], edit: true, editVals: false })" style="margin-bottom: 10px">添加规格</el-button>
    <el-button type="primary" size="small" style="margin-bottom: 10px;margin-left: 10px" :disabled="specList.length === 0" @click="genSku">重新生成SKU表格</el-button>
    <br>
    <el-form ref="sku" :model="{ skuList }">
      <table v-if="skuList instanceof Array && skuList.length > 0" class="spec-table" border="1" bordercolor="#CCC">
        <tr>
          <th :colspan="specList.length">商品规格</th>
          <th rowspan="2">SKU主图</th>
          <th rowspan="2">名称</th>
          <th rowspan="2">价格</th>
          <th rowspan="2">兑换价格</th>
          <th rowspan="2">成本</th>
          <th rowspan="2">库存</th>
          <th rowspan="2">启用</th>
        </tr>
        <tr>
          <th v-for="(spec, index) in specList" :key="index" style="width: 80px">{{ spec.name }}</th>
        </tr>
        <!-- k1:v1;k2:v2 -->
        <tr v-for="(sku, index) in skuList" :key="index">
          <td v-for="(spec, i) in specList" :key="i" style="min-width: 50px">
            {{ formatObj(sku.properties)[spec.name] }}
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.picUrl`" :rules="{ required: true, message: '请上传SKU图片', trigger: 'blur' }">
              <Upload v-model="sku.picUrl" :limit="1" style="height: 40px;overflow: hidden" />
            </el-form-item>
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.name`" :rules="{ required: true, message: '名称不能为空', trigger: 'blur' }">
              <el-input v-model="sku.name" />
            </el-form-item>
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.value`" :rules="[{ required: true, message: '请输入价格', trigger: 'blur' }, { pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }]">
              <el-input v-model="sku.value" />
            </el-form-item>
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.exchangePrice`" :rules="[{ required: true, message: '请输入兑换价格', trigger: 'blur' },{ pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }]">
              <el-input v-model="sku.exchangePrice" />
            </el-form-item>
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.cost`" :rules="[{ required: true, message: '请输入成本', trigger: 'blur' },{ pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }]">
              <el-input v-model="sku.cost" />
            </el-form-item>
          </td>
          <td>
            <el-form-item :prop="`skuList.${index}.quantity`" :rules="{ required: true, message: '请输入库存', trigger: 'blur' }">
              <el-input-number v-model="sku.quantity" :min="0" />
            </el-form-item>
          </td>
          <td style="padding: 0px 10px">
            <el-form-item :prop="`skuList.${index}.status`" :rules="{ required: true, message: '请选择状态', trigger: 'blur' }">
              <el-switch v-model="sku.status" active-color="#13ce66" inactive-color="#ff4949" />
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>
  </div>
</template>
<script>
import Upload from '@/components/ImageUpload'
export default {
  name: 'Spec',
  components: {
    Upload
  },
  props: {
    multiSku: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      specList: [],
      skuList: [],
      specValTmp: '',
      specifications: []
    }
  },
  methods: {
    formatObj(properties) {
      if (properties) {
        let obj = {}
        properties.split(';').forEach(item => {
          obj[item.split(':')[0]] = item.split(':')[1]
        })
        return obj
      }
      return {}
    },
    checkSpecVal(spec) {
      if (!this.specValTmp) {
        this.$message.warning('请输入规格值')
        return
      }
      if (spec.vals.find(item => item === this.specValTmp)) {
        this.$message.warning('规格值已存在')
        return 
      }
      spec.vals.push(this.specValTmp)
      this.specValTmp = ''
      spec.editVals = false
    },
    genSku() {
      this.$refs.spec.validate((valid, items) => {
        if (valid) {
          this.genSkuList()
        }
      })
    },
    genSkuList() {
      let specificationsTmp = []
      this.specList.forEach(spec => {
        spec.vals.forEach(val => {
          specificationsTmp.push({
            specification: spec.name,
            value: val
          })
        })
      })
      var specValues = []
      var spec = specificationsTmp[0].specification
      var values = []
      values.push(0)

      for (var i = 1; i < specificationsTmp.length; i++) {
        const aspec = specificationsTmp[i].specification

        if (aspec === spec) {
          values.push(i)
        } else {
          specValues.push(values)
          spec = aspec
          values = []
          values.push(i)
        }
      }
      specValues.push(values)
      var productsIndex = 0
      var skuList = []
      var combination = []
      var n = specValues.length
      for (var s = 0; s < n; s++) {
        combination[s] = 0
      }
      var index = 0
      var isContinue = false
      do {
        var specifications = []
        var properties = ''
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]]
          specifications.push(specificationsTmp[z].value)
          properties = `${properties ? (properties + ';') : ''}${specificationsTmp[z].specification}:${specificationsTmp[z].value}`
        }
        skuList[productsIndex] = {
          idx: productsIndex,
          name: specifications.toString(),
          picUrl: '',
          originPrice: 0.00,
          exchangePrice: 0.00,
          value: 0.00,
          cost: 0.00,
          quantity: 0,
          status: true,
          properties
        }
        productsIndex++

        index++
        combination[n - 1] = index
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0
            index = 0
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1
            }
          }
        }
        isContinue = false
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true
          }
        }
      } while (isContinue)
      this.skuList = skuList
    },
    getSkuList() {
      if (this.skuList.length === 0) {
        this.$message.warning('请完善规格并生成sku表格')
        return false
      }
      this.$refs.sku.validate((valid, items) => {
        if (valid) {
          this.$emit('valid', this.skuList)
        } else {
          if (items && Object.keys(items).length>0) {
            this.$message({
              message: items[Object.keys(items)[0]][0].message,
              type: 'warning'
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.spec-table {
  border-collapse: collapse;
  width: 100%;
  line-height: 32px;
  color: #606266;
  font-size: 14px;
  th {
    background-color: #ECECEC;
  }
  td {
    text-align: center;
  }
}
</style>