<template>
  <el-form size="mini" label-width="100px" :rules="attrRules">
    <!-- <el-form-item label="商品规格" prop="attr">
      <div class="attr-container">
        <el-form
          class="attr-wrap"
          v-for="(item, index) in Attr"
          ref="attr"
          :key="index"
          :model="item"
          size="mini"
          label-width="100px"
        >
          <el-form-item label="规格名：" class="attr-name">
            <el-input
              v-model="item.name"
              maxlength="8"
              placeholder="请输入"
              :disabled="locking"
            />
            <i class="el-icon-circle-close" @click="deleteAttr(index)"></i>
          </el-form-item>
          <el-form-item label="规格值：" class="attr-detail">
            <div
              v-for="(item1, index1) in item.value"
              :key="index1"
              class="detail-wrap"
            >
              <el-input
                v-model="item.value[index1]"
                maxlength="16"
                placeholder="请输入"
                :disabled="locking"
              />
              <i
                class="el-icon-circle-close"
                @click="deleteAttrValue(index, index1)"
              ></i>
            </div>
            <el-button
              type="text"
              :size="inputSize"
              @click.native="addAttrValue(index)"
              class="text-btn"
              >添加规格值</el-button
            >
          </el-form-item>
        </el-form>
        <div class="addAttr">
          <el-button
            :size="inputSize"
            @click.native="addAttr"
            :class="{ gray: Attr.length >= 3, 'cancel-btn': true }"
            >添加规格</el-button
          >
          <el-button
            v-if="!locking"
            :size="inputSize"
            type="primary"
            @click.native="buildDetail"
            class="confirm-btn"
            >生成明细</el-button
          >
          <el-button
            v-else-if="locking"
            :size="inputSize"
            type="primary"
            @click.native="resolveAttr"
            class="confirm-btn"
            >解锁规格</el-button
          >
          <p class="tips" v-if="Attr.length > 0">
            提示：编辑完成后，请点击“生成规格明细”填写相关明细，修改规格将会清空明细
          </p>
        </div>
      </div>
    </el-form-item> -->
    <el-form-item label="规格明细" v-if="tableData.length > 0">
      <table>
        <tr>
          <th v-for="(item, index) in Attr" :key="index">{{ item.name }}</th>
          <!-- <th>
                        <span>*</span> 成本价/元
                    </th> -->
          <th><span></span> 规格主图</th>
          <th><span></span> 价格/元</th>
          <th><span></span> 库存</th>
          <th><span></span> 打赏金额</th>
          <th><span></span> 绿通支付金额</th>
          <!-- <th><span></span> 编码</th>
          <th><span></span> 供应链skuID</th>
          <th><span></span> 进价</th> -->
        </tr>
        <tr v-for="(item, index) in tableData" :key="index">
          <td v-for="(item1, index1) in item.attribute" :key="index1">
            {{ item1 }}
          </td>
          <!-- <td>
                        <el-input v-model="item.cost" type="number" />
                    </td> -->
          <td class="upImg">
            <img v-if="item.pic" :src="item.pic || ''" class="mainImg" />
            <!-- <div class="add-img" v-else>+</div> -->
            <!-- <input type="file" class="file" :name="index" @change="changeImg" /> -->
          </td>
          <td>
            <!-- <el-input v-model="item.price" type="number" @blur="priceFmt" /> -->
            {{ item.price }}
          </td>
          <td>
            <!-- <el-input v-model="item.stock" type="number" /> -->
            {{ item.stock }}
          </td>
          <td>
            {{ item.rewardAmount }}
          </td>
          <td>
            {{ item.goldAmount }}
          </td>
          <!-- <td>
            <el-input v-model="item.code" type="number" />
          </td>
          <td>
            <el-input v-model="item.chainId" type="text" />
          </td>
          <td>
            <el-input v-model="item.cost" type="number" />
          </td> -->
        </tr>
        <!-- <tr>
          <td :colspan="col">
            <div class="batch">
              <p>批量设置</p>
              <div v-if="batchEdit.type">
                <el-input
                  v-model="batchEdit.value"
                  type="number"
                  oninput="value=value.length>9?value.slice(0,9):value"
                />
                <button class="text-btn" @click="saveBatch">保存</button>
                <button class="text-btn" @click="cancelBatch">取消</button>
              </div>
              <div class="batchBtn" v-else>
                <button
                  v-for="(item, i) in batchList"
                  :key="i"
                  class="text-btn"
                  @click="editBatch(i, item.value)"
                >
                  {{ item.name }}
                </button>
                <div class="batchImg">
                                    <input type="file" class="file" @change="batchImg" />
                                    <button>规格主图</button>
                                </div>
              </div>
            </div>
          </td>
        </tr> -->
      </table>
    </el-form-item>
    <el-form-item label="规格明细" v-else>
      <p style="line-height: 2">无</p>
    </el-form-item>
    <!-- <el-form-item label="划线价">
            <el-input v-model="oldPrice" type="number" />
        </el-form-item> -->
    <!-- <el-form-item label="商品原价">
      <el-input v-model="hypocrisy" type="number" />
    </el-form-item> -->
  </el-form>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'goodsAttr',
  props: {
    attrSku: {
      type: Array
    },
    skuTable: {
      type: Array
    },
    OldPrice: {
      type: Number
    },
    sales: {
      type: Number
    }
  },
  data() {
    return {
      locking: false, // 锁定规
      inputSize: 'mini',
      oldPrice: this.OldPrice, // 划线价
      hypocrisy: this.sales, // 划线价
      defaultImg: this.$Public.defaultImg, // 默认规格图
      ruleForm: {
        name: ''
      },
      attrRules: {
        attr: [
          {
            required: true,
            message: '请输入商品规格值'
          }
        ]
      }, // 基础校验
      batchList: [
        // {
        //     name: '成本价',
        //     value: 'cost'
        // },
        {
          name: '价格',
          value: 'price'
        },
        {
          name: '库存',
          value: 'stock'
        }
      ], // 批量设置列表,静态数据
      batchEdit: {
        name: '', // 批量编辑字段
        type: false,
        value: '' // 批量编辑数值
      },
      col: 0, // 表格列数，批量排版
      Attr: [
        {
          name: '',
          value: ['']
        }
      ], // 规格列表
      tableData: [], // 规格明细表格
      attribute: {}, // tableData单list的attribute信息
      info: {
        stock: '',
        code: '',
        pic: '',
        price: '',
        // cost: '',
        attribute: {}
      } // tableData单list信息
    };
  },
  created() {},
  computed: {},
  methods: {
    changeImg(e) {
      // 上传规格图片
      let index = e.target.name;
      let file = e.target.files[0];
      this.request.upPic({ prefix: 'other', file: file }).then(
        (res) => {
          this.tableData[index].pic = res;
          this.tableData = [...this.tableData];
        },
        (res) => {}
      );
    },
    batchImg(e) {
      // 批量上传图片
      let file = e.target.files[0];
      this.request.upPic({ type: 3, file: file }).then(
        (res) => {
          this.tableData.forEach((item) => {
            item.pic = res;
          });
        },
        (res) => {}
      );
    },
    editBatch(i, name) {
      // 批量设置
      this.batchEdit.name = name;
      this.batchEdit.type = true;
    },
    saveBatch() {
      this.batchEdit.type = false;
      // 遍历tableData,批量改数据
      this.tableData.forEach((item, index) => {
        // 价格和分润结构不同
        let name = this.batchEdit.name;
        // 分公司和能量站最多4.2折，价格不能小于0.03
        // if (name === 'price') {
        // if (this.batchEdit.value && +this.batchEdit.value < 0.03) {
        //   this.$message({
        //     message: '商品价格请勿小于0.03',
        //     type: 'warning'
        //   });
        //   this.batchEdit.value = '';
        // }
        // }
        item[name] = this.batchEdit.value;
      });
      // 清空input
      this.batchEdit.value = '';
    },
    cancelBatch() {
      this.batchEdit.type = false;
    },
    addAttr() {
      // 添加规格
      if (this.locking) {
        return;
      }
      if (this.Attr.length >= 3) {
        this.$message({
          message: '至多添加三个规格',
          type: 'warning'
        });
        return false;
      }
      let obj = {
        name: '',
        value: ['']
      };
      this.Attr.push(obj);
    },
    deleteAttr(index) {
      // 删除规格
      if (this.locking) {
        return;
      }
      this.Attr.splice(index, 1);
    },
    addAttrValue(index) {
      // 添加规格值
      if (this.locking) {
        return;
      }
      let val = '';
      this.Attr[index].value.push(val);
    },
    deleteAttrValue(i, j) {
      if (this.locking) {
        return;
      }
      // 删除规格值
      this.Attr[i].value.splice(j, 1);
    },
    resolveAttr() {
      // 解锁规格
      this.$confirm('此操作将清空规格明细, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 清空tableData/info/attribute
          this.tableData = [];
          this.attribute = {};
          this.info = {
            stock: '',
            code: '',
            pic: '',
            price: '',
            // cost: '',
            attribute: {}
          };
          this.locking = false;
        })
        .catch(() => {
          return false;
        });
    },
    getTable(i, len) {
      // 根据选择的attr生成规格明细列表
      this.Attr[i].value.forEach((item) => {
        this.$set(this.attribute, this.Attr[i].name, item);
        if (i === len - 1) {
          this.$set(this.info, 'attribute', { ...this.attribute });
          this.tableData.push({ ...this.info });
          return false;
        }
        this.getTable(i + 1, len);
      });
    },
    buildDetail() {
      let isPass = true;
      if (this.Attr.length <= 0) {
        this.$message({
          message: '请添加规格',
          type: 'warning'
        });
        return false;
      }
      this.Attr.forEach((item, i) => {
        if (item.name === '') {
          this.$message({
            message: '请填写规格名',
            type: 'warning'
          });
          isPass = false;
        }
        let value = item.value[0];
        if (value === '' || typeof value === 'undefined') {
          this.$message({
            message: '请填写规格值',
            type: 'warning'
          });
          isPass = false;
        }
      });
      if (!isPass) {
        return false;
      }
      // 锁定规格
      this.locking = true;
      this.col = this.Attr.length + 7;
      // 生成规格明细
      let len = this.Attr.length;
      this.getTable(0, len);
    },
    priceFmt() {
      // 分公司和能量站最多4.2折，价格不能小于0.03
      // this.tableData.map((it, index) => {
      // if (it.price && +it.price < 0.03) {
      //   this.$message({
      //     message: '商品价格请勿小于0.03',
      //     type: 'warning'
      //   });
      //   this.tableData[index].price = '';
      // }
      // });
    }
  },
  watch: {
    tableData: {
      handler(val) {
        console.log(val, 'aaaaaaaaaaaaaa');
        // val.map((it, index) => {
        // if (it.price && +it.price < 0.03) {
        //     this.$message({
        //         message: '商品价格请勿小于0.03',
        //         type: 'warning'
        //     });
        //     this.tableData[index].price = '';
        // }
        // });
        // 编辑规格明细时，向父组件传规格明细，库存
        this.$emit('editAttr', val);
      },
      deep: true
    },
    OldPrice(val) {
      this.oldPrice = val;
    },
    oldPrice(val) {
      // 编辑划线价
      this.$emit('getOldPrice', val);
    },
    sales(val) {
      this.hypocrisy = val;
    },
    hypocrisy(val) {
      // 编辑划线价
      this.$emit('getSales', val);
    },
    skuTable(val) {
      this.tableData = val;
    },
    attrSku: function (val) {
      this.Attr = [];
      // 根据根据tableData是否为空判断是上传还是编辑
      if (this.tableData.length <= 0) {
        // 新品页面时，根据传递的attrSku，计算Attr的规格名
        val.forEach((item) => {
          let list = {
            name: item,
            value: ['']
          };
          this.Attr.push(list);
        });
      } else {
        // 编辑页面时，计算Attr的规格名，根据tableData，推算Attr的规格值，并锁住
        val.forEach((item) => {
          let list = {
            name: item,
            value: []
          };
          this.Attr.push(list);
        });
        this.tableData.forEach((item) => {
          let attribute = item.attribute;
          for (let i in attribute) {
            this.Attr.forEach((item) => {
              if (item.name === i) {
                item.value.push(attribute[i]);
              }
            });
          }
        });
        this.Attr.forEach((item) => {
          item.value = [...new Set(item.value)];
        }); // value去重
        this.locking = true;
        this.col = this.Attr.length + 7;
      }
    }
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~assets/main.styl';

.el-input {
  width: 100px;
}

.batch {
  flex-x(flex-satrt);
  padding: 0 16px;
  word(14px, #333);

  button {
    color: blue;
    margin-left: 10px;
  }

  p {
    word(14px, #333);
    margin-right: 15px;
  }

  .batchBtn {
    flex-x(flex-satrt);

    .batchImg {
      position: relative;

      input {
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
        width: 60px;
        height: 40px;
        line-height: 40px;
        margin-left: 10px;
      }
    }
  }
}

.upImg {
  position: relative;
  vertical-align: middle;
  height: 100%;

  .add-img{
    width: 40px;
    height: 40px;
    border: 1px solid #e8e8e8;
    background: #F6F6F6;
    box-sizing: border-box;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    font-size: 24px;
    color: #999;
  }

  .mainImg {
    width: 40px;
    height: 40px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }

  input {
    width: 40px;
    height: 40px;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
}

.attr-container {
  padding: 10px;
  box-sizing: border-box;
  border();

  .addAttr {
    flex-x(flex-start);
    width: 98%;
    height: 40px;
    line-height: 40px;
    background: bk;
    padding-left: 20px;

    .tips {
      margin-left: 20px;
    }

    .gray {
      color: gray9;
      background: grayE;
      border();
    }
  }

  .attr-wrap {
    .el-input {
      width: 160px;
      margin-bottom: 5px;
    }

    .attr-name {
      position: relative;
      width: 100%;
      height: 40px;
      padding-top: 5px;
      box-sizing: border-box;
      background: bk;

      i {
        position: absolute;
        right: 20px;
        line-height: 30px;
        color: gray9;
      }

      .el-button--mini {
        margin-left: 10px;
      }
    }

    .attr-detail {
      .detail-wrap {
        position: relative;
        width: 160px;
        display: inline-block;
        margin-right: 10px;

        i {
          position: absolute;
          right: 10px;
          line-height: 30px;
          color: #999;
          top: 0;
        }
      }
    }

    .el-autocomplete {
      width: 200px;
    }
  }
}

table {
  border: 1px solid border-color;
  width: 100%;

  tr {
    height: 40px;
    line-height: 40px;
    text-align: left;
  }

  th {
    height: 54px;
    background: #F6F6F6;
    span {
      color: red;
    }

    text-align: center;
    font-weight: normal;
    color: gray3;
    // padding-left: 20px;
  }

  td {
    // padding-left: 20px;
    height: 54px;
    text-align: center;
    bor-top();
    bor-bottom();
    color: gray9;
    width: 80px;
  }
}

.confirm-btn {
  confirm-btn();
}

.cancel-btn {
  cancel-btn();
}

.text-btn {
  color: btn-color !important;
}
</style>
