<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"
      />
      <decipt-info :data="form.deciptInfo" :isDetail="isDetail" :status="status"/>
      <info-con title="销售信息：" class="base-info-con">
      <!-- <div class="series-info">
        <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-info">
        <label class="label">商品备注：</label>
          <Input v-model="form.note" :readonly="isDetail" type="textarea" 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 === 'commodity_update_good') {
        return '编辑商品 - 填写商品信息'
      } else if (this.routeName == 'commodity_good_detail') {
        return '商品详情'
        // this.isSelf // : `商品详情（ 品牌商：${this.form.brandName} ）`
      } else if (this.routeName === 'commodity_again_good') {
        return '重新发布商品 - 填写商品信息'
      } else {
        return '发布商品 - 填写商品信息'
      }
    },
    isDetail () {
      return this.routeName === 'commodity_good_detail'
    },
    isAdd () {
      return this.routeName === 'commodity_add_good'
    },
    isEdit () {
      return this.routeName === 'commodity_update_good'
    },
    isAgain () {
      return this.routeName === 'commodity_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', // 商品类型
          coinName: ''
        },
        saleInfo: {
          sku: [],
          imgObj: {},
          commodityPass: 3,
          originalPrice: '',
          weight: '',
          nftSalesType: '',
          stock: ''
          // statu:this.status
        },
        deciptInfo: {
          video: '',
          videoList: [],
          nftFile: '',
          nftEnclosureList: [],
          videoThumb: '',
          thumb: '',
          thumbList: [],
          detailPictures: [],
          detailDescribe: '',
          defaultDetailPicture: [],
          defaultVideoList: [],
          defaultThumbList: [],
          defaultNftEnclosureList: []
          // statu:this.status
        },
        returnType: '', // 退货类型
        returnReason: '', // 退货理由
        note: '', // 商品备注
        traceabilityNumber: '', // 溯源编号
        delayDelivery: false // 延迟提货
      },
      loading: true,
      expressList: [],
      submitLoading: false,
      commodityPassId: '',
      availableNumber: '',
      skuId: ''
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    requestOptionData () {
      // 获取快递模板
      this.api({
        apiName: 'templateList',
        success: (res) => {
          this.expressList = 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,
            auctionVO,
            commodityPass,
            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
          }
          this.form.baseInfo = {
            name,
            description,
            coinName: skus[0].coinName,
            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 = {
            originalPrice: skus[0].originalPrice,
            weight: skus[0].weight,
            nftSalesType: skus[0].nftSalesType,
            stock: skus[0].stock
          }
          this.form.saleInfo.commodityPass = commodityPass
          this.skuId = skus[0].skuId
          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 = []
          }
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      let { goodsId, labelName, commodityPassId, availableNumber } = this.$route.query
      this.form.baseInfo.coinName = labelName
      this.commodityPassId = commodityPassId
      this.availableNumber = availableNumber
      this.form.goodsId = goodsId
      this.routeName = routeName
      if (routeName == 'commodity_update_good' || routeName == 'commodity_good_detail' || routeName == 'commodity_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: '',
          weight: '',
          commodityPassId: ''
        }],
        packageDTO: {},
        nftdto: {}
      }

      let {
        goodsId,
        // templateId,
        baseInfo,
        saleInfo,
        deciptInfo,
        returnType,
        returnReason,
        note,
        traceabilityNumber,
        delayDelivery
      } = 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 (!saleInfo.originalPrice) {
        return { errMsg: '请填写销售价格！' }
      }
      if (!saleInfo.weight) {
        return { errMsg: '请填写商品重量！' }
      }
      if (!saleInfo.nftSalesType) {
        return { errMsg: '请选择NFT销售方式！' }
      }
      if (!saleInfo.stock && saleInfo.nftSalesType == 2) {
        return { errMsg: '请填写拷贝数量！' }
      }
      form.commodityPass = saleInfo.commodityPass
      // 图文信息
      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 = ''
      }
      // 退货类型
      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
      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 (!errMsg) {
        form.categoryId = JSON.stringify(form.categoryId)
        form.prop = JSON.stringify(form.prop)
        form.type = JSON.parse(form.type)
      }
      if (!errMsg) {
        if (form.type == 6) {
          // form.commodityPass = 0
          form.skuList.forEach(item => {
            item.originalPrice = this.form.saleInfo.originalPrice
            item.coinName = this.form.baseInfo.coinName
            item.propertyList = [{ propKey: '规格', propVal: '默认' }]
            item.image = form.thumb
            item.nftSalesType = this.form.saleInfo.nftSalesType
            item.weight = this.form.saleInfo.weight
            item.commodityPassId = this.commodityPassId
            item.skuId = this.skuId
            item.stock = item.nftSalesType == 1 ? this.availableNumber : this.form.saleInfo.stock
          })
        }
      }
      // 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 ? '重新发布成功！' : '编辑成功！'
      console.log('form', form)
      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.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>
