<template>
  <info-con title="规格信息：" class="sale-info-con">
    <div
      class="item"
      v-for="(pItem, pIndex) of propList"
      :key="'prop-item-' + pIndex"
    >
    <label class="label">规格参数：</label>
      <Input
        style="width:140px;margin-right:10px;"
        placeholder="请输入规格名称"
        @on-change="delAllSku(pItem, pIndex)"
        v-model="pItem.name"
        :readonly="isDetail || isEdit"
        :maxlength="30"
      />
      <div class="property-con">
        <div
          class="property-item"
          v-for="(vItem, vIndex) of pItem.valList"
          :key="'val-item-' + vIndex"
        >
          <Input
            class="prop-val"
            placeholder="请输入规格值"
            @on-change="delSkuVal(pItem, vIndex)"
            v-model="vItem.val"
            :readonly="isDetail || isEdit"
            :maxlength="30"
          />
          <Icon
            class="del-con"
            type="md-close-circle"
            color="#ed4014"
            :size="20"
            @click="delVal(pItem, vIndex)"
            v-if="!isDetail && !isEdit"
          />
        </div>
        <div class="add-btn">
          <Button
            type="info"
            shape="circle"
            size="small"
            @click="addVal(pItem)"
            v-if="!isDetail && !isEdit && pItem.valList.length < 10"
            >+ 添加属性值</Button
          >
        </div>
      </div>
      <Icon
        class="del-con"
        type="md-backspace"
        color="#ed4014"
        :size="30"
        @click="delProp(pIndex)"
        v-if="!isDetail && !isEdit"
      />
    </div>
    <div class="item">
      <div class="empty" />
      <div class="opt-btn" v-if="!isDetail && !isEdit">
        <Button type="info" @click="addProp" v-show="propList.length < 3"
          >+ 添加属性</Button
        >
      </div>
    </div>
    <div class="item">
      <label class="label">商品通证：</label>
      <RadioGroup v-model="data.commodityPass">
        <!-- <Radio :label="0" style="width:200px" :disabled="isDetail || isEdit">否</Radio> -->
        <Radio :label="1" style="width:200px" :disabled="isDetail || isEdit">是，自动生成Token</Radio>
        <Radio :label="2" style="width:200px" :disabled="isDetail || isEdit">是，使用外部既有Token</Radio>
    </RadioGroup>
    </div>
    <div class="item" style="text-align:center">
      <Button type="primary" style="margin:auto" @click="genSkuTable">生成价目表</Button>
    </div>
    <div class="tip" v-if="!isDetail && !isEdit">
      提示：如修改上述基本属性后，需重新生成价目表！缩略图建议尺寸100 *
      100，大小不得超过6MB
    </div>
    <Table v-if="showTable" border :columns="columns" :data="data.sku">
      <template slot-scope="{ row, index }" slot="originalPrice">
        <span v-if="isDetail">{{ row.originalPrice }}</span>
        <Input
          v-else
          placeholder="单位（RMB）"
          :value="row.originalPrice"
          @on-change="handleInputChange(index, 'originalPrice')"
          type="number"
          :readonly="isDetail"
        />
      </template>
      <template slot-scope="{ row, index }" slot="stock">
        <span v-if="isDetail">{{ row.stock }}</span>
        <Input
          v-else
          placeholder="整数值"
          :value="row.stock"
          @on-change="handleInputChange(index, 'stock')"
          @on-blur="onBlur(index,row)"
          type="number"
          :readonly="isDetail"
          :maxlength="9"
        />
      </template>
      <template slot-scope="{ row, index }" slot="coinName">
        <template v-if="isDetail || isEdit||data.sku[index].status==1">
          <label class="coinName-label">{{(row.coinNamePrefix+row.coinName)||'--'}}</label>
        </template>
        <template v-else>
          <div v-if="data.commodityPass == 0">
            <label>--</label>
          </div>
          <div v-if="data.commodityPass == 1">

        <label class="coinName-label">{{
          coinNamePrefix
        }}</label>
          <!-- <label class="coinName-label" style="color: #ed4014"
            >&nbsp;&nbsp;+&nbsp;&nbsp;</label
          > -->
          <Input
            placeholder="2-10位大写字母或数字"
            :value="row.coinName"
            @on-change="handleInputChange(index, 'coinName')"
            @on-blur="handleInputBlur(index, 'coinName')"
            style="width: 140px"
            :disabled="isDetail||data.sku[index].status==1"
            :maxlength="10"
          />
          </div>
          <div v-if="data.commodityPass ==2">
                <label class="coinName-label">{{
          coinNamePrefix
        }}</label>
          <Select :transfer=true v-model="data.sku[index].name" @on-change="getMoreParams(data.sku[index].name,index)" style="width: 140px;">
          <Option
            v-for="(item, index) of seriesList"
            :value="JSON.stringify(item)"
            :key="'series-option-' + index"
            >{{ item.labelName }}</Option
          >
        </Select>
      </div>
      </template>
      </template>
      <template slot-scope="{ row, index }" slot="weight">
        <span v-if="isDetail">{{ row.weight }}</span>
        <Input
          v-else
          placeholder="单位（KG）"
          :value="row.weight"
          @on-change="handleInputChange(index, 'weight')"
          type="number"
          :readonly="isDetail"
        />
      </template>
      <template slot-scope="{ row, index }" slot="image">
        <file-upload
          :ref="'fileUpload' + index"
          :width="46"
          style="margin-top: 5px"
          v-model="data.sku[index].upload.imageList"
          @input="handleUploadInput($event, index)"
          :maxNum="1"
          :defaultList="data.sku[index].upload.defaultImgList"
          :readonly="isDetail"
          showWatch
          :iconSize="16"
        />
      </template>

      <template slot-scope="{ index }" slot="opt">
        <Button type="error" size="small" @click="delSku(index)">删除</Button>
      </template>
    </Table>
  </info-con>
</template>

<script>
import InfoCon from './info-con'
import FileUpload from '_c/file-upload'
import config from '@/config'
import axios from 'axios'
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro
export default {
  props: {
    data: {
      type: Object,
      default: { sku: [] },
      commodityPass: ''
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    // isSelf: {
    //   type: Boolean,
    //   default: false
    // },
    isAgain: {
      type: Boolean,
      default: false
    },
    status: ''

  },
  components: {
    InfoCon,
    FileUpload
  },
  data () {
    return {
      propList: [{ name: '', valList: [{ val: '' }] }],
      showTable: false,
      columns: [],

      coinNamePrefix: '',
      seriesList: [{
      }],
      name: '',
      tokenNumber: '',
      numberStock: ''
      // rateList: [3, 4, 5, 6, 9, 10, 11, 13]
    }
  },
  computed: {
    platform () {
      return this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
    }
  },
  mounted () {
    this.genPropList(this.data.sku)
    this.genColumn()
    if (!this.platform) {
      this.getMerchantPrefixInfo()
    }
    if (!this.platform) {
      this.getunbindToken()
    }
    this.data.sku.forEach(item => {
      this.numberStock = item.stock
      if (this.isAgain) {
        item.republish = false
      }
      item.coinNamePrefix = item.coinName.substring(0, 4)
      item.coinName = item.coinName.substring(4)
      // console.log('coinName', item.coinName)
    })

    this.showTable = true
    setTimeout(() => {
    })
  },
  methods: {
    getMoreParams (val, index) {
      val = JSON.parse(val)
      this.tokenNumber = val.availableNumber
      this.data.sku[index].stock = ''
    },
    onBlur (index, val) {
      // console.log('4444', this.data.commodityPass)
      if (!this.isEdit && JSON.parse(val.stock) > this.tokenNumber && this.data.commodityPass == 2) {
        this.data.sku[index].stock = parseInt(this.tokenNumber)
        return this.$Notice.warning({ title: `填写库存过多 (实际数量：${parseInt(this.tokenNumber)})` })
      }
      if (this.isEdit && this.data.commodityPass == 2) {
        let number = JSON.parse(val.stock) - this.numberStock
        //  + this.data.sku[index].balanceNum
        if (number > this.data.sku[index].balanceNum) {
          this.data.sku[index].stock = parseInt(this.numberStock + this.data.sku[index].balanceNum)
          return this.$Notice.warning({ title: `填写库存过多 (实际数量：${parseInt(this.numberStock + this.data.sku[index].balanceNum)})` })
        }
      }
    },
    getMerchantPrefixInfo () {
      this.api({
        apiName: 'getMerchantPrefix',
        success: (res) => {
          this.coinNamePrefix = res.data
        }
      })
    },
    getunbindToken () {
      this.api({
        apiName: 'unbindToken',
        success: (res) => {
          this.seriesList = res.data
        }
      })
    },
    handleInputChange (index, key) {
      this.data.sku[index][key] = event.target.value
    },
    handleInputBlur (index, key) {
      if (this.isAgain) {
        if (key == 'coinName') {
          this.data.sku[index].republish = true
          this.data.sku[index].coinNamePrefix = this.coinNamePrefix
        }
      }
    },
    handleUploadInput (e, index) {
      console.log(index, this.data.sku)
      // this.data.sku[index].upload.imageList = e;
      // this.data.sku[index].upload.defaultImgList = e.slice(0)
    },

    addProp () {
      this.propList.push({ name: '', valList: [{ val: '' }] })
    },
    delAllSku (item, index) {
      this.data.sku = []

      this.propList[index].valList = [{ val: '' }]
      this.data.commodityPass = ''
      this.columns[0].title = ''
    },
    delSkuVal (item, index) {
      this.data.sku = []
      this.data.commodityPass = ''
      this.columns[0].title = ''
    },
    delProp (index) {
      this.propList.splice(index, 1)
    },
    addVal (item) {
      item.valList.push({ val: '' })
    },
    delVal (item, index) {
      item.valList.splice(index, 1)
    },
    delSku (index) {
      this.data.sku.splice(index, 1)
    },

    exportCer (row) {
      if (row.stock == 0) {
        return this.$Notice.warning({ title: '当前库存为0，无法导出！' })
      }
      let skuId = row.skuId
      axios({
        method: 'GET',
        url: `${baseUrl}/goods/exportCert`,
        params: { skuId },
        responseType: 'blob'
      }).then((res) => {
        let content = res.data
        let blob = new Blob([content])
        let fileName = 'test.xls'
        if ('download' in document.createElement('a')) {
          let link = document.createElement('a')
          link.download = fileName
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },

    genPropList (sku) {
      if (sku && sku.length !== 0) {
        let propHashTable = {}
        sku.forEach((sItem) => {
          if (!sItem.propertyList || sItem.propertyList.length === 0) {
            return
          }
          sItem.propertyList.forEach((pItem) => {
            if (propHashTable[pItem.propKey]) {
              propHashTable[pItem.propKey][pItem.propVal] = 'x'
            } else {
              propHashTable[pItem.propKey] = {
                [pItem.propVal]: 'x'
              }
            }
          })
        })
        this.propList = []
        for (let key in propHashTable) {
          let valList = []
          for (let vkey in propHashTable[key]) {
            valList.push({ val: vkey })
          }
          this.propList.push({ name: key, valList })
        }
      }
    },

    genSkuTable () {
      let check = true
      let title = ''
      if (!this.propList || this.propList.length === 0) {
        check = false
        title = '请添加属性！'
      }
      let propNameHashTable = {}
      this.propList.find((pItem) => {
        let propName = pItem.name
        if (!propName) {
          title = '属性名称不能为空！'
          check = false
          return true
        }
        if (propNameHashTable[propName]) {
          title = '属性名称不能重复！'
          check = false
          return true
        }
        if (
          [
            'originalPrice',
            'stock',
            'coinName',
            'image',
            'imageList',
            'defaultImgList',
            'propertyList'
          ].includes(propName)
        ) {
          title = '属性名称不符合规范！'
          check = false
          return true
        }
        propNameHashTable[propName] = true
        if (!pItem.valList || pItem.valList.length === 0) {
          title = '属性值不能为空！'
          check = false
          return true
        }
        pItem.valList.find((vItem) => {
          if (!vItem.val) {
            title = '属性值不能为空！'
            check = false
            return true
          }
        })
        for (var i = 0; i < pItem.valList.length - 1; i++) {
          for (var j = i + 1; j < pItem.valList.length; j++) {
            if (pItem.valList[i].val === pItem.valList[j].val) {
              title = '属性值不能重复！'
              check = false
              return true
            }
          }
        }
      })

      if (!check) {
        this.$Notice.warning({ title })
      } else {
        // console.log(typeof this.data.commodityPass)
        if (typeof this.data.commodityPass !== 'number') {
          return this.$Notice.warning({ title: '请先选择商品通证' })
        }
        this.genColumn()
        this.genSku()
        this.showTable = true
      }
    },
    genColumn () {
      let columns = []
      this.propList.forEach((pItem) => {
        columns.push({
          title: pItem.name,
          minWidth: 120,
          key: pItem.name,
          align: 'center'
        })
      })
      columns.push({
        title: '缩略图',
        slot: 'image',
        width: 240,
        align: 'center'
      })
      columns.push({
        title: '价格（￥）',
        slot: 'originalPrice',
        width: 160,
        align: 'center'
      })
      columns.push({
        title: '商品Token',
        slot: 'coinName',
        width: 230,
        align: 'center'
      })
      columns.push({
        title: '重量（KG）',
        slot: 'weight',
        width: 130,
        align: 'center'
      })
      columns.push({
        title: '库存',
        slot: 'stock',
        width: 160,
        align: 'center'
      })
      // columns.push({
      //   title: '税率',
      //   slot: 'rate',
      //   width: 110,
      //   align: 'center'
      // })
      // columns.push({
      //   title: '类型编码',
      //   slot: 'typeCode',
      //   width: 200,
      //   align: 'center'
      // })
      // if (this.isDetail) {
      //   columns.push({
      //     title: '发行量',
      //     key: 'issueNum',
      //     width: 160,
      //     align: 'center'
      //   })
      // }
      if (!this.isDetail && !this.isEdit && !this.isAgain) {
        columns.push({
          title: '操作',
          slot: 'opt',
          width: 80,
          align: 'center'
        })
      }
      // if (this.isDetail && this.isSelf) {
      //   columns.push({
      //     title: '操作',
      //     slot: 'opt2',
      //     width: 100,
      //     align: 'center'
      //   })
      // }
      this.columns = columns
    },
    genSku () {
      let resArr = []
      this.propList.forEach((item) => {
        resArr = this.genSkuData(item, resArr)
      })

      this.data.sku = resArr
    },
    genSkuData (prop, resArr) {
      let newArr = []
      let { name, valList } = prop
      if (resArr.length === 0) {
        valList.forEach((item) => {
          let propertyList = [{ propKey: name, propVal: item.val }]
          newArr.push({
            [name]: item.val,
            originalPrice: '',
            stock: '',
            coinName: '',
            coinNamePrefix: this.coinNamePrefix,
            name: '',
            republish: false,
            // availableNumber: '',
            image: '',
            propertyList,
            // rate: 0,
            // typeCode: '',
            weight: '',
            upload: {
              imageList: [],
              defaultImgList: []
            }
          })
        })
        // console.log('newArr1', newArr)
      } else {
        resArr.forEach((rItem) => {
          valList.forEach((vItem) => {
            let newItem = { ...rItem, [name]: vItem.val }
            newItem.propertyList = JSON.parse(JSON.stringify(newItem.propertyList))
            newItem.propertyList.push({
              propKey: name,
              propVal: vItem.val
            })
            newItem.upload = {
              imageList: [],
              defaultImgList: []
            }
            // console.log('newItem', newItem)
            newArr.push(newItem)
          })
        })
      }
      // console.log('newArr', newArr)
      return newArr
    }
  }
}
</script>

<style lang="less">
.sale-info-con {
  .item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .item .label {
    width: 140px;
    margin-right: 10px;
    text-align: right;
  }
  .item .property-con {
    flex: 1;
    padding: 20px;
    border: 1px solid #dcdee2;
    border-radius: 5px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .item .property-con .add-btn {
    width: 100%;
  }
  .del-con {
    margin-left: 5px;
    cursor: pointer;
  }
  .item .property-item {
    width: 240px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding-right: 30px;
    .prop-val {
      flex: 1;
    }
  }
  .item .empty {
    width: 150px;
  }
  .item .opt-btn {
    flex: 1;
    display: flex;
    justify-content: space-between;
  }
  .tip {
    color: #ed4014;
    font-size: 12px;
    margin: 20px 0 5px 0;
  }
  .token-label {
    font-size: 14px;
  }
}
</style>
