<template>
  <div class="style-information-component">
    <el-form-item label="商品图片" />
    <div class="upload-wrap">
      <el-upload ref="upImagesFiles" list-type="picture-card" :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove" :headers="headers" :data="dataObj" :file-list="form.imgs" :limit="20"
        :on-success="handleImageSuccess" :action="action" :before-upload="changeFiles" :disabled="true">
        <i slot="default" class="el-icon-plus" />
        <div slot="file" slot-scope="{ file }">
          <img v-if="!isVideo(file.imgPath)" class="el-upload-list__item-thumbnail" :src="file.imgPath">
          <video v-else class="el-upload-list__item-thumbnail" style="width: 148px;height: 148px;"
            :src="file.imgPath"></video>
          <span class="el-upload-list__item-actions">
            <span v-if="!isVideo(file.imgPath)" class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in" />
            </span>
            <span @click="playVideo(file.imgPath)">
              <i class="el-icon-video-play"></i>
            </span>
          </span>
        </div>
      </el-upload>
    </div>
    <el-form-item label="款式设置">
      <el-radio-group v-model="form.attrStyle" :disabled="true">
        <el-radio :label="0">单款式</el-radio>
        <el-radio :label="1">多款式</el-radio>
      </el-radio-group>
    </el-form-item>
    <div class="style-container">
      <div v-if="form.attrStyle === 0" class="single-style">
        <el-table :data="skuList" style="width: 100%" :header-cell-style="{ background: '#EEF3FF', color: '#333333' }">
          <el-table-column label="规格">
            <template slot-scope="scope">
              <el-input v-model="singleStyle.skuValue" :sss="scope" maxlength="20" />
            </template>
          </el-table-column>
          <el-table-column label="售价">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" :controls="false" :max="999999999" :min="0" :precision="2"
                :step="0.01" style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="原价">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.originalPrice" :controls="false" :max="999999999" :min="0"
                :precision="2" :step="0.01" style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.stockNumber" :controls="false" :max="999999999" :min="0"
                :precision="0" style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="重量(KG)">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.weight" :controls="false" :max="999" :min="0" :precision="2"
                :step="0.01" style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="赠送代金券">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.presenterVoucher" :controls="false" :min="0" :precision="2"
                :step="0.01" style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="代金券最大抵扣额度(一般设置全额抵扣)">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.voucherPrice" :controls="false" :min="0" :precision="6" :step="0.01"
                style="width: auto;" />
            </template>
          </el-table-column>
          <el-table-column label="商品绑定的代金券">
            <template slot-scope="scope">
              <el-select v-model="scope.row.voucherId" placeholder="请选择商品绑定的代金券">
                <el-option v-for="item in voucherList" :key="item.id" :label="item.voucherName" :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="国际条码">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sku" maxlength="20" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="multiple-styles">
        <div v-for="(skuAttr, index) in form.skuAttrList" :key="index" class="sku-attr-list">
          <el-form-item label="规格名">
            <el-input v-model="skuAttr.skuName" maxlength="20" :disabled="true" />
          </el-form-item>
          <el-form-item label="规格值">
            <div class="attr-value-list">
              <div v-for="(sku, index1) in skuAttr.values" :key="index + '-' + index1" class="main-diagram m-8">
                <!-- 去除了长度限制 -->
                <el-input v-model="sku.skuValue" :disabled="true" />
                <div v-if="skuAttr.needImg && index === 0" class="upload-wrap diagram-upload">
                  <div class="span-wrap">
                    <el-upload list-type="picture-card" :show-file-list="false" :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove" :headers="headers" :data="dataObj" :file-list="[sku]"
                      :multiple="false" :on-success="handleImageSuccess1" :action="action" :disabled="true">
                      <i v-if="!sku.image" slot="trigger" class="el-icon-plus" />
                      <div v-else class="attr-value-img">
                        <img class="attr-thumbnail" :src="sku.image">
                      </div>
                    </el-upload>
                    <div v-if="sku.image" class="attr-actions">
                      <span class="attr-preview" @click="handlePictureCardPreview({ imgPath: sku.image })">
                        <i class="el-icon-zoom-in" />
                      </span>
                      <span class="attr-delete" @click="handleRemove1(sku)">
                        <i class="el-icon-delete" />
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </div>
      <el-table highlight-current-row  @current-change="handleRowChange" :data="skuList" style="width: 100%" :header-cell-style="{ background: '#EEF3FF', color: '#333333' }">
        <!--  单选框 -->
        <el-table-column label="选择" align="center">
          <template slot-scope="scope">
            <div class="next-box">
              <div class="select-box" :class="addToCartParams.skuId == scope.row.skuId?'selectAct':''">
              <i class="el-icon-check" color=""></i>
            </div>
            </div>
           
          </template>
        </el-table-column>
        <el-table-column v-for="(skuAttr, index) in skuAttrName" :key="index" :label="skuAttr.skuName">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark"
              :content="scope.row.skuAttrCodeDTOList && scope.row.skuAttrCodeDTOList[index] | attrValueFilter(form.skuAttrList)"
              placement="top-start">
              <div class="tipsView">
                {{ scope.row.skuAttrCodeDTOList && scope.row.skuAttrCodeDTOList[index] |
        attrValueFilter(form.skuAttrList) }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="优惠价">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.price" :controls="false" :max="999999999" :min="0" :precision="2"
              :step="0.01" style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="市场价">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.originalPrice" :controls="false" :max="999999999" :min="0"
              :precision="2" :step="0.01" style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="供货价">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.manufacturerBasePrice" :controls="false" :max="999999999" :min="0"
              :precision="2" :step="0.01" style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="渠道价">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.manufacturerGuidePrice" :controls="false" :max="999999999" :min="0"
              :precision="2" :step="0.01" style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.stockNumber" :controls="false" :max="999999999" :min="0" :precision="0"
              style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="重量(KG)">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.weight" :controls="false" :max="999" :min="0" :precision="6"
              :step="0.01" style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="赠送代金券">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.presenterVoucher" :controls="false" :min="0" :precision="6" :step="1"
              style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="代金券最大抵扣额度(一般设置全额抵扣)">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.voucherPrice" :controls="false" :min="0" :precision="6" :step="0.01"
              style="width: auto;" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="国际条码">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sku" maxlength="20" :disabled="true" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="number-box">
      <el-input-number v-model="addToCartParams.number" size="large" :min="0" :max="numberAll"  label="请选择数量"></el-input-number>
      <span>选择的SKU商品库存数量如果是0，不能增加购买商品数量，需注意！！！！！</span>
    </div>
    <div class="btn-list">
      <el-button type="info" plain @click="cancel">取消</el-button>
      <el-button type="primary" @click="addCart">加入购物车</el-button>
    </div>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible" class="check-image-dialog" title="查看图片"
      center="center">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>

    <el-dialog width="30%" :append-to-body="true" :visible.sync="previewVideoVisible" class="check-image-dialog"
      title="预览视频" center="center">
      <div style="display: flex; align-items: center; justify-content: center;">
        <video controls autoplay muted style="width: 400px; height: 400px;" :src="dialogVideoUrl"></video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { uploadUrl } from '@/utils/request'
import { getToken } from '@/utils/auth'
import { isVideo } from '@/utils/index'
import { addShopCar } from '@/api/threeSelection'
export default {
  name: 'addComponent',
  filters: {
    attrValueFilter(map, list) {
      const hasChilds =
        list &&
        list.filter((skuAttr) => {
          const hasChild = skuAttr.values.some((attr) => attr.skuValue)
          return skuAttr.skuName && hasChild
        })
      if (!map) {
        return ''
      }
      const { code, valueCode } = map
      let codeStr = ''
      // eslint-disable-next-line array-callback-return
      hasChilds.map((item) => {
        const { values } = item
        values &&
          values.some((attr) => {
            const isSome = item.code === code && attr.valueCode === valueCode
            if (isSome) {
              codeStr = attr.skuValue
            }
            return isSome
          })
      })
      return codeStr
    }
  },
  props: {
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    voucherList: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVideoUrl: '',
      dialogVisible: false,
      previewVideoVisible: false,
      headers: {
        'Authorization-business': getToken(),
        'tenant': 'MDAwMA=='
      },
      action: uploadUrl,
      dataObj: {
        folderId: 1
      },
      fileList: [],
      //  记录当前是哪里增加或者删除的
      idx: null,
      //  添加到购物车的参数
      addToCartParams: {
        skuId: '',
        number:''
      },
      //  数量库存判断
      numberAll:0
    }
  },
  computed: {
    skuAttrName() {
      return (
        this.form.skuAttrList &&
        this.form.skuAttrList.filter((skuAttr) => {
          const hasChilds = skuAttr.values.some((attr) => attr.skuValue)
          return skuAttr.skuName && hasChilds
        })
      )
    },
    singleStyle() {
      if (this.form.skuAttrList && this.form.skuAttrList[0]) {
        return this.form.skuAttrList && this.form.skuAttrList[0].values[0]
      }
      return {
        skuValue: ''
      }
    },
    skuList() {
      // console.log(this.form)
      if (this.form.attrStyle === 0) {
        return this.form.skuList.slice(0, 1)
      }
      return this.form.skuList
    }

  },
  watch: {
    'form.skuAttrList': {
      handler(newVal, oldVal) {
        // 判断是否有规格值
        const hasChilds =
          this.form.skuAttrList &&
          this.form.skuAttrList.filter((skuAttr) => {
            const hasChild = skuAttr.values.some((attr) => attr.skuValue)
            return skuAttr.skuName && hasChild
          })
        // console.log(hasChilds);
        if (this.form.attrStyle === 1 && hasChilds.length) {
          this.skuFormat()
        }
      },
      deep: true
    },
    'form.skuList': {
      handler(newVal, oldVal) {
        // console.log(newVal)
        // console.log(oldVal)
        // 修复因为添加规格导致的价格归零的问题
        oldVal.forEach((item, index) => {
          // newVal[index] = Object.assign(item, newVal[index])
          for (const key in newVal[index]) {
            if (item[key]) {
              newVal[index][key] = item[key]
            }
          }
        })
        // console.log(newVal)
      },
      deep: true
    }
  },
  methods: {
    //  添加到购物车
    async addCart(){
      if(this.addToCartParams.skuId == ""){
        this.$message.warning("请选择你要加入购物车的商品")
        return
      }
      if(!this.addToCartParams.number){
        this.$message.warning("请选择要加入购物车的商品数量")
        return
      }
      console.log("添加到购物车",this.addToCartParams);
      let res = await addShopCar(this.addToCartParams);
      if(res.code == ""){
        this.$message.success("加入购物车成功")
        this.cancel()
      }
    },
    //  取消按钮
    cancel(){
      this.addToCartParams = {
        skuId: '',
        number:''
      }
      this.numberAll = 0
      this.$emit("cancel")
    },
          //  表格选择
    handleRowChange(val) {
      this.numberAll = val.stockNumber
      //  表格选择
      this.addToCartParams.skuId = val.skuId
    },
    isVideo,
    playVideo(url) {
      this.dialogVideoUrl = url
      this.previewVideoVisible = true
    },
    handleImageSuccess(response) {
      const url = response.data.url
      // eslint-disable-next-line vue/no-mutating-props
      this.form.imgs.push({
        imgPath: url
      })
    },
    // 移除图片
    handleRemove(file) {
      const { imgPath } = file
      // eslint-disable-next-line vue/no-mutating-props
      this.form.imgs = this.form.imgs.filter((item) => item.imgPath !== imgPath)
    },
    handleRemove1(file) {
      file.image = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.imgPath
      this.dialogVisible = true
    },
    handleImageSuccess1(response, file, fileList) {
      const url = response.data.url
      fileList[0].image = url
    },
    addAttrValue(index) {
      // eslint-disable-next-line vue/no-mutating-props
      this.form.skuAttrList[index].values.push({
        skuId: '',
        valueCode: '',
        skuValue: '',
        image: ''
      })
      if (this.idx == index) {
        this.form.deletes.splice(this.form.deletes.length - 1, 1)
      }
    },
    // 删除规格值
    delValue(index, index1) {
      if (index1 < this.form.skuAttrList[index].values.length - 1) return
      this.idx = index
      const newList = JSON.parse(JSON.stringify(this.form.skuAttrList[index]))
      const valueObj = {
        code: newList.code,
        skuId: newList.skuId,
        valueCode: newList.values[index1].valueCode
      }
      // eslint-disable-next-line vue/no-mutating-props
      this.form.deletes.push(valueObj)
      console.log(this.form.deletes, '删除')
      // console.log(this.valueObj)
      this.form.skuAttrList[index].values.splice(index1, 1)
      // console.log(this.form.skuAttrList[index].values);
    },
    // 删除规格名
    delSkuAttrList(index) {
      const newList = JSON.parse(JSON.stringify(this.form.skuAttrList[index]))
      newList.values.forEach((item) => {
        const valueObj = {
          code: newList.code,
          skuId: newList.skuId,
          valueCode: ''
        }
        valueObj.valueCode = item.valueCode
        // eslint-disable-next-line vue/no-mutating-props
        this.form.deletes.push(valueObj)
      })
      // eslint-disable-next-line vue/no-mutating-props
      this.form.skuAttrList.splice(index, 1)
    },
    delAttrValue1(row, index, arr) { },
    skuFormat() {
      const skuListArray = []
      const result = {
        originalPrice: 0,
        price: 0,
        productId: '',
        skuAttrCodeDTOList: [
          {
            code: '',
            valueCode: ''
          }
        ],
        skuId: '',
        skuImage: '',
        stockNumber: 0,
        voucherId: 0,
        voucherPrice: 0,
        weight: 0
      }
      const doExchange = (arr, depth) => {
        const map = {
          arr: []
        }
        for (var i = 0; i < arr[depth].length; i++) {
          map.arr.push(arr[depth][i])
          const { code, valueCode, attrId } = arr[depth][i]
          result.skuAttrCodeDTOList[depth] = {
            code,
            valueCode,
            attrId
          }
          if (depth !== arr.length - 1) {
            doExchange(arr, depth + 1)
          } else {
            skuListArray.push(JSON.parse(JSON.stringify(result)))
          }
        }
      }
      // this.form.skuList  = skuListArray
      // 获取规格值的所有组合
      const values = []
      // eslint-disable-next-line array-callback-return
      this.form.skuAttrList.map((skuItem, index) => {
        const attrList = []
        skuItem.code = skuItem.code || 'attr_code_' + index
        const { code } = skuItem
        skuItem.values &&
          // eslint-disable-next-line array-callback-return
          skuItem.values.map((attrItem, index1) => {
            attrItem.valueCode = skuItem.valueCode || code + '_value_' + index1
            const skuId = attrItem.skuId
            const attrId = attrItem.attrId
            if (attrItem.skuValue) {
              attrList.push({
                skuId,
                attrId,
                code,
                valueCode: attrItem.valueCode
              })
            }
          })
        if (attrList.length) {
          values.push(attrList)
        }
      })
      // 相互组合
      if (values.length) {
        doExchange(values, 0)
      }
      // console.log(this.form.skuList)
      // eslint-disable-next-line vue/no-mutating-props
      this.form.skuList = skuListArray.map((sku1) => {
        const { skuAttrList, skuAttrCodeDTOList } = sku1
        const skuAttrList1 = skuAttrCodeDTOList || skuAttrList
        const skuMap = this.form.skuList.filter((sku2) => {
          const skuAttrList2 = sku2.skuAttrList
          sku2.skuAttrCodeDTOList = skuAttrList2
          if (!skuAttrList2) return false
          const ids = []
          skuAttrList1.filter((item) => ids.push(item.id))
          const result = skuAttrList2.every((item) => ids.indexOf(item.attrValueId) !== -1)
          return result
        })
        let selectMap = sku1
        if (skuMap && skuMap.length) {
          selectMap = JSON.parse(JSON.stringify(skuMap[0]))
          selectMap.skuAttrCodeDTOList = skuAttrCodeDTOList
        }
        return selectMap
      })
    },
    changeFiles(file, fileList) {
      // console.log(file)
      // console.log(fileList)
      // eslint-disable-next-line prefer-const
      let uid = file.uid
      const isLt =
        file.size / 1024 / 5 >= 1 && file.size / 1024 / 1024 / 5 <= 1
      if (!isLt) {
        // this.$refs.upImagesFiles.abort()
        this.$message.error('上传文件大小不得小于5KB,不得大于5MB!')
        return false
      }
      // console.log(fileList)
    }
  }
}
</script>

<style lang="scss" scoped>
@import url("../../../styles/elDialog.scss");

.tipsView {
  width: 110px;
  height: 46px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  /*行数*/
}

.style-information-component {
  width: 100%;
  min-height: 300px;
  padding: 24px;
  background-color: rgb(255, 255, 255);

  .el-form-item {
    margin-bottom: 10px;
  }

  .attr-value-list {
    display: flex;
    flex-wrap: wrap;

    .main-diagram {
      position: relative;
      width: 180px;

      .span-wrap {
        position: relative;
        display: inline-block;
        margin-top: 10px;

        .attr-actions {
          line-height: 100px;
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          cursor: default;
          text-align: center;
          color: #fff;
          opacity: 0;
          font-size: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          -webkit-transition: opacity 0.3s;
          transition: opacity 0.3s;
          z-index: 1;

          &:hover {
            opacity: 1;

            .attr-preview {
              display: inline-block;
            }

            i {
              color: #fff;
              font-size: 20px;
            }
          }
        }

        .attr-preview {
          display: none;
          cursor: pointer;
          font-size: 20px;
          color: #fff;
        }

        .attr-delete {
          margin-left: 15px;
          color: #fff;
        }
      }

      .attr-value-img {
        width: 100%;
        height: 100%;

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }

  .m-8 {
    margin-right: 8px;
  }

  .upload-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 110px;
    cursor: pointer;
    border: 2px dashed #2e60f8;
    border-radius: 2px;
    background-color: #f8f9fb;
    text-align: center;
    font-size: 20px;
    color: #2e60f8;

    i {
      color: #2e60f8;
      font-size: 20px;
    }

    .upload-title {
      margin-left: 10px;
      font-size: 14px;
    }
  }

  .upload-wrap {
    margin-bottom: 25px;

    .el-upload-list__item {
      transition: none !important;
    }

    .el-upload,
    .el-upload-list__item {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    .el-progress,
    .el-progress-circle {
      width: 80px !important;
      height: 80px !important;
    }
  }

  .sku-attr-list {
    .el-input {
      width: 180px;
    }
  }

  .single-style {
    .el-input {
      max-width: 180px;
    }
  }

  .add-attr-btn {
    margin-bottom: 25px;
  }

  .check-image-dialog {
    .el-dialog {
      margin-top: 25px;

      .el-dialog__body {
        img {
          max-width: 100%;
          max-height: 100%;
          height: 500px;
          object-fit: contain;
        }
      }
    }
  }

  .delImg {
    position: absolute;
    top: 12px;
    margin-left: -24px
  }

  .delImg:hover {
    border-radius: 50%;
    color: #ffffff;
    background: #2e60f8;
    cursor: pointer;
  }
}


.next-box{
  display:flex;
  align-items: center;
  justify-content: center;
}
/* 选框选中 */
.select-box{
  width: 25px;
  height: 25px;
  border: 1px solid #000;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
.selectAct{
  background-color: #2e60f8;
  border:0;
}
.number-box{
  margin-top:30px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30px;
  span{
    color:red;
    font-weight: 600;
    font-size:18px;
  }
}
.btn-list{
  margin:40px 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30px;
}
</style>
