<template>
  <div class="add-good-con">
    <Card v-if="loading" class="loading-card">
      <Spin fix size="large" />
    </Card>
    <Card v-else>
      <div class="head">
        <Icon type="md-bookmark" color="#2d8cf0" :size="28" />
        <label>{{ title }}</label>
      </div>
      <base-info :data="form.baseInfo" :isDetail="isDetail" :isEdit="isEdit" :isAgain="isAgain"/>
      <!-- <sale-info
        :data="form.saleInfo"
        :isDetail="isDetail"
        :isEdit="isEdit"
        :isAgain="isAgain"
        :isSelf="isSelf"
        :status="status"
        v-if="form.baseInfo.type!=6 && form.baseInfo.type!=5"
      /> -->
      <decipt-info :data="form.deciptInfo" :isDetail="isDetail" :status="status"/>
      <info-con title="资源信息" class="base-info-con"  v-if="form.baseInfo.type==5">
        <div class="series-info">
          <label class="label">打包价格：</label>
          <Input v-model="form.packageDTO.price" :disabled='isDetail' placeholder="请输入打包价格" style="width: 400px" />
        </div>
        <div class="package-resources">
          <label class="label">打包资源：</label>
          <div class="property-con">
          <div
          class="property-item"
          v-for="(item, index) of form.packageDTO.resource"
          :key="'prop-item-' + index"
        >
          <AutoComplete
            v-model="item.name"
            @on-search="handleSearch($event,index)"
            placeholder="请输入资源编号或名称"
            :disabled='isDetail'
            style="width:215px;">
            <Option v-for="(item,index) in item.integralMerchantNameList"  :value="item.name"
                    :key="'state-option-' + index">{{ item.name }}</Option>
          </AutoComplete>
          <Select
            placeholder="请选择资源规格"
            class="search-input"
            v-model="item.skuId"
            :disabled='isDetail'
            style="width: 215px;margin:0 20px;"
          >
            <Option
              v-for="(itemb,idx) of item.specificationsList"
              :value="itemb.skuId"
              :key="itemb.skuId"
              @click.native="handleSpecifications(idx,index)"
              >{{itemb.name}}</Option
            >

          </Select>
          <Input
            class="prop-val"
            placeholder="请设置资源数量"
            v-model="item.number"
            :disabled='isDetail'
            @on-blur="onBlur(index,item)"
            :maxlength="30"
            style="width:215px"
          />
          <span v-if="item.actualNumber&&item.actualNumber!=0">资源总数：{{ item.actualNumber}}</span>
          <Icon
            class="del-con"
            type="md-close-circle"
            color="#ed4014"
            v-if="!isDetail"
            :size="20"
            @click="delAge(index)"
          />
          </div>
          <div class="add-btn">
            <Button
              type="info"
              @click="addAge"
              v-if="!isDetail"
              >+ 添加</Button
            >
          </div>
        </div>
        </div>
        <div class="series-info">
            <label class="label">库存：</label>
            <Input v-model="form.packageDTO.stock" :disabled='isDetail' placeholder="请输入库存" style="width: 400px" @on-blur="stockBlur(form.packageDTO.stock)"/>
        </div>
      </info-con>
      <info-con title="规格信息" class="base-info-con"  v-if="form.baseInfo.type==6">
        <div class="series-info">
          <label class="label">商品价格：</label>
          <Input v-model="form.nftdto.price" :readonly="isDetail" placeholder="请输入商品价格" style="width: 400px" />
        </div>
        <div class="series-info">
        <label class="label">商品通证：</label>
        <RadioGroup v-model="form.nftdto.tzType" @on-change="changeTzType">
          <Radio label="1" :disabled="isDetail||isEdit||isAgain" style="width:200px;">内部发行</Radio>
          <Radio label="2" :disabled="isDetail||isEdit||isAgain" style="width:200px;">外部绑定</Radio>
        </RadioGroup>
      </div>
      <div class="series-info" v-if="form.nftdto.tzType==1">
        <label class="label">NFT类型：</label>
        <RadioGroup v-model="form.nftdto.type" @on-change="changeType">
          <Radio label="1" :disabled="isDetail||isEdit||isAgain" style="width:200px;">单个，不可拷贝</Radio>
          <Radio label="2" :disabled="isDetail||isEdit||isAgain" style="width:200px;">可拷贝</Radio>
        </RadioGroup>
      </div>
      <div class="series-info" v-if="form.nftdto.type==2">
        <label class="label">发行数量：</label>
        <Input v-model="form.nftdto.number" :readonly="isDetail||isEdit||isAgain" placeholder="请输入发行数量，正整数" style="width: 400px" />
      </div>
      <div class="series-info" v-if="form.nftdto.tzType==2">
        <label class="label">绑定NFT：</label>
        <Input v-model="form.nftdto.tokenId" v-if="isDetail||isEdit||isAgain" :readonly="isDetail||isEdit||isAgain" style="width: 400px" />
        <Select
            v-else
            placeholder="请选择NFT TOKENID"
            transfer
            v-model="form.nftdto.tokenId"
            style="width: 200px"
          >
        <Option
          :value="item.labelName"
          v-for="(item, index) of nftList"
          :key="`rate-option-${index}`"
          @click.native="handleNFT(item)"
          >{{ item.labelName }}</Option
        >
      </Select>
      </div>
      </info-con>
      <info-con title="销售信息：" class="base-info-con">
      <div class="series-info" v-if="(form.baseInfo.type==1||form.baseInfo.type==3)&&form.saleInfo.commodityPass!=0">
        <label class="label">是否允许延后提货：</label>
        <i-switch v-model="form.delayDelivery" :disabled="delayDeliveryDisabled || isDetail"/>
      </div>
      <div class="series-info">
        <label class="label">退换货类型：</label>
        <RadioGroup v-model="form.returnType">
          <Radio label="0" :disabled="isDetail" class="ivu-radio">不支持</Radio>
          <Radio label="1" :disabled="isDetail" class="ivu-radio">七天无理由退货</Radio>
          <Radio label="2" :disabled="isDetail" class="ivu-radio">
            自定义
            <Input v-model="form.returnReason" :disabled="isDetail" type="textarea" placeholder="请输入退货缘由" style="width: 200px" />
          </Radio>

        </RadioGroup>
      </div>
      <div class="series-time" v-if="form.baseInfo.type == 2">
        <label class="label">预售时间：</label>
          <Row class="time">
            <Col>
                <DatePicker type="date" :options="startOption" :readonly="isDetail" v-model="form.saleStartTime" placeholder="请选择开始时间" style="width: 200px"></DatePicker>
            </Col>
            <span>至</span>
            <Col>
                <DatePicker type="date" :options="endOption" :readonly="isDetail" v-model="form.saleEndTime" placeholder="请选择结束时间" style="width: 200px"></DatePicker>
            </Col>
          </Row>
      </div>
      <div class="series-time" v-if="form.baseInfo.type==2">
        <label class="label">预计提货时间：</label>
          <Row class="time">
            <Col>
                <DatePicker type="date" :options="drawStartOption" :readonly="isDetail" v-model="form.drawStartTime" placeholder="请选择开始时间" style="width: 200px"></DatePicker>
            </Col>
            <span>至</span>
            <Col>
                <DatePicker type="date" :options="drawEndOption" :readonly="isDetail" v-model="form.drawEndTime"  placeholder="请选择结束时间" style="width: 200px"></DatePicker>
            </Col>
          </Row>
      </div>
      <div class="series-time" v-if="form.baseInfo.type==2">
        <label class="label">首付比例：</label>
        <RadioGroup v-model="form.depositType">
          <Radio label="1" :disabled="isDetail" class="ivu-radio" style="width: 260px;">
          <span>固定比例</span>
          <Input v-model="fixedProportion" :disabled="isDetail" style="width: 100px"/>
              <span>%</span>
            <!-- </Input> -->
          </Radio>
          <Radio label="2" :disabled="isDetail" class="ivu-radio" style="width: 260px">
          <span>固定金额</span>
            <Input v-model="fixedAmount" :disabled="isDetail" style="width: 100px"/>
              <span>元</span>
            <!-- </Input> -->
          </Radio>
        </RadioGroup>
      </div>
      <div class="series-time" v-if="form.baseInfo.type==3">
        <label class="label">拍卖保证金：</label>
        <Input v-model="form.buyerDeposit" :readonly='isDetail' type="number" style="width: 100px;">
        </Input>
      </div>
      <div class="series-time" v-if="form.baseInfo.type==3">
        <label class="label">出价最小增幅：</label>
        <Input v-model="form.priceIncrease" :readonly='isDetail' type="number" style="width: 100px;">
        </Input>
      </div>
      <div class="series-time" v-if="form.baseInfo.type==3">
        <label class="label">结束时间：</label>
        <DatePicker type="date" :options="buyEndOption" :readonly="isDetail" v-model="form.endTime" placeholder="请选择结束时间" style="width: 200px"></DatePicker>
      </div>
      <div class="series-info">
        <label class="label">商品备注：</label>
          <Input v-model="form.note" :readonly="isDetail" type="textarea" placeholder="商品备注" style="width: 200px" />
      </div>
<!--       <div class="series-info" v-if="form.baseInfo.type==4">-->
<!--        <label class="label">库存：</label>-->
<!--          <Input v-model="form.stock" type="number" placeholder="商品库存" style="width: 200px" />-->
<!--      </div>-->
<!--       <div class="series-info" v-if="form.baseInfo.type==4">-->
<!--        <label class="label">所需积分：</label>-->
<!--          <Input v-model="form.pnum" type="number" placeholder="所需积分" style="width: 200px" />-->
<!--      </div>-->

      </info-con>
      <info-con title="溯源信息" class="base-info-con">
        <div class="series-info">
        <label class="label">溯源编号：</label>
        <Input v-model="form.traceabilityNumber" :readonly="isDetail" placeholder="请输入溯源系统的商品溯源编号(非必填)" style="width: 400px" />
      </div>
      </info-con>
      <div class="submit-con">
        <Button
          type="primary"
          @click="handleSubmit"
          v-if="!isDetail"
          :loading="submitLoading"
          >提交商品信息</Button
        >
      </div>
    </Card>
  </div>
</template>

<script>
import BaseInfo from './base-info'
import SaleInfo from './sale-info'
import DeciptInfo from './decpit-info'
import { getPosterFromVideoUrl } from '@/libs/tools'
import { mapMutations } from 'vuex'
import InfoCon from './info-con'
import { formatTime } from '../../../libs/ali-oss'
export default {
  name: 'add_good',
  components: {
    BaseInfo,
    SaleInfo,
    DeciptInfo,
    InfoCon
  },
  computed: {
    title () {
      if (this.routeName === 'update_good') {
        return '编辑商品 - 填写商品信息'
      } else if (this.routeName == 'good_detail') {
        return '商品详情'
        // this.isSelf // : `商品详情（ 品牌商：${this.form.brandName} ）`
      } else if (this.routeName === 'again_good') {
        return '重新发布商品 - 填写商品信息'
      } else {
        return '发布商品 - 填写商品信息'
      }
    },
    isDetail () {
      return this.routeName === 'good_detail'
    },
    isAdd () {
      return this.routeName === 'add_good'
    },
    isEdit () {
      return this.routeName === 'update_good'
    },
    isAgain () {
      return this.routeName === 'again_good'
    },
    isSelf () {
      return this.form.brandId === this.$store.state.admin.brandId
    },
    status () {
      return this.form.baseInfo.type
    }
  },
  data () {
    return {
      routeName: '',
      delayDeliveryDisabled: false,
      form: {
        brandId: '',
        brandName: '',
        goodsId: '',

        // templateId: '',
        baseInfo: {
          name: '', // 商品名称
          description: '', // 商品描述
          prop: [{ name: '', val: '' }], // 商品属性
          categoryId: [], // 类目选择
          type: '6'// 商品类型

        },
        saleInfo: {
          sku: [],
          imgObj: {},
          commodityPass: ''
          // statu:this.status
        },
        deciptInfo: {
          video: '',
          videoList: [],
          nftFile: '',
          nftEnclosureList: [],
          videoThumb: '',
          thumb: '',
          thumbList: [],
          detailPictures: [],
          detailDescribe: '',
          defaultDetailPicture: [],
          defaultVideoList: [],
          defaultThumbList: [],
          defaultNftEnclosureList: []
          // statu:this.status
        },
        returnType: '', // 退货类型
        returnReason: '', // 退货理由
        note: '', // 商品备注
        buyerDeposit: '', // 买家保证金
        priceIncrease: '', // 出价最小增幅
        endTime: '', // 结束时间
        deposit: '', // 首付比例
        depositType: '', // 首付比例类型
        drawStartTime: '', // 预计提货开始时间
        drawEndTime: '', // 预计提货结束时间
        saleStartTime: '', // 预售开始时间
        saleEndTime: '', // 预售结束时间
        stock: '', // 积分库存
        pnum: '', // 积分数量
        traceabilityNumber: '', // 溯源编号
        delayDelivery: false, // 延迟提货
        packageDTO: {
          resource: [{ integralMerchantNameList: [], goodsId: '', skuId: '', number: '', specificationsList: [], actualNumber: '' }], // 打包资源
          price: '', // 打包价格
          stock: ''// 库存
        },
        nftdto: {
          number: '', // 发行数量：只有商户选择“可拷贝”时，才会出现
          price: '', // 商品价格
          type: '', // NFT类型（1.单个，不可考贝 2.可拷贝）
          tzType: '', // 1.内部发行 2.外部绑定
          tokenId: '' // 绑定的外部通证id
        }

      },
      skuNumber: '',
      loading: true,
      expressList: [],
      profitList: [],
      integralMerchantNameList: [],
      specificationsList: [],
      idx: '',
      fixedProportion: '',
      fixedAmount: '',
      nftList: [],
      submitLoading: false,
      startOption: {
        // 指定开始限制时间
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      endOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      drawStartOption: {
        // 指定开始限制时间
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      drawEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      buyEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    addAge () {
      this.form.packageDTO.resource.push({ integralMerchantNameList: [], goodsId: '', skuId: '', number: '', specificationsList: [], actualNumber: '' })
    },
    changeTzType () {
      this.form.nftdto.type = ''
      this.form.nftdto.number = ''
      this.form.nftdto.tokenId = ''
    },
    changeType () {
      this.form.nftdto.number = ''
    },
    delAge (index) {
      this.form.packageDTO.resource.splice(index, 1)
    },
    handleNFT (val) {
      console.log(val)
      this.form.nftdto.number = val.availableNumber
    },
    handleSearch (goodsInfo, index) {
      if (!goodsInfo) {
        return this.$Message.warning('请先输入资源编号以便查询！')
      }
      this.api({
        apiName: 'spugetbyvague',
        postdata: goodsInfo,
        success: (res) => {
          this.form.packageDTO.resource[index].integralMerchantNameList = res.data
          if (this.form.packageDTO.resource[index].integralMerchantNameList.length === 1) {
            let goodsId = this.form.packageDTO.resource[index].integralMerchantNameList[0].goodsId
            this.api({
              apiName: 'skugetbygoodsId',
              postdata: goodsId,
              success: (res) => {
                let arr = []
                let list = this.form.packageDTO.resource[index].specificationsList
                if (list && list.length > 0) {
                  for (let item of res.data) {
                    if (list.find(x => { return x.skuId === item.skuId })) {
                      item.stock = list.find(x => { return x.skuId === item.skuId }).stock
                    }
                    arr.push(item)
                  }
                } else {
                  arr = res.data
                }
                this.form.packageDTO.resource[index].specificationsList = arr
              }
            })
          }
        }
      })
    },
    handleSpecifications (idx, index) {
      this.idx = idx
      this.form.packageDTO.resource[index].number = ''
      for (var i = 0; i < this.form.packageDTO.resource.length - 1; i++) {
        for (var j = i + 1; j < this.form.packageDTO.resource.length; j++) {
          if (this.form.packageDTO.resource[i].skuId === this.form.packageDTO.resource[j].skuId) {
            let title = '规格信息不能重复！'
            this.form.packageDTO.resource[index].skuId = ''
            return this.$Notice.error({ title })
          }
        }
      }
    },
    onBlur (index, val) {
      for (let i = 0, len = val.specificationsList.length; i < len; i++) {
        if (val.specificationsList[i].skuId === val.skuId) {
          this.idx = i
          break
        }
      }
      let idx = this.idx

      this.form.packageDTO.resource[index].actualNumber = this.form.packageDTO.resource[index].specificationsList[idx].stock
      this.$set(this.form.packageDTO.resource, index, this.form.packageDTO.resource[index])
      let stockNumber = JSON.parse(val.number) * this.form.packageDTO.stock
      if (stockNumber > this.form.packageDTO.resource[index].actualNumber) {
        this.form.packageDTO.resource[index].number = ''
        return this.$Notice.warning({ title: `库存*填写的资源量不能超过总资源数量` })
      }
    },
    stockBlur (val) {
      let skuNumber = this.form.packageDTO.resource
      skuNumber.forEach((item, index) => {
        let number = item.number * val
        let n = NaN
        for (let i = 0, len = item.specificationsList.length; i < len; i++) {
          if (item.specificationsList[i].skuId === item.skuId) {
            n = i
            break
          }
        }
        if (number > item.specificationsList[n].stock) {
          this.form.packageDTO.resource[index].number = ''
          return this.$Notice.warning({ title: `库存 * 填写的资源量不能超过总资源数量` })
        }
      })
    },
    requestOptionData () {
      // 获取快递模板
      this.api({
        apiName: 'templateList',
        success: (res) => {
          this.expressList = res.data
        }
      })
    },
    getNftList () {
      // 获取外部NFT
      this.api({
        apiName: 'externnftlist',
        success: (res) => {
          // console.log('333', this.nftList)
          this.nftList = res.data
        }
      })
    },
    getDelayDelivery () {
      if (!this.isDetail) {
        this.api({
          apiName: 'merchantDelayDelivery',
          success: (res) => {
            if (res.data == 0) {
              this.delayDeliveryDisabled = true
            }
          }
        })
      }
    },
    getTemplateorshopquery () {
      if (this.isAdd) {
        this.api({
          apiName: 'templateorshopquery',
          success: (res) => {
          }
        })
      }
    },
    requestGoodDetail (goodsId) {
      this.loading = true
      this.api({
        apiName: 'getGoodDetail',
        postdata: { goodsId },
        success: (res) => {
          let {
            brandId,
            brandName,
            // templateId,
            name,
            description,
            prop,
            skus,
            imgList,
            video,
            videoThumb,
            thumb,
            detail,
            type,
            note,
            returnType,
            traceabilityNumber,
            delayDelivery,
            returnReason,
            categoryName,
            categoryIds,
            preSaleVO,
            auctionVO,
            commodityPass,
            goodsPackageVO,
            goodsNftVO,
            nftFile
          } = res.data

          this.form.brandId = brandId
          this.form.brandName = brandName
          // this.form.templateId = templateId
          this.form.note = note
          this.form.returnType = returnType.toString()
          this.form.returnReason = returnReason
          this.form.traceabilityNumber = traceabilityNumber
          if (delayDelivery == 0) {
            this.form.delayDelivery = false
          } else {
            this.form.delayDelivery = true
          }
          if (auctionVO) {
            this.form.buyerDeposit = auctionVO.buyerDeposit
            this.form.priceIncrease = auctionVO.priceIncrease
            this.form.endTime = formatTime(auctionVO.endTime)
          }
          this.form.baseInfo = {
            name,
            description,
            prop: JSON.parse(prop),
            type: type.toString(),
            categoryId: this.isAgain ? JSON.parse(categoryIds) : categoryName
          }
          let newSku = []
          skus.forEach((item) => {
            let { image, propertyList } = item
            let upload = {
              imageList: [image],
              defaultImgList: [image]
            }
            let prop = {}
            propertyList.forEach((pItem) => {
              prop[pItem.propKey] = pItem.propVal
            })
            newSku.push({ ...item, ...prop, upload })
          })
          this.form.saleInfo.sku = newSku
          this.form.saleInfo.commodityPass = commodityPass
          this.form.deciptInfo = {
            nftFile,
            nftEnclosureList: [nftFile],
            video,
            videoList: [video],
            videoThumb,
            thumb,
            thumbList: [thumb],
            detailPictures: JSON.parse(imgList),
            detailDescribe: detail,

            defaultDetailPicture: JSON.parse(imgList),
            defaultVideoList: [video],
            defaultThumbList: [thumb],
            defaultNftEnclosureList: [nftFile]
          }
          if (!video) {
            this.form.deciptInfo.video = ''
            this.form.deciptInfo.defaultVideoList = []
          }
          if (!nftFile) {
            this.form.deciptInfo.nftFile = ''
            this.form.deciptInfo.defaultNftEnclosureList = []
          }
          if (type == 2) {
            this.form.depositType = preSaleVO.depositType.toString()
            if (this.form.depositType == 1) {
              this.fixedProportion = preSaleVO.deposit
            } else {
              this.fixedAmount = preSaleVO.deposit
            }
            // this.form.deposit = preSaleVO.deposit
            this.form.drawEndTime = formatTime(preSaleVO.drawEndTime)
            this.form.drawStartTime = formatTime(preSaleVO.drawStartTime)
            this.form.saleEndTime = formatTime(preSaleVO.saleEndTime)
            this.form.saleStartTime = formatTime(preSaleVO.saleStartTime)
          }
          if (goodsPackageVO) {
            goodsPackageVO.resource.forEach((item, index) => {
              item.name = item.goodsName
              let stock = item.sku.number + (item.number * goodsPackageVO.stock)
              // console.log('stock', stock)
              item.specificationsList = [
                { name: item.sku.name, skuId: item.sku.skuId, stock: stock }
              ]
              item.skuId = item.sku.skuId
            })
            this.form.packageDTO = goodsPackageVO
          }

          if (goodsNftVO) {
            goodsNftVO.type = goodsNftVO.type.toString()
            goodsNftVO.tzType = goodsNftVO.tzType.toString()
            // goodsNftVO.tokenId = goodsNftVO.tokenId

            this.form.nftdto = goodsNftVO
            // console.log('22222222', this.form.nftdto)
          }
          // this.form.nftdto = nftdto
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      let { goodsId } = this.$route.query
      this.form.goodsId = goodsId
      this.routeName = routeName
      if (routeName == 'update_good' || routeName == 'good_detail' || routeName == 'again_good') {
        this.requestGoodDetail(goodsId)
      } else {
        this.loading = false
      }
    },
    checkForm () {
      let errMsg = ''
      let form = {
        auctionDTO: {},
        pointsExchangeDTO: {},
        preSaleDTO: {},
        skuList: [{
          coinName: '',
          originalPrice: '',
          nftSalesType: '',
          propertyList: [{
            propKey: '',
            propVal: ''
          }],
          republish: '',
          skuId: '',
          stock: ''
        }],
        packageDTO: {},
        nftdto: {}
      }

      let {
        goodsId,
        // templateId,
        baseInfo,
        saleInfo,
        deciptInfo,
        returnType,
        returnReason,
        note,
        deposit,
        depositType,
        buyerDeposit,
        priceIncrease,
        drawStartTime,
        drawEndTime,
        saleStartTime,
        saleEndTime,
        endTime,
        stock,
        pnum,
        traceabilityNumber,
        delayDelivery,
        nftdto,
        // packagePrice
        packageDTO
      } = this.form
      form.goodsId = goodsId
      if (!baseInfo) {
        return { errMsg: '请完善基本信息！' }
      }
      if (!baseInfo.name) {
        return { errMsg: '请填写 基本信息 - 商品名称！' }
      }
      if (!baseInfo.type) {
        return { errMsg: '请填写 基本信息 - 商品类型！' }
      }
      if (!baseInfo.description) {
        return { errMsg: '请填写 基本信息 - 商品描述！' }
      }
      // if (
      //   (!baseInfo.prop ||
      //   baseInfo.prop.length === 0 ||
      //   !baseInfo.prop[0].name ||
      //   !baseInfo.prop[0].val)
      // ) {
      //   return { errMsg: '请填写 基本信息 - 商品属性！' }
      // }
      if (
        (!baseInfo.categoryId ||
        baseInfo.categoryId.length === 0)
      ) {
        return { errMsg: '请填写 基本信息 - 类目选择！' }
      }
      form = { ...form, ...baseInfo }
      // 销售信息
      if (baseInfo.type != 6 && baseInfo.type != 5) {
        if (
          (!saleInfo.sku ||
        saleInfo.sku.length === 0)
        ) {
          return { errMsg: '请完善规格信息！' }
        }
        let skuIndex = 0
        saleInfo.sku.forEach((item) => {
        // console.log('item', item)
          if (!item.originalPrice && item.originalPrice != 0) {
            errMsg = '请填写 规格信息 - 价格！'
          }
          if (!item.stock) {
            errMsg = '请填写 规格信息 - 库存！'
          }
          if (this.isAdd && saleInfo.commodityPass == 1 && !item.coinName) {
            errMsg = '请填写 规格信息 - Token名称！'
          }
          if (!item.weight) {
            errMsg = '请填写 规格信息 - 重量！'
          }
          if ((item.weight == 0 || (item.weight && item.weight < 0) || item.weight > 9999)) {
            errMsg = '规格信息 - 重量 格式不正确！'
          }
          item.weight = parseFloat(item.weight)
          if (!/^[0-9]+(.[0-9]{1,2})?$/.test(item.weight)) {
            errMsg = '规格信息 - 重量 最多至小数点后两位！'
          }
          // console.log('coinName', item.coinName)
          if (this.isAdd && saleInfo.commodityPass == 1 && !/^[A-Z0-9]{2,10}$/.test(item.coinName)) {
            errMsg = '规格信息 - Token名称 格式不正确！'
          }
          if ((item.originalPrice <= 0 || item.originalPrice > 999999)) {
            errMsg = '规格信息 - 价格 格式不正确！'
          }
          item.originalPrice = parseFloat(item.originalPrice)
          if (!/^[0-9]+(.[0-9]{1,2})?$/.test(item.originalPrice)) {
            errMsg = '规格信息 - 价格 最多至小数点后两位！'
          }
          if ((item.stock < 0 || !/^\d+$/.test(item.stock) || item.stock > 99999999)) {
            errMsg = '规格信息 - 库存 格式不正确！'
          }
          if (
            item.upload &&
          item.upload.imageList &&
          item.upload.imageList.length !== 0
          ) {
            saleInfo.sku[skuIndex].image = item.upload.imageList[0]
          }
          skuIndex++
        })
        if (errMsg) {
          return { errMsg }
        }

        form.skuList = saleInfo.sku
        form.commodityPass = saleInfo.commodityPass

        if (form.commodityPass == 1) {
          form.skuList = form.skuList.map(item => {
            let {
              coinName,
              coinNamePrefix,
              ...other
            } = item
            return { coinName: coinNamePrefix + coinName, ...other }
          })
        }
        if (form.commodityPass == 2 && !this.isEdit) {
          form.skuList.forEach(item => {
            let name = JSON.parse(item.name)
            item.commodityPassId = name.commodityPassId
            item.coinName = `${item.coinNamePrefix}${name.labelName}`
          })
        }
      }
      if (baseInfo.type == 6 && saleInfo.sku.length != 0) {
        // console.log(11111, saleInfo.sku)
        form.skuList = saleInfo.sku
      }
      // form.skuList = skuList
      // console.log('form.skuList', form.skuList)
      // 图文信息
      if (!deciptInfo) {
        return { errMsg: '请完善图文描述！' }
      }
      if (!deciptInfo.detailPictures ||
        deciptInfo.detailPictures.length === 0) {
        return { errMsg: '请上传 图文描述 - 商品图片！' }
      }
      // if (!deciptInfo.videoList || deciptInfo.videoList.length === 0) {
      //   return { errMsg: '请上传 图文描述 - 商品视频！' }
      // }
      if (!deciptInfo.thumbList || deciptInfo.thumbList.length === 0) {
        return { errMsg: '请上传 图文描述 - 缩略图！' }
      }
      if (deciptInfo.detailDescribe.length > 18000) {
        return { errMsg: '图文描述 - 详情描述 内容长度过长！' }
      }
      if (deciptInfo.detailDescribe.length == 0) {
        return { errMsg: '图文描述 - 请输入详情描述！' }
      }
      // form = { ...form, ...deciptInfo }
      form.thumb = deciptInfo.thumbList[0]
      form.imgList = JSON.stringify(deciptInfo.detailPictures)
      form.detail = deciptInfo.detailDescribe
      if (deciptInfo.videoList && deciptInfo.videoList.length !== 0) {
        form.video = deciptInfo.videoList[0]
        form.videoPoster = getPosterFromVideoUrl(form.video)
      } else {
        form.video = ''
        form.videoPoster = ''
      }
      if (deciptInfo.nftEnclosureList && deciptInfo.nftEnclosureList.length !== 0) {
        form.nftFile = deciptInfo.nftEnclosureList[0]
        // form.videoPoster = getPosterFromVideoUrl(form.video)
      } else {
        form.nftFile = ''
      }
      // console.log('form',form)
      // 快递模板
      // if (!templateId) {
      //   return { errMsg: '请选择快递模板！' }
      // }
      // form.templateId = templateId
      // 打包价格
      if (!packageDTO.price && baseInfo.type == 5) {
        return { errMsg: '请填写打包价格' }
      }
      form.packageDTO.price = packageDTO.price
      // 打包资源
      packageDTO.resource.forEach(item => {
        if (!item.skuId && baseInfo.type == 5) {
          errMsg = '请选择规格！'
        }
        if (!item.number && item.number != 0 && baseInfo.type == 5) {
          errMsg = '请填写数量！'
        }
      })
      form.packageDTO.resource = packageDTO.resource
      form.packageDTO.resource = form.packageDTO.resource.map(item => {
        let {
          skuId,
          number
        } = item
        return { skuId: skuId, number: number }
      })
      form.packageDTO.resource = JSON.stringify(form.packageDTO.resource)
      if (!packageDTO.stock && baseInfo.type == 5) {
        return { errMsg: '请填写打包库存' }
      }
      form.packageDTO.stock = packageDTO.stock
      // NFT商品价格
      // console.log('nftdto', nftdto)
      if (!nftdto.price && baseInfo.type == 6) {
        return { errMsg: '请填写商品价格' }
      }
      // NFT类型
      if (!nftdto.type && baseInfo.type == 6 && nftdto.tzType == 1) {
        return { errMsg: '请选择NFT类型' }
      }
      // NFT类型
      if (!nftdto.number && baseInfo.type == 6 && nftdto.type == 2) {
        return { errMsg: '请填写发行数量' }
      }
      form.nftdto = nftdto
      // 退货类型
      if (!returnType && returnType != 0) {
        return { errMsg: '请选择退货类型' }
      }
      form.returnType = returnType
      // 自定义退货(退货理由)
      if (returnReason == '' && returnType == 2) {
        return { errMsg: '请描述退货理由' }
      }
      form.returnReason = returnReason
      // 商品备注
      if (!note) {
        return { errMsg: '请填写商品备注' }
      }
      form.note = note
      if (!depositType && baseInfo.type == 2) {
        return { errMsg: '请选择预售定金类型' }
      }
      form.preSaleDTO.depositType = depositType
      // 首付比例
      if (baseInfo.type == 2) {
        if (depositType == 1) {
          deposit = this.fixedProportion
        } else {
          deposit = this.fixedAmount
        }
      }
      if (!deposit && baseInfo.type == 2) {
        return { errMsg: '请填写首付比例' }
      }
      form.preSaleDTO.deposit = deposit
      // 预计提货开始时间
      if (!drawStartTime && baseInfo.type == 2) {
        return { errMsg: '请填写预计提货开始时间' }
      }
      form.preSaleDTO.drawStartTime = drawStartTime
      // 预计提货结束时间
      if (!drawEndTime && baseInfo.type == 2) {
        return { errMsg: '请填写预计提货结束时间' }
      }
      form.preSaleDTO.drawEndTime = drawEndTime
      // 预售开始时间
      if (!saleStartTime && baseInfo.type == 2) {
        return { errMsg: '请填写预售开始时间' }
      }
      form.preSaleDTO.saleStartTime = saleStartTime
      // 预售结束时间
      if (!saleEndTime && baseInfo.type == 2) {
        return { errMsg: '请填写预售结束时间' }
      }
      form.preSaleDTO.saleEndTime = saleEndTime
      // 买家保证金
      if (!buyerDeposit && baseInfo.type == 3) {
        return { errMsg: '请填写拍卖保证金' }
      }
      if ((buyerDeposit < 0 || !/^\d+$/.test(buyerDeposit)) && baseInfo.type == 3) {
        return { errMsg: '拍卖保证金格式输入有误！' }
      }
      form.auctionDTO.buyerDeposit = buyerDeposit
      // 出价最小增幅
      if (!priceIncrease && baseInfo.type == 3) {
        return { errMsg: '请填写出价最小增幅' }
      }
      if ((priceIncrease < 0 || !/^\d+$/.test(priceIncrease)) && baseInfo.type == 3) {
        return { errMsg: '出价最小增幅格式输入有误！' }
      }
      form.auctionDTO.priceIncrease = priceIncrease
      if (!endTime && baseInfo.type == 3) {
        return { errMsg: '请填写拍卖结束时间' }
      }
      form.auctionDTO.endTime = endTime
      // 积分库存
      // if (!stock && baseInfo.type == 4) {
      //   return { errMsg: '请填写库存' }
      // }
      // form.pointsExchangeDTO.stock = stock
      // // 积分数量
      // if (!pnum && baseInfo.type == 4) {
      //   return { errMsg: '请填写积分数量' }
      // }
      form.pointsExchangeDTO.pnum = pnum
      // if (!traceabilityNumber) {
      //   return { errMsg: '请输入溯源系统的商品溯源编号' }
      // }
      form.traceabilityNumber = traceabilityNumber
      form.delayDelivery = delayDelivery == true ? '1' : '0'
      return { errMsg, form }
    },
    handleSubmit () {
      let { errMsg, form } = this.checkForm()
      // console.log('form', form)
      if (errMsg) {
        return this.$Notice.warning({ title: errMsg })
      }
      if (form.preSaleDTO.drawStartTime > form.preSaleDTO.drawEndTime) {
        return this.$Notice.warning('提货开始时间不能大于结束时间')
      }
      if (form.preSaleDTO.saleStartTime > form.preSaleDTO.saleEndTime) {
        return this.$Notice.warning('预售开始时间不能大于结束时间')
      }

      if (!errMsg) {
        form.categoryId = JSON.stringify(form.categoryId)
        form.prop = JSON.stringify(form.prop)
        form.type = JSON.parse(form.type)
      }
      if (!errMsg) {
        form.returnType = JSON.parse(form.returnType)
        form.preSaleDTO.drawStartTime = new Date(form.preSaleDTO.drawStartTime).getTime()
        form.preSaleDTO.drawEndTime = new Date(form.preSaleDTO.drawEndTime).getTime() + 86399000
        form.preSaleDTO.saleStartTime = new Date(form.preSaleDTO.saleStartTime).getTime()
        form.preSaleDTO.saleEndTime = new Date(form.preSaleDTO.saleEndTime).getTime() + 86399000
        form.auctionDTO.endTime = new Date(form.auctionDTO.endTime).getTime() + 86399000
      }
      if (!errMsg) {
        if (form.type == 6) {
          if (form.nftdto.tzType == 1 && form.nftdto.type == 1) {
            form.nftdto.number = 1
          }
          if (form.nftdto.tzType == 1) {
            form.commodityPass = 1
          } else if (form.nftdto.tzType == 2) {
            form.commodityPass = 2
          }
          // form.commodityPass = 0
          form.skuList.forEach(item => {
            item.originalPrice = form.nftdto.price
            item.coinName = form.nftdto.tokenId
            item.republish = false
            item.propertyList = [{ propKey: '规格', propVal: form.name }]
            item.stock = form.nftdto.number
            item.image = form.thumb
            item.nftSalesType = 0
          })
        }
      }
      // form.detail
      var regex1 = new RegExp("(i?)(\<p)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)", 'gmi')
      form.detail = form.detail.replace(regex1, '$2 style="padding:0 10px"$3')
      // console.log('form', form)
      let apiName = this.isAdd ? 'addGood' : this.isAgain ? 'republishGood' : 'updateGood'
      let title = this.isAdd ? '添加成功！' : this.isAgain ? '重新发布成功！' : '编辑成功！'
      this.submitLoading = true
      this.api({
        apiName,
        postdata: form,
        success: (res) => {
          // 关闭当前标签页
          let route = this.$route
          let toRouteName = 'product_list'
          this.closeTag({ route, toRouteName })
          this.$Notice.success({ title })
        },
        complete: () => {
          this.submitLoading = false
        }
      })
    }

  },
  mounted () {
    this.getNftList()
    this.requestOptionData()
    this.initData()
    this.getDelayDelivery()
    this.getTemplateorshopquery()
    // console.log('base', this.form.baseInfo)
  }
}
</script>

<style lang="less" scoped>
.add-good-con {
  height: 100%;
  .loading-card {
    height: 100%;
  }
  .head {
    color: #17233d;
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    i {
      margin-right: 10px;
    }
  }
  .series-info {
    padding: 5px 36px;
    // border: 1px solid #dcdee2;
    // border-radius: 5px;
    margin-bottom: 10px;
    .label {
      // color: #17233d;
      font-size: 12px;
      // font-weight: bold;
    }
    .ivu-radio{
      width: 200px;
    }
    .ivu-select {
      width: 200px;
    }
  }
  .series-time{
    padding: 5px 36px;
    margin-bottom: 10px;
    display: flex;
    flex: 1;
    .label {
      padding: 5px;
      font-size: 12px;
    }
    .time{
      display: flex;
      justify-content: space-around;
    }
  }
  .submit-con {
    text-align: center;
  }
  .package-resources{
    padding: 5px 36px;
    margin-bottom: 10px;
    align-items: center;
    display: flex;
    .label {
      // color: #17233d;
      text-align: right;
      font-size: 12px;
      // font-weight: bold;
    }
    .property-con{
      border: 1px solid #dcdee2;
      border-radius: 5px;
      padding: 20px;
      align-items: center;
      .property-item{

        // display: flex;
        // justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding-right: 30px;
        .del-con {
          // float: left;
          margin-left: 5px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
