<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"
        :isDraft="isDraft"
        :clearForm="clearForm"
      />
      <sale-info
        :data="form.saleInfo"
        :isDetail="isDetail"
        :isEdit="isEdit"
        :isAgain="isAgain"
        :isDraft="isDraft"
        :isSelf="isSelf"
        :shopStatus="status"
        v-if="form.baseInfo.type != 6 && form.baseInfo.type != 5"
      />
      <decipt-info
        :data="form.deciptInfo"
        :isDetail="isDetail"
        :isEdit="isEdit"
         :isAgain="isAgain"
        :isDraft="isDraft"
        :shopStatus="status"
      />
      <info-con title="售后信息：" class="base-info-con">
        <template v-if="this.form.saleInfo.salesType !== 5">
          <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 || isEdit|| isAgain"
            />
          </div>
          <div class="series-info" v-if="form.baseInfo.type != 4">
            <label class="label">退换货类型：</label>
            <RadioGroup v-model="backType">
              <Radio label="1" :disabled="isDetail || isEdit|| isAgain" class="ivu-radio"
                >不支持</Radio
              >
              <Radio label="2" :disabled="isDetail || isEdit|| isAgain" class="ivu-radio"
                >七天无理由退货</Radio
              >
              <Radio label="3" :disabled="isDetail || isEdit|| isAgain" class="ivu-radio">
                自定义
                <Input
                  v-model="customDays"
                  type="number"
                  :max="15"
                  :disabled="isDetail || isEdit|| isAgain"
                  style="width: 80px"
                />
                无理由退款
              </Radio>
            </RadioGroup>
          </div>
        </template>

        <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>
      <div class="submit-bottom">
        <div class="submit-con">
          <Button
            type="primary"
            @click="handleDraft"
            v-if="!isDetail"
            :disabled="isEdit"
            :loading="draftLoading"
            >存为草稿</Button
          >
        </div>
        <div class="submit-con">
          <Button
            type="primary"
            @click="handleSubmit"
            v-if="!isDetail"
            :loading="submitLoading"
            >提交商品信息</Button
          >
        </div>
      </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";
    },
    isDraft() {
      return this.routeName === "draft_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: '' }], // 商品属性
          prop: [],
          categoryId: [], // 类目选择
          type: "2", // 商品类型
          useNft: "0",
        },
        saleInfo: {
          sku: [],
          imgObj: {},
          commodityPass: 0,
          saleStartTime: "",
          saleEndTime: "",
          drawStartTime: "",
          drawEndTime: "",
          fixedProportion: "",
          fixedAmount: "",
          depositType: "",
          resource: [
            {
              integralMerchantNameList: [],
              goodsId: "",
              skuId: "",
              number: "",
              specificationsList: [],
              actualNumber: "",
            },
          ], // 打包资源
          stock: "",
          salesType: 1,
          name: "",
          outToken: "",
          shopPrice: "",
          preSalePrice: "",
          hash: "",
          difficulty: 3,
          isHide: false,
          // stock: 0,
          blindBoxRule: "",
          purchaseLimit:0
          // statu:this.status
        },
        deciptInfo: {
          video: "",
          videoList: [],
          videoThumb: "",
          thumb: "",
          thumbList: [],
          detailPictures: [],
          detailDescribe: "",
          defaultDetailPicture: [],
          defaultVideoList: [],
          defaultThumbList: [],
          defaultthreeDUrl:[],
          threeDUrl:[]
          // statu:this.status
        },
        returnType: "", // 退货类型
        returnReason: "", // 退货理由
        note: "", // 商品备注
        stock: "", // 积分库存
        pnum: "", // 积分数量
        traceabilityNumber: "", // 溯源编号
        delayDelivery: false, // 延迟提货
        packageDTO: {
          resource: [
            {
              integralMerchantNameList: [],
              goodsId: "",
              skuId: "",
              number: "",
              specificationsList: [],
              actualNumber: "",
            },
          ], // 打包资源
          price: "", // 打包价格
          stock: "", // 库存
        },
      },
      skuNumber: "",
      loading: true,
      expressList: [],
      profitList: [],
      integralMerchantNameList: [],
      // specificationsList: [],
      idx: "",
      // fixedProportion: '',
      // fixedAmount: '',
      depositList: [3, 4, 5, 6, 9, 10, 11, 13],
      nftList: [],
      submitLoading: false,
      draftLoading: false,
      backType: "1",
      customDays: "",
      buyEndOption: {
        // 指定终止日期
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
    };
  },
  methods: {
    ...mapMutations(["closeTag"]),
    clearForm() {
      // Object.assign(this.$data, this.$options.data())
      this.form.baseInfo.description = "";
      this.form.baseInfo.prop = [];
      this.form.baseInfo.categoryId = [];
      this.form.saleInfo.sku = [];
      this.form.saleInfo.imgObj = {};
      this.form.saleInfo.commodityPass = 0;
      this.form.saleInfo.saleStartTime = "";
      this.form.saleInfo.saleEndTime = "";
      this.form.saleInfo.drawStartTime = "";
      this.form.saleInfo.drawEndTime = "";
      this.form.saleInfo.fixedProportion = "";
      this.form.saleInfo.fixedAmount = "";
      this.form.saleInfo.depositType = "";
      this.form.saleInfo.resource = [
        {
          integralMerchantNameList: [],
          goodsId: "",
          skuId: "",
          number: "",
          specificationsList: [],
          actualNumber: "",
        },
      ];
      this.form.saleInfo.stock = "";
      this.form.saleInfo.salesType = 1;
      this.form.saleInfo.name = "";
      this.form.saleInfo.outToken = "";
      this.form.saleInfo.shopPrice = "";
      this.form.saleInfo.preSalePrice = "";
      this.form.saleInfo.hash = "";
      this.form.deciptInfo.video = "";
      this.form.deciptInfo.videoList = [];
      this.form.deciptInfo.videoThumb = "";
      this.form.deciptInfo.thumb = "";
      this.form.deciptInfo.thumbList = [];
      this.form.deciptInfo.detailPictures = [];
      this.form.deciptInfo.detailDescribe = "";
      this.form.deciptInfo.defaultDetailPicture = [];
      this.form.deciptInfo.defaultVideoList = [];
      this.form.deciptInfo.defaultThumbList = [];
      this.form.deciptInfo.threeDUrl = []
      this.form.deciptInfo.defaultthreeDUrl = []
      this.backType = "1";
      this.customDays = "";
      this.form.note = "";
      this.form.stock = "";
      this.form.pnum = "";
      this.form.traceabilityNumber = "";
      this.form.delayDelivery = false;
      this.form.packageDTO.resource = [
        {
          integralMerchantNameList: [],
          goodsId: "",
          skuId: "",
          number: "",
          specificationsList: [],
          actualNumber: "",
        },
      ];
      this.form.packageDTO.price = "";
      this.form.packageDTO.stock = "";
    },
    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(id) {
      this.loading = true;
      this.api({
        apiName: "getGoodDetail",
        postdata: { id },
        success: (res) => {
          let {
            brandId,
            brandName,
            // templateId,
            name,
            description,
            prop,
            skus,
            imgList,
            video,
            blindBoxPrice,
            difficulty,
            blindBoxRule,
            videoThumb,
            thumb,
            detail,
            type,
            note,
            returnType,
            traceabilityNumber,
            delayDelivery,
            returnReason,
            categoryName,
            categoryIds,
            preSaleVO,
            auctionVO,
            commodityPass,
            goodsPackageVO,
            goodsNftVO,
            useNft,
            salesType,
            purchaseLimit,
            threeDUrl
          } = res.data;

          this.form.brandId = brandId;
          this.form.blindBoxPrice = blindBoxPrice;
          this.form.difficulty = difficulty;
          this.form.brandName = brandName;
          // this.form.templateId = templateId
          this.form.note = note;
          // this.form.returnType = returnType.toString()
          if (returnType == 0) {
            this.backType = "1";
          } else if (returnType == 7) {
            this.backType = "2";
          } else {
            this.backType = "3";
            this.customDays = returnType;
            // form.returnType = this.customDays
          }
          this.form.returnReason = returnReason;
          this.form.traceabilityNumber = traceabilityNumber;
          if (delayDelivery == 0) {
            this.form.delayDelivery = false;
          } else {
            this.form.delayDelivery = true;
          }
          if (auctionVO) {
            this.form.saleInfo.buyerDeposit = auctionVO.buyerDeposit;
            this.form.saleInfo.startPrice = auctionVO.startPrice;
            this.form.saleInfo.priceIncrease = auctionVO.priceIncrease;
            this.form.saleInfo.delayPayTime = auctionVO.delayPayTime;
            this.form.saleInfo.endTime = auctionVO.endTime
              ? formatTime(auctionVO.endTime)
              : "";
            // this.form.saleInfo.name = auctionVO.name
          }
          this.form.baseInfo = {
            name,
            description,
            prop: JSON.parse(prop),
            type: type.toString(),
            categoryId:
              this.isDraft || this.isEdit
                ? JSON.parse(categoryIds)
                : categoryName,
            useNft: useNft.toString(),
          };
          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;
            });
            let obj = { ...item, ...prop, upload };
            if (item.outToken) {
              let str = JSON.parse(item.outToken);
              str.disabled = true;
              obj.outToken = JSON.stringify(str);
            }
            newSku.push(obj);
            this.form.saleInfo.name = item.name;
            this.form.saleInfo.id = item.commodityPassId;
            this.form.saleInfo.outStock = item.stock;
          });
          this.form.saleInfo.sku = newSku;
          this.form.saleInfo.purchaseLimit=purchaseLimit
          this.form.saleInfo.commodityPass = commodityPass;
          this.form.saleInfo.salesType = salesType;
          this.form.saleInfo = { ...goodsNftVO, ...this.form.saleInfo };
          this.form.saleInfo.blindBoxRule = blindBoxRule;
          if (this.form.baseInfo.type == 4) {
            if (
              this.form.saleInfo.salesType == 1 ||
              this.form.saleInfo.salesType == 5
            ) {
              this.form.saleInfo.shopPrice = skus[0].originalPrice;
            } else if (this.form.saleInfo.salesType == 2) {
              this.form.saleInfo.preSalePrice = skus[0].originalPrice;
            }
          }
          if (
            this.form.baseInfo.type == 4 ||
            this.form.saleInfo.salesType == 3
          ) {
            this.form.saleInfo.hash = this.form.saleInfo.sku[0].hash;
          }
          this.form.deciptInfo = {
            video,
            videoList: [video],
            videoThumb,
            thumb,
            thumbList: thumb ? [thumb] : [],
            detailPictures: JSON.parse(imgList),
            detailDescribe: detail,
            threeDUrl: threeDUrl ? [threeDUrl] : [],
            defaultthreeDUrl: threeDUrl ? [threeDUrl] : [],
            defaultDetailPicture: JSON.parse(imgList),
            defaultVideoList: [video],
            defaultThumbList: thumb ? [thumb] : [],
          };
          if (!video) {
            this.form.deciptInfo.video = "";
            this.form.deciptInfo.defaultVideoList = [];
          }
          if (salesType == 2) {
            this.form.saleInfo.depositType = preSaleVO.depositType.toString();
            if (this.form.saleInfo.depositType == 1) {
              this.form.saleInfo.fixedProportion = preSaleVO.deposit;
            } else if (this.form.saleInfo.depositType == 2) {
              this.form.saleInfo.fixedAmount = preSaleVO.deposit;
            }
            // this.form.deposit = preSaleVO.deposit
            this.form.saleInfo.drawEndTime = preSaleVO.drawEndTime
              ? formatTime(preSaleVO.drawEndTime)
              : "";
            this.form.saleInfo.drawStartTime = preSaleVO.drawStartTime
              ? formatTime(preSaleVO.drawStartTime)
              : "";
            this.form.saleInfo.saleEndTime = preSaleVO.saleEndTime
              ? formatTime(preSaleVO.saleEndTime)
              : "";
            this.form.saleInfo.saleStartTime = preSaleVO.saleStartTime
              ? formatTime(preSaleVO.saleStartTime)
              : "";
          }
          if (salesType == 4) {
           if(commodityPass==4){
              this.form.saleInfo.commodityPass=1
            }else{
              this.form.saleInfo.commodityPass=2
            }
            this.form.saleInfo.price = blindBoxPrice || 0;
            this.form.saleInfo.difficulty = difficulty || 1;
            let sku = [];
            for (let item of skus) {
              let obj = {
                ...item,
                isHide: !!item.isHide,
                name: item.propertyList[0].propVal,
                upload: {
                  imageList: [item.image],
                  defaultImgList: [item.image],
                },
              };
              sku.push(obj);
            }
            this.form.saleInfo.sku = sku;
          }
          if (goodsPackageVO) {
            goodsPackageVO.resource.forEach((item, index) => {
              item.name = item.goodsName;
              let stock = item.sku.number + item.number * goodsPackageVO.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()
          //   // this.form.nftdto = goodsNftVO
          // }
        },
        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" ||
        routeName == "draft_good"
      ) {
        this.requestGoodDetail(goodsId);
      } else {
        this.loading = false;
      }
    },
    checkForm() {
      let errMsg = "";
      let form = {
        auctionDTO: {},
        pointsExchangeDTO: {},
        preSaleDTO: {},
        skuList: [
          {
            coinName: "",
            originalPrice: "",
            propertyList: [
              {
                propKey: "",
                propVal: "",
              },
            ],
            republish: "",
            skuId: "",
            stock: "",
            skuName: "",
          },
        ],
        packageDTO: {},
        // nftdto: {}
      };
      let {
        goodsId,
        // templateId,
        baseInfo,
        saleInfo,
        deciptInfo,
        // returnType,
        // returnReason,
        note,
        deposit,
        pnum,
        traceabilityNumber,
        delayDelivery,
        // nftdto,
        // packagePrice
        packageDTO,
      } = this.form;
      if(baseInfo.type==4){
        form.purchaseLimit=1
      }else{
        form.purchaseLimit=saleInfo.purchaseLimit
      }
    
      if (this.form.goodsId) {
        form.goodsId = this.form.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: "请选择 基本信息 - 所属类目！" };
      }
      // if (!baseInfo.useNft) {
      //   return { errMsg: '请填写 基本信息 - 是否应用NFT！' }
      // }
      form = { ...form, ...baseInfo };
      // 销售信息

      if (!saleInfo.salesType) {
        return { errMsg: "请选择商品类型" };
      }
      form.salesType = saleInfo.salesType;
      if (!saleInfo.depositType && saleInfo.salesType == 2) {
        return { errMsg: "请选择预售定金类型" };
      }
      form.preSaleDTO.depositType = saleInfo.depositType;
      // 首付比例
      if (saleInfo.salesType == 2) {
        if (saleInfo.depositType == 1) {
          deposit = saleInfo.fixedProportion;
        } else {
          deposit = saleInfo.fixedAmount;
        }
      }
      if (!deposit && saleInfo.salesType == 2) {
        return { errMsg: "请填写首付比例" };
      }
      form.preSaleDTO.deposit = deposit;
      // 预计提货开始时间
      if (!saleInfo.drawStartTime && saleInfo.salesType == 2) {
        return { errMsg: "请填写预计提货开始时间" };
      }
      form.preSaleDTO.drawStartTime = saleInfo.drawStartTime;
      // 预计提货结束时间
      if (!saleInfo.drawEndTime && saleInfo.salesType == 2) {
        return { errMsg: "请填写预计提货结束时间" };
      }
      form.preSaleDTO.drawEndTime = saleInfo.drawEndTime;
      // 预售开始时间
      if (!saleInfo.saleStartTime && saleInfo.salesType == 2) {
        return { errMsg: "请填写预售开始时间" };
      }
      form.preSaleDTO.saleStartTime = saleInfo.saleStartTime;
      // 预售结束时间
      if (!saleInfo.saleEndTime && saleInfo.salesType == 2) {
        return { errMsg: "请填写预售结束时间" };
      }
      form.preSaleDTO.saleEndTime = saleInfo.saleEndTime;
      form.commodityPass = saleInfo.commodityPass;
      if (
        !saleInfo.shopPrice &&
        (saleInfo.salesType == 1 || saleInfo.salesType == 5) &&
        baseInfo.type == 4
      ) {
        return { errMsg: "请填写商品价格" };
      }
      if (
        !saleInfo.preSalePrice &&
        saleInfo.salesType == 2 &&
        baseInfo.type == 4
      ) {
        return { errMsg: "请填写预售价格" };
      }
      if (
        saleInfo.salesType == 2 &&
        baseInfo.type == 4 &&
        saleInfo.depositType == 2 &&
        Number(saleInfo.fixedAmount) > Number(saleInfo.preSalePrice)
      ) {
        return { errMsg: "首付固定金额不能大于商品预售价格" };
      }

      if (saleInfo.salesType != 3 && baseInfo.type != 4 &&saleInfo.salesType !== 4) {
        // console.log('1111')
        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 (
            saleInfo.salesType == 2 &&
            saleInfo.depositType == 2 &&
            Number(saleInfo.fixedAmount) > Number(item.originalPrice)
          ) {
            errMsg = "首付固定金额不能大于商品预售价格";
          }
          // if (!item.stock) {
          //   errMsg = "请填写 规格信息 - 库存！";
          // }
          if (!item.hash) {
            errMsg = "请填写 规格信息 - 溯源哈希！";
          }
          // if (this.isAdd && saleInfo.commodityPass == 1 && !item.coinName) {
          //   errMsg = '请填写 规格信息 - Token名称！'
          // }
          if (!item.weight && baseInfo.type == 1) {
            errMsg = "请填写 规格信息 - 重量！";
          }
          if ((item.weight && item.weight < 0) || item.weight > 9999) {
            errMsg = "规格信息 - 重量 格式不正确！";
          }
          item.weight = baseInfo.type == 1 ? parseFloat(item.weight) : 0;
          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;
      }
      if (saleInfo.salesType === 4) {
        form.commodityPass = this.form.saleInfo.commodityPass;
        if(this.form.saleInfo.commodityPass==1){
          form.commodityPass=4
        }else{
           form.commodityPass=5
        }
        form.blindBoxPrice = this.form.saleInfo.price;
        form.blindBoxRule = this.form.saleInfo.blindBoxRule;
        form.difficulty=this.form.saleInfo.difficulty || 3
        let skuList = [];
        for (let item of this.form.saleInfo.sku) {
          let obj = {
            ...item,
            originalPrice:form.blindBoxPrice,
            isHide: item.isHide ? 1 : 0,
            propertyList: [
              {
                propKey: "规格名称",
                propVal: item.name || "",
              },
            ],
          };
          if (
            item.upload &&
            item.upload.imageList &&
            item.upload.imageList.length !== 0
          ) {
            obj.image = item.upload.imageList[0];
          }
          skuList.push(obj);
        }
        form.skuList = skuList;
        if (!this.form.saleInfo.blindBoxRule) {
          errMsg = "请完善规格信息 - 盲盒规则！";
        }
        if (this.form.saleInfo.blindBoxRule.length == 0) {
          errMsg = "请完善规格信息 - 盲盒规则！";
        }
        // if (this.form.saleInfo.blindBoxRule.length > 18000) {
        //   errMsg = "规格信息 - 盲盒规则 内容长度过长！";
        // }
        // if (this.form.saleInfo.blindBoxRule.length > 18000) {
        //   errMsg = "规格信息 - 盲盒规则 内容长度过长！";
        // }

        if (!this.form.saleInfo.sku || this.form.saleInfo.sku.length === 0) {
          errMsg = "请完善规格信息！";
        }
        for (let item of this.form.saleInfo.sku) {
          if (!item.name) {
            errMsg = "请填写 规格信息 - 规格名称！";
            break;
          }
          if (!typeof item.weight === "number") {
            errMsg = "请填写 规格信息 - 重量！";
            break;
          }
          if (item.weight < 0 || item.weight > 9999) {
            errMsg = "规格信息 - 重量 格式不正确！";
            break;
          }
          // if (!item.stock) {
          //   errMsg = "请填写 规格信息 - 库存！";
          //   break;
          // }
          if (
            item.stock < 0 ||
            !/^\d+$/.test(item.stock) ||
            item.stock > 20000
          ) {
            errMsg = "规格信息 - 库存 格式不正确！";
            break;
          }
        }
      }
      //    买家起拍价
      if (!saleInfo.startPrice && saleInfo.salesType == 3) {
        return { errMsg: "请填写起拍价" };
      }
      // if ((saleInfo.startPrice < 0 || !/^\d+$/.test(saleInfo.startPrice)) && saleInfo.salesType == 3) {
      //   return { errMsg: '起拍价格式输入有误！' }
      // }
      if (saleInfo.startPrice < 0 && saleInfo.salesType == 3) {
        return { errMsg: "拍卖起拍价不能小于0！" };
      }
      form.auctionDTO.startPrice = saleInfo.startPrice;
      // console.log('333', saleInfo.buyerDeposit)
      //    买家保证金
      if (!saleInfo.buyerDeposit && saleInfo.salesType == 3) {
        return { errMsg: "请填写拍卖保证金" };
      }
      // if ((saleInfo.buyerDeposit < 0 || !/^\d+$/.test(saleInfo.buyerDeposit)) && saleInfo.salesType == 3) {
      //   return { errMsg: '拍卖保证金格式输入有误！' }
      // }
      if (saleInfo.buyerDeposit < 0 && saleInfo.salesType == 3) {
        return { errMsg: "拍卖保证金不能小于0！" };
      }
      if (
        saleInfo.buyerDeposit > saleInfo.startPrice &&
        saleInfo.salesType == 3
      ) {
        return { errMsg: "请填写拍卖保证金不能大于起拍价" };
      }
      form.auctionDTO.buyerDeposit = saleInfo.buyerDeposit;
      // 出价最小增幅
      if (!saleInfo.priceIncrease && saleInfo.salesType == 3) {
        return { errMsg: "请填写出价最小增幅" };
      }
      // if ((saleInfo.priceIncrease < 0 || !/^\d+$/.test(saleInfo.priceIncrease)) && saleInfo.salesType == 3) {
      //   return { errMsg: '出价最小增幅格式输入有误！' }
      // }
      if (saleInfo.priceIncrease < 0 && saleInfo.salesType == 3) {
        return { errMsg: "最小增幅不能小于0！" };
      }
      form.auctionDTO.priceIncrease = saleInfo.priceIncrease;
      if (!saleInfo.endTime && saleInfo.salesType == 3) {
        return { errMsg: "请填写拍卖结束时间" };
      }
      form.auctionDTO.endTime = saleInfo.endTime;
      if (!saleInfo.delayPayTime && saleInfo.salesType == 3) {
        return { errMsg: "请填写延后天数" };
      }
      // console.log('1111', saleInfo.delayPayTime)
      form.auctionDTO.delayPayTime = saleInfo.delayPayTime;

      if (!saleInfo.name && (saleInfo.salesType == 3 || baseInfo.type == 4)) {
        return { errMsg: "请填写规格名称" };
      }
      if (!saleInfo.hash && (saleInfo.salesType == 3 || baseInfo.type == 4)) {
        return { errMsg: "请填写溯源哈希" };
      }
      // form.auctionDTO.endTime = saleInfo.endTime
      if (!saleInfo.price && baseInfo.type == 3) {
        return { errMsg: "请填写打包价格" };
      }
      form.packageDTO.price = saleInfo.price;
      // 打包资源
      saleInfo.resource.forEach((item) => {
        if (!item.skuId && baseInfo.type == 5) {
          errMsg = "请选择规格！";
        }
        if (!item.number && item.number != 0 && baseInfo.type == 3) {
          errMsg = "请填写数量！";
        }
      });
      form.packageDTO.resource = saleInfo.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 (!saleInfo.stock && baseInfo.type == 3) {
        return { errMsg: "请填写打包库存" };
      }
      form.packageDTO.stock = saleInfo.stock;
      // 图文信息
      if (!deciptInfo) {
        return { errMsg: "请完善图文描述！" };
      }
      if (
        (!deciptInfo.detailPictures ||
          deciptInfo.detailPictures.length === 0) &&
        baseInfo.type != 4
      ) {
        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 =
        baseInfo.type == 4
          ? JSON.stringify([deciptInfo.thumbList[0]])
          : 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);
      }
      if(deciptInfo.threeDUrl&&deciptInfo.threeDUrl.length>0){
        form.threeDUrl=deciptInfo.threeDUrl[0]
      }else{
        form.threeDUrl=''
      }
      
      // console.log('form',form)
      // 快递模板
      // if (!templateId) {
      //   return { errMsg: '请选择快递模板！' }
      // }
      // form.templateId = templateId
      // 退货类型
      if (!this.backType) {
        return { errMsg: "请选择退货类型" };
      }
      if (this.customDays == "" && this.backType == 3) {
        return { errMsg: "请自定义多少天可以退货" };
      }

      if (this.backType == 1) {
        form.returnType = 0;
      } else if (this.backType == 2) {
        form.returnType = 7;
      } else if (this.backType == 3) {
        if (parseInt(this.customDays) > 15) {
          return { errMsg: "请自定义最多15天！" };
        }
        form.returnType = this.customDays;
      }
      if (saleInfo.salesType === 5) {
        form.returnType = 0;
      }
      // 商品备注
      // if (!note) {
      //   return { errMsg: '请填写商品备注' }
      // }
      form.note = note;
      // 积分库存
      // if (!stock && baseInfo.type == 4) {
      //   return { errMsg: '请填写库存' }
      // }
      // form.pointsExchangeDTO.stock = stock
      // // 积分数量
      // if (!pnum && baseInfo.type == 4) {
      //   return { errMsg: '请填写积分数量' }
      // }
      form.pointsExchangeDTO.pnum = pnum;
      if (traceabilityNumber.length > 100) {
        return { errMsg: "溯源系统的商品溯源编号不能大于100位" };
      }
      form.traceabilityNumber = traceabilityNumber;
      form.delayDelivery = delayDelivery == true ? "1" : "0";
      return { errMsg, form };
    },
    handleSubmit() {
      let { errMsg, form } = this.checkForm();
      // return
      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);
        // console.log('145', form.prop)
        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.salesType == 3) {
          form.skuList.forEach((item) => {
            item.stock =
              form.commodityPass == 2 ? this.form.saleInfo.outStock : 1;
            item.skuName = this.form.saleInfo.name;
            item.propertyList = [{ propKey: "规格", propVal: item.skuName }];
            item.commodityPassId = this.form.saleInfo.id;
            item.hash = this.form.saleInfo.hash;
          });
        }
        if (form.type == 4) {
          form.skuList.forEach((item) => {
            item.stock = 1;
            item.skuName = this.form.saleInfo.name;
            item.originalPrice =
              form.salesType == 1
                ? this.form.saleInfo.shopPrice
                : this.form.saleInfo.preSalePrice;
            item.propertyList = [{ propKey: "规格", propVal: item.skuName }];
            item.commodityPassId = this.form.saleInfo.id;
            item.hash = this.form.saleInfo.hash;
          });
        }
      }
      // form.detail
      var regex1 = new RegExp(
        "(i?)(<p)(?!(.*?style=['\"](.*)['\"])[^>]+>)",
        "gmi"
      );
      form.detail = form.detail
        ? form.detail.replace(regex1, '$2 style="padding:0 10px"$3')
        : "";
      form.blindBoxRule = form.blindBoxRule
        ? form.blindBoxRule.replace(regex1, '$2 style="padding:0 10px"$3')
        : "";
      let apiName = this.isAdd || this.isDraft ? "addGood" : "updateGood";
      let title = this.isAdd ? "添加成功！" : "编辑成功！";
      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;
        },
      });
    },
    handleDraft() {
      let form = {
        auctionDTO: {},
        pointsExchangeDTO: {},
        preSaleDTO: {},
        skuList: [
          {
            coinName: "",
            originalPrice: "",
            propertyList: [
              {
                propKey: "",
                propVal: "",
              },
            ],
            republish: "",
            skuId: "",
            stock: "",
            skuName: "",
          },
        ],
        packageDTO: {},
      };
      let {
        goodsId,
        baseInfo,
        saleInfo,
        deciptInfo,
        note,
        deposit,
        pnum,
        traceabilityNumber,
        delayDelivery,
        packageDTO,
      } = this.form;
      form.goodsId = goodsId;
      if (!baseInfo.name) {
        return this.$Notice.warning({ title: "请填写商品名称！" });
      }
      form = { ...form, ...baseInfo };
      form.salesType = saleInfo.salesType;
      form.preSaleDTO.depositType = saleInfo.depositType;
      if (saleInfo.salesType == 2) {
        if (saleInfo.depositType == 1) {
          deposit = saleInfo.fixedProportion;
        } else {
          deposit = saleInfo.fixedAmount;
        }
      }
      form.preSaleDTO.deposit = deposit;
      form.preSaleDTO.drawStartTime = saleInfo.drawStartTime;
      form.preSaleDTO.drawEndTime = saleInfo.drawEndTime;
      form.preSaleDTO.saleStartTime = saleInfo.saleStartTime;
      form.preSaleDTO.saleEndTime = saleInfo.saleEndTime;
      form.commodityPass = saleInfo.commodityPass;
      if (saleInfo.salesType != 3 && form.type != 4) {
        let skuIndex = 0;
        saleInfo.sku.forEach((item) => {
          item.weight = parseFloat(item.weight);
          item.originalPrice = parseFloat(item.originalPrice);
          if (
            item.upload &&
            item.upload.imageList &&
            item.upload.imageList.length !== 0
          ) {
            saleInfo.sku[skuIndex].image = item.upload.imageList[0];
          }
          skuIndex++;
        });
        form.skuList = saleInfo.sku;
      }
      form.auctionDTO.buyerDeposit = saleInfo.buyerDeposit;
      form.auctionDTO.startPrice = saleInfo.startPrice;
      form.auctionDTO.priceIncrease = saleInfo.priceIncrease;
      form.auctionDTO.delayPayTime = saleInfo.delayPayTime;
      form.auctionDTO.endTime = saleInfo.endTime;
      form.packageDTO.price = saleInfo.price;
      // 打包资源
      form.packageDTO.resource = saleInfo.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);
      form.packageDTO.stock = saleInfo.stock;
      form.thumb = deciptInfo.thumbList[0] ? deciptInfo.thumbList[0] : "";
      form.imgList =
        baseInfo.type == 4
          ? JSON.stringify([deciptInfo.thumbList[0]])
          : 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);
      }
      if (this.backType == 1) {
        form.returnType = 0;
      } else if (this.backType == 2) {
        form.returnType = 7;
      } else if (this.backType == 3) {
        form.returnType = this.customDays;
      }
      if (saleInfo.salesType === 5) {
        form.returnType = 0;
      }
      form.note = note;
      form.pointsExchangeDTO.pnum = pnum;
      if (traceabilityNumber.length > 100) {
        return { errMsg: "溯源系统的商品溯源编号不能大于100位" };
      }
      form.traceabilityNumber = traceabilityNumber;
      form.delayDelivery = delayDelivery == true ? "1" : "0";
      form.categoryId = JSON.stringify(form.categoryId);
      form.prop = JSON.stringify(form.prop);
      form.type = JSON.parse(form.type);

      // form.returnType = 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 (form.salesType == 3) {
        form.skuList.forEach((item) => {
          item.stock =
            form.commodityPass == 2 ? this.form.saleInfo.outStock : 1;
          item.skuName = this.form.saleInfo.name;
          item.commodityPassId = this.form.saleInfo.id;
        });
      }
      if (form.type == 4) {
        form.skuList.forEach((item) => {
          item.stock = 1;
          item.skuName = this.form.saleInfo.name;
          item.originalPrice =
            saleInfo.salesType == 1 || saleInfo.salesType == 5
              ? this.form.saleInfo.shopPrice
              : this.form.saleInfo.preSalePrice;
          item.propertyList = [{ propKey: "规格", propVal: item.skuName }];
          item.commodityPassId = this.form.saleInfo.id;
        });
      }
      this.draftLoading = true;
      this.api({
        apiName: "draftGood",
        postdata: form,
        success: (res) => {
          // 关闭当前标签页
          let route = this.$route;
          let toRouteName = "product_list";
          this.closeTag({ route, toRouteName });
          this.$Notice.success({ title: "保存成功！" });
        },
        complete: () => {
          this.draftLoading = 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-bottom {
    margin: 0 auto;
    width: 50%;
    display: flex;
    justify-content: space-around;
    .submit-con {
      // text-align: center;
    }
  }
  // .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>
