<!--
Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

https://www.mall4j.com/

未经允许，不可做商业用途！

版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-post-prod">
    <!-- <pord-title :prodTitle="'发布商品'" /> -->

    <!-- 商品名称 -->
    <view class="goods-name">
      <view class="L0">
        <text>
          {{ $t('shangPinMingCheng') }}<text class="required">
            *
          </text>
        </text>
        <textarea
          v-model="dataForm.prodName"
          :disabled="showProd"
          type="text"
          :maxlength="60"
          placeholder-style="color:#999"
          :placeholder="$t('changDuBuChaoGuo_60GeZiFu')"
        />
      </view>
      <view class="L1">
        <text>{{ $t('shangPinMaiDian') }}</text>
        <textarea
          v-model="dataForm.brief"
          :disabled="showProd"
          type="text"
          :maxlength="100"
          placeholder-style="color:#999"
          :placeholder="$t('changDuBuChaoGuo_100GeZiFu')"
        />
      </view>
    </view>

    <!-- 上传图片视频 -->
    <view class="goods-img">
      <view class="L0">
        <text>
          {{ $t('shangPinTuPian') }}<text class="required">
            *
          </text>
        </text>
        <view
          id="img"
          class="img"
        >
          <block
            v-for="(imgItem, idx) in dataForm.imageData"
            :key="idx"
          >
            <view class="img-item transparent-border">
              <img-show :src="imgItem" />
              <view
                v-if="!showProd"
                class="img-del"
                @tap="onDeleteImage(idx)"
              >
                ×
              </view>
            </view>
          </block>
          <!-- 添加 -->
          <view
            v-if="dataForm.imageData.length < 9&&!showProd"
            class="img-item"
            @tap="onChooseSuccessImages"
          >
            +
          </view>
        </view>

        <text class="hint">
          {{ $t('jianYiChiCun_800800XiangSuZuiDuoShangChuan_9ZhangShouTuWeiZhuTu') }}
        </text>
      </view>
      <view class="L1 L0">
        <text>{{ $t('shangPinShiPin') }}</text>
        <view class="img">
          <view
            v-if="!dataForm.videoData.length &&!showProd"
            class="img-item"
            @tap="onChooseVideo"
          >
            +
          </view>
          <view
            v-if="dataForm.videoData.length"
            class="img-item transparent-border"
          >
            <image
              class="prod-video"
              src="/static/images/play.png"
              @tap="previewVideo"
            />
            <view
              class="img-del"
              @tap="onDeleteVideo"
            >
              ×
            </view>
            <view
              v-if="previewVideoSrc != ''"
              class="preview-full"
            >
              <video
                :autoplay="true"
                :src="util.checkFileUrl(previewVideoSrc)"
                :show-fullscreen-btn="false"
              >
                <cover-view
                  class="preview-full-close"
                  @tap="previewVideoSrc = ''"
                > ×
                </cover-view>
              </video>
            </view>
          </view>
          <view
            v-if="!dataForm.videoData.length && showProd"
            class="img-item"
          >
            <view class="line" />
          </view>
        </view>
        <text class="hint">
          {{ $t('zhuTuShiPinJianYiShiChang_930MiaoShiPinKuanGaoHeShangPinTuBaoChiYiZhi') }}
        </text>
      </view>
    </view>

    <!-- 商品类目 -->
    <view class="goods-type goods">
      <view class="list">
        <view>
          <text>{{ $t('pingTaiLeiMu') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toSelectType(1)"
        >
          <text :class="[selected.categoryName ? 'selected' : '', showProd ? 'disable' : '']">
            {{ selected.categoryName ? selected.categoryName : $t('qingXuanZe') }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>{{ $t('dianPuLeiMu') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toSelectType(2)"
        >
          <text :class="[selected.shopCategoryName ? 'selected' : '', showProd ? 'disable' : '']">
            {{ selected.shopCategoryName ? selected.shopCategoryName : $t('qingXuanZe') }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>{{ $t('shangPinLeiXing') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="moldOpen"
        >
          <text :class="dataForm.mold === null || dataForm.prodId ? '' : 'selected'">
            {{
              dataForm.mold === null
                ?
                  $t('qingXuanZe')
                :
                  [$t('shiWuShangPin'),$t('xuNiShangPin'),$t('zuHeShangPin'),$t('dianZiKaQuan')][dataForm.mold]
            }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>{{ $t('shangPinPinPai') }}</text>
        </view>
        <view
          class="right"
          @tap="toCommodityBrand"
        >
          <text :class="dataForm.brandName ? 'selected' : ''">
            {{ dataForm.brandName ? dataForm.brandName : $t('keXuanTian') }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>{{ $t('shangPinPaiXu') }}</text>
        </view>
        <view class="right">
          <input
            v-model="dataForm.seq"
            :disabled="showProd"
            type="number"
            :placeholder="$t('keXuanTian')"
            placeholder-style="color:#999"
            @blur="seqChange"
          >
        </view>
      </view>
      <view
        v-if="dataForm.mold === 3"
        class="list"
      >
        <view>
          <text>{{ $t('guanLianKaQuan') }}</text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :checked="dataForm.isBindVoucher"
            @change="changeIsBindVoucher"
          />
        </view>
      </view>
      <view
        v-if="dataForm.mold !== 1 && dataForm.mold !== 2 && dataForm.mold !== 3"
        class="list combom-con"
      >
        <view class="flex-box">
          <text>{{ $t('zuHeXuanPin') }}</text>
          <view class="uni-padding-wrap uni-common-mt aligning">
            <switch
              color="#082BA6"
              :disabled="showProd"
              :checked="dataForm.prodType == 5"
              @change="prodTypeChange"
            />
          </view>
        </view>
        <text class="activity">
          {{ $t('zuHeXuanPinBuNengDanDuGouMai') }}
        </text>
      </view>
      <!-- &&(!dataForm.prodId||!dataForm.preSellTime) -->
      <view
        v-if="dataForm.prodType !== 5 && dataForm.mold !== 1 && dataForm.mold !== 2 && dataForm.mold !== 3"
        class="list"
      >
        <view>
          <text>{{ $t('kaiQiYuShou') }}</text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :disabled="showProd"
            :checked="dataForm.preSellStatus == 1"
            @change="preSellStatusChange"
          />
        </view>
      </view>
      <view
        v-if="dataForm.preSellStatus == 1 && dataForm.prodType !== 5 && dataForm.mold !== 1 && dataForm.mold !== 3"
        class="list"
      >
        <view>
          <text>{{ $t('yuShouFaHuoShiJian') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toPresellTime"
        >
          <text :class="dataForm.preSellTime ? 'selected' : ''">
            {{ dataForm.preSellTime ? preSellTimeShowHandler(dataForm.preSellTime) : $t('qingXuanZe') }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 商品规格 -->
    <view class="goods-type goods">
      <view class="list">
        <view>
          <text>{{ $t('duoGuiGe') }}</text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :disabled="showProd"
            :checked="dataForm.specifications"
            @change="changeSpecifications"
          />
        </view>
      </view>
      <view v-if="!dataForm.specifications">
        <view class="list">
          <view>
            <text>{{ $t('xiaoShouJiaGe') }}</text><text class="required">
              *
            </text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.price"
              :disabled="showProd"
              type="number"
              :placeholder="$t('qingTianXie')"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.price, 'price', 0.01, 100000000)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>{{ $t('shiChangJiaGe') }}</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.oriPrice"
              :disabled="showProd"
              type="number"
              :placeholder="$t('huaXianJia')"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.oriPrice, 'oriPrice', 0, 100000000)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>{{ $t('kuCun') }}</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @click="toChangeStock(-1,'warehouse')"
          >
            <input
              v-if="
                (prodStore.stockPointInfo.warehouseSize===1 && dataForm.mold!==2 && dataForm.mold!==3)
                  ||
                  dataForm.mold===1
                  ||
                  (dataForm.mold===3&&dataForm.isBindVoucher!==1)
              "
              v-model="dataForm.warehouseStock"
              :disabled="showProd"
              :min="0"
              :maxlength="7"
              type="number"
              :placeholder="$t('qingTianXie-0')"
              placeholder-style="color:#999"
              @blur="numHandleInputValue(dataForm.warehouseStock, 'warehouseStock', 0, 9999999)"
              @input="onStockInput(dataForm.warehouseStock)"
            >
            <view
              v-else
              style="color: #999;display: flex; align-items: center;"
            >
              {{ dataForm.warehouseStock }}
              <view class="icon" />
            </view>
          </view>
        </view>
        <view
          v-if="prodStore.stockPointInfo.stationSize > 0 && dataForm.mold !== 3 && dataForm.mold !== 1"
          class="list"
        >
          <view>
            <text>{{ $t('menDianKuCun') }}</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @click="toChangeStock(-1,'station')"
          >
            <view style="color: #999;display: flex; align-items: center;">
              {{ dataForm.stationStock }}
              <view class="icon" />
            </view>
          </view>
        </view>
        <view class="list">
          <view>
            <text>{{ $t('zongKuCun') }}</text>
          </view>
          <view class="right">
            <view style="color: #999;display: flex; align-items: center;">
              {{ dataForm.totalStocks }}
            </view>
          </view>
        </view>
        <view
          v-if="dataForm.mold !== 1 && dataForm.mold !== 3"
          class="list"
        >
          <view>
            <text>{{ $t('tiJiM') }}</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.volume"
              :disabled="showProd"
              type="number"
              :placeholder="$t('keXuanTian-0')"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.volume, 'volume', 0, 100000000)"
            >
          </view>
        </view>
        <view
          v-if="dataForm.mold !== 1 && dataForm.mold !== 3"
          class="list"
        >
          <view>
            <text>{{ $t('zhongLiangKg') }}</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.weight"
              :disabled="showProd"
              type="number"
              :placeholder="$t('keXuanTian-1')"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.weight, 'weight', 0.01, 100000000)"
            >
          </view>
        </view>
        <view
          v-if="dataForm.mold !== 2"
          class="list"
        >
          <view>
            <text>{{ $t('kuCunYuJing') }}</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.stockWarning"
              type="number"
              :min="0"
              :disabled="showProd"
              :maxlength="7"
              :placeholder="$t('keXuanTian-2')"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.stockWarning, 'stockWarning', 0, 9999999)"
              @input="onStockInput(dataForm.warehouseStock)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>{{ $t('shangPinBianMa') }}</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.partyCode"
              type="text"
              :placeholder="$t('ruWuBianMaJiangZiDongShengCheng')"
              :disabled="showProd"
              placeholder-style="color:#999"
              @blur="validatePartyCode(dataForm.partyCode)"
            >
          </view>
        </view>
        <view
          v-if="dataForm.mold === 3 && dataForm.isBindVoucher === 1"
          class="list"
        >
          <view>
            <text>{{ $t('guanLianKaQuan-0') }}</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @tap="toCouponPage"
          >
            <text :class="dataForm.skuList[0]?.voucherName ? 'selected' : ''">
              {{ dataForm.skuList[0]?.voucherName ? dataForm.skuList[0].voucherName : $t('quGuanLian') }}
            </text>
            <view class="icon" />
          </view>
        </view>
        <view
          v-if="dataForm.mold === 2"
          class="list"
        >
          <view>
            <text>{{ $t('guanLianShangPin') }}</text>
          </view>
          <view
            class="right"
            @tap="toAssociationGoods()"
          >
            <text :class="dataForm.skuList.length > 0 ? 'selected' : ''">
              {{ dataForm.skuComboList?.length > 0 ? $t('yiGuanLianSkucombolistlengthJian').replace(['length'], dataForm.skuComboList?.length) : $t('quGuanLian') }}
            </text>
            <view class="icon" />
          </view>
        </view>
      </view>
      <view v-if="dataForm.specifications">
        <view class="list">
          <view>
            <text>{{ $t('shangPinGuiGe') }}</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @tap="toSpecificationManagement"
          >
            <text :class="dataForm.skuList.length > 0 ? 'selected' : ''">
              {{ dataForm.skuList.length > 0 ? $t('yiSheZhi') : $t('qingXuanZe') }}
            </text>
            <view class="icon" />
          </view>
        </view>
        <view
          v-if="dataForm.skuList.length > 0"
          class="list"
        >
          <view>
            <text>{{ $t('guiGeMingXi') }}</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @tap="toSpecificationBreakdown"
          >
            <text :class="dataForm.skuList.length > 0 ? 'selected' : ''">
              {{ dataForm.skuList.length > 0 ? $t('gongSkuListXiang').replace('[skuList]', dataForm.skuList.length) : $t('qingXuanZeGuiGe') }}
            </text>
            <view class="icon" />
          </view>
        </view>
      </view>
    </view>

    <!-- 配送 -->
    <view
      v-if="dataForm.prodType !== 5 && dataForm.mold !== 1 && dataForm.mold !== 3"
      class="goods-delivery goods"
    >
      <view class="list">
        <view>
          <text>{{ $t('peiSongFangShi') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="deliveryModeOpen"
        >
          <text
            :class="dataForm.deliveryModeVo.hasUserPickUp || dataForm.deliveryModeVo.hasShopDelivery || dataForm.deliveryModeVo.hasCityDelivery ? 'selected' : ''"
          >
            {{ deliveryModeStr }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view
        v-if="dataForm.deliveryModeVo.hasShopDelivery"
        class="list"
      >
        <view>
          <text>{{ $t('yunFeiSheZhi') }}</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toTableRate"
        >
          <text :class="dataForm.deliveryTemplateName ? 'selected' : ''">
            {{ dataForm.deliveryTemplateName ? dataForm.deliveryTemplateName : $t('qingXuanZe') }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 参数 -->
    <view class="goods">
      <view class="list">
        <view>
          <text>{{ $t('canShuSheZhi') }}</text>
        </view>
        <view
          class="right"
          @tap="toParameter"
        >
          <text :class="dataForm.prodParameterList.length > 0 ? 'selected' : ''">
            {{ dataForm.prodParameterList.length > 0 ? $t('gongProdparameterlistZu').replace('[prodParameterList]', dataForm.prodParameterList.length) : $t('qingTianJia') }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!--  卡券 使用说明  -->
    <view
      v-if="dataForm.mold === 3"
      class="goods instructions-use-wrap"
    >
      <view class="list">
        <view>
          <text>{{ $t('shiYongShuoMing') }}</text><text class="required">
            *
          </text>
        </view>
      </view>
      <view class="textarea-box">
        <textarea
          v-model="dataForm.directions"
          :placeholder="$t('dianJiShuRuShiYongShuoMing')"
          maxlength="250"
        />
        <!--          @blur="checkInput('intro')"-->
      </view>
    </view>

    <!-- 核销 -->
    <view
      v-if="dataForm.mold === 1 || dataForm.mold === 3"
      class="goods"
    >
      <view
        v-if="dataForm.mold === 1"
        class="list"
      >
        <view>
          <text>{{ $t('heXiaoCiShu-0') }}</text>
        </view>
        <view
          class="right"
          @tap="toWriteOff"
        >
          <text :class="dataForm.writeOffNum !== null ? 'selected' : ''">
            {{ dataForm.writeOffNum === 1 ? $t('danCiHeXiao') : null }}{{ dataForm.writeOffNum === 0 ? $t('wuXuHeXiao') : null }}{{
              dataForm.writeOffNum === -1 ? $t('duoCiHeXiao'): null }} {{ dataForm.writeOffNum === null ? $t('qingXuanZe') : null }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view
        v-if="dataForm.mold === 1 || dataForm.mold === 3"
        class="list"
      >
        <view>
          <text>{{ $t('yongHuLiuYan') }}</text>
        </view>
        <view
          class="right"
          @tap="toMessage"
        >
          <text :class="dataForm.virtualRemark.length > 0 ? 'selected' : ''">
            {{ dataForm.virtualRemark.length > 0 ? $t('gongVirtualremarkZu').replace('[virtualRemark]', dataForm.virtualRemark.length) : $t('qingTianJia') }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="goods-details goods">
      <view class="list">
        <view>
          <text>{{ $t('shangPinXiangQing') }}</text>
        </view>
        <view
          class="right"
          @tap="toCommodityDetails"
        >
          <text :class="dataForm.content ? 'selected' : ''">
            {{ dataForm.content ? $t('yiTianJia') : $t('qingTianJia') }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 上架 -->
    <view class="grounding">
      <button
        class="button"
        type="primary"
        @tap="submit"
      >
        {{ dataForm.prodId ?showProd?$t('queDing'): $t('baoCun') : $t('shangJiaChuShou') }}
      </button>
    </view>

    <!-- 选择商品类型 -->
    <uni-popup
      ref="moldPopupRef"
      type="bottom"
    >
      <view class="optionType">
        <view class="title">
          <text>{{ $t('xuanZeShangPinLeiXing') }}</text>
          <view
            class="close iconfont"
            @tap="moldClose(1)"
          >
            &#xe60e;
          </view>
        </view>
        <view
          :class="mold === 0 ? 'active list' : 'list'"
          @tap="moleChange(0)"
        >
          <view class="left">
            <text>{{ $t('shiWuShangPin') }}</text><text class="hint">
              {{ $t('wuLiuFaHuo') }}
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="mold === 2 ? 'active list' : 'list'"
          @tap="moleChange(2)"
        >
          <view class="left">
            <text>{{ $t('zuHeShangPin') }}</text><text class="hint">
              {{ $t('wuLiuFaHuo-0') }}
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="mold === 1 ? 'active list' : 'list'"
          @tap="moleChange(1)"
        >
          <view class="left">
            <text>{{ $t('xuNiShangPin') }}</text><text class="hint">
              {{ $t('wuXuWuLiu') }}
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="mold === 3 ? 'active list' : 'list'"
          @tap="moleChange(3)"
        >
          <view class="left">
            <text>{{ $t('dianZiKaQuan') }}</text><text class="hint">
              {{ $t('wuXuWuLiu-0') }}
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view class="">
          <button
            class="button"
            type="primary"
            @tap="moldClose"
          >
            {{ $t('queDing') }}
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 商品配送方式选取 -->
    <selectPopup
      ref="deliveryModeRef"
      :lists="deliveryModeList"
      :is-mult="true"
      :null-tips="$t('qingXuanZePeiSongFangShi')"
      :tips="$t('yongHuZiTiJiTongChengPeiSongXuZaiKuCun')"
      @change="deliveryModeVoChange"
    />
  </view>
</template>

<script setup>
import { validNoEmptySpace } from '@/utils/validate'
import selectPopup from '../../components/select-popup/select-popup.vue'
import util from '../../../utils/util'
const Data = reactive({
  isSubmit: true,
  isNullLen: 0,
  mold: 0,
  masterLang: null
})

const { mold } = toRefs(Data)

const prodStore = useProdStore()

const dataForm = computed(() => {
  return prodStore.dataForm
})

const selected = computed(() => {
  return prodStore.selected
})

// 配送方式回显
const deliveryModeStr = computed(() => {
  const { hasShopDelivery, hasUserPickUp, hasCityDelivery } = prodStore.dataForm.deliveryModeVo
  if (!hasShopDelivery && !hasUserPickUp && !hasCityDelivery) {
    return $t('qingXuanZe')
  }
  let str = ''
  if (hasShopDelivery) {
    str += $t('kuaiDiPeiSong')
  }
  if (hasUserPickUp) {
    str = str + (hasShopDelivery ? '/' : '') + $t('yongHuZiTi')
  }
  if (hasCityDelivery) {
    str = str + (hasShopDelivery || hasUserPickUp ? '/' : '') + $t('tongChengPeiSong')
  }
  return str
})

// 电子卡券-商品-单规格 总库存=库存
watch(() => dataForm.value.warehouseStock, (stockNum) => {
  if (dataForm.value.mold === 3 && dataForm.value.isBindVoucher !== 1) {
    prodStore.dataForm.totalStocks = stockNum
  }
})
const showProd = ref(false)
onLoad((options) => {
  if (options.prodId || options.add) {
    uni.removeStorageSync('bbcProdDataFrom')
    prodStore.resetForm()
  }
  if (options.prodBelongs) {
    showProd.value = true
  }
  if (options.showProd === 'true') {
    showProd.value = true
  }
  getProdInfo(options.prodId)
  prodStore.getPointInfo()
})

onShow(() => {
  const router = getCurrentPages()
  if (router[router.length - 2]?.route === '/package-prod/pages/prod-management/prod-management' && !(router[router.length - 1].options.add) && !(router[router.length - 1].options.prodId)) {
    uni.navigateTo({
      url: 'pages/index/index'
    })
  }

  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: prodStore.scroll,
      duration: 0
    })
  }, 0)

  uni.setNavigationBarTitle({
    title: $t('faBuShangPin')
  })
})

onHide(() => {
  // #ifdef H5
  prodStore.scroll = document.documentElement.scrollTop
  // #endif
})

const getLangList = () => {
  http.request({
    url: '/sys/lang',
    method: 'GET',
    data: {
    }
  }).then(({ data: res }) => {
    if (!prodStore.dataForm.prodId) {
      Data.masterLang = res.lang
      prodStore.dataForm.prodLangList = [{
        prodId: 0,
        lang: res.lang,
        prodName: '',
        brief: '',
        content: ''
      }]
    } else {
      for (const item of prodStore.dataForm.prodLangList) {
        if (item.prodName === prodStore.dataForm.prodName) {
          Data.masterLang = item.lang
          break
        }
      }
    }
  })
}

// 数据反显
const getProdInfo = (prodId) => {
  if (prodId) {
    http.request({
      url: `/prod/prod/info/${prodId}`,
      method: 'GET',
      data: {
        showProd: showProd.value
      }
    }).then(({ data: res }) => {
      res.deliveryModeVo = JSON.parse(res.deliveryMode)
      res.deliveryMode = JSON.parse(res.deliveryMode)
      res.oldSkuList = JSON.parse(JSON.stringify(res.skuList))
      res.virtualRemark = res.virtualRemark ? JSON.parse(res.virtualRemark) : []
      prodStore.dataForm = {
        ...prodStore.dataForm,
        ...res,
        changeStock: res.totalStocks
      }
      prodStore.dataForm.skuList.forEach(sku => {
        sku.changeStock = 0
      })
      if (!prodStore.dataForm.preSellTime) {
        prodStore.dataForm.preSellTime = ''
      }
      if (prodStore.dataForm.skuList.length === 1 && prodStore.dataForm.skuList[0].properties === '') { // 单规格处理
        prodStore.dataForm.specifications = false
        prodStore.dataForm.volume = prodStore.dataForm.skuList[0].volume
        prodStore.dataForm.partyCode = prodStore.dataForm.skuList[0].partyCode
        prodStore.dataForm.weight = prodStore.dataForm.skuList[0].weight
        prodStore.dataForm.stockWarning = prodStore.dataForm.skuList[0].stockWarning
        prodStore.dataForm.warehouseStock = prodStore.dataForm.skuList[0].warehouseStock || prodStore.dataForm.skuList[0].stocks
        prodStore.dataForm.stationStock = prodStore.dataForm.skuList[0].stationStock
        prodStore.dataForm.skuId = prodStore.dataForm.skuList[0].skuId
        prodStore.stockPointList = prodStore.dataForm.skuList[0].stockPointList
        prodStore.dataForm.skuComboList = prodStore.dataForm.skuList[0].skuComboList
      } else { // 多规格处理
        prodStore.dataForm.specifications = true
      }
      if (prodStore.dataForm.imgs) prodStore.dataForm.imageData = prodStore.dataForm.imgs.split(',')
      if (prodStore.dataForm.video) prodStore.dataForm.videoData = prodStore.dataForm.video.split(',')
      if (prodStore.dataForm.brand) prodStore.dataForm.brandName = prodStore.dataForm.brand.name
      // 运费反显
      // 统一包邮
      if (prodStore.dataForm.deliveryTemplateId === 0) {
        prodStore.dataForm.deliveryTemplateName = $t('tongYiBaoYou')
        prodStore.deliveryIndex.index = 1
      }
      // 统一运费
      if (prodStore.dataForm.deliveryTemplateId === -1) {
        prodStore.dataForm.deliveryTemplateName = prodStore.dataForm.deliveryAmount + $t('yuan')
        prodStore.deliveryIndex.pic = prodStore.dataForm.deliveryAmount
        prodStore.deliveryIndex.index = 2
      }
      // 运费模板
      if (prodStore.dataForm.deliveryTemplateId > 0) {
        prodStore.deliveryIndex.id = prodStore.dataForm.deliveryTemplateId
        prodStore.deliveryIndex.index = 3
        getdeliveryTemplateName()
      }
      getCategoryName()
      getLangList()
    })
  } else {
    getLangList()
  }
}

/**
* 只允许输入正数和小数(保留小数点后两位)
*/
const checkInput = (num) => {
  if (num) {
    let tmpVal = String(num).replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

// 获取分类名称
const getCategoryName = () => {
  http.request({
    url: '/prod/category/listAvailableSigningCategory',
    method: 'GET',
    data: {

    }
  }).then(({ data: res }) => {
    prodStore.dataForm.classifyName[2] = (res.filter(item => item.categoryId === prodStore.dataForm.categoryId))[0]
    prodStore.dataForm.classifyName[1] = (res.filter(item => item.categoryId === prodStore.dataForm.classifyName[2].parentId))[0]
    prodStore.dataForm.classifyName[0] = (res.filter(item => item.categoryId === prodStore.dataForm.classifyName[1].parentId))[0]
    prodStore.selected.categoryName = prodStore.dataForm.classifyName[0].categoryName + '/' + prodStore.dataForm.classifyName[1].categoryName + '/' + prodStore.dataForm.classifyName[2].categoryName
    getShopTypeName()
  })
}

// 获取运费模板名称
const getdeliveryTemplateName = () => {
  if (!prodStore.dataForm.deliveryTemplateId) {
    return
  }

  http.request({
    url: `/shop/transport/info/${prodStore.dataForm.deliveryTemplateId}`,
    method: 'GET',
    data: {}
  }).then(({ data: res }) => {
    prodStore.dataForm.deliveryTemplateName = res.transName
    prodStore.deliveryIndex.name = res.transName
  })
}

// 获取店铺类目名称
const getShopTypeName = () => {
  http.request({
    url: '/prod/category/listCategory',
    method: 'GET',
    data: {
      status: 1
    }
  }).then(({ data: res }) => {
    prodStore.selected.shopCategoryName = (res.filter(item => item.categoryId === prodStore.dataForm.shopCategoryId))[0].categoryName
  })
}

// 商品排序
const seqChange = (e) => {
  if (e.detail.value) {
    prodStore.dataForm.seq = Math.floor(e.detail.value)
    if (prodStore.dataForm.seq > 32767) {
      prodStore.dataForm.seq = 32767
    }
  }
}

const changeSpecifications = () => {
  prodStore.dataForm.specifications = !prodStore.dataForm.specifications
  if (prodStore.dataForm.specifications) {
    // 多规格
    prodStore.dataForm.skuList = []
  } else {
    // 单规格
    prodStore.dataForm.volume = 0
    prodStore.dataForm.partyCode = ''
    prodStore.dataForm.weight = 0.01
    prodStore.dataForm.stockWarning = 0
    prodStore.dataForm.skuId = null
    prodStore.dataForm.price = 0.01
    prodStore.dataForm.oriPrice = 0.01
    prodStore.dataForm.totalStocks = 0
    prodStore.dataForm.warehouseStock = 0
    prodStore.dataForm.stationStock = 0
    prodStore.dataForm.skuList = []
    prodStore.stockPointList = [{
      stock: 0,
      stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
      stockPointType: 1,
      type: 0
    }]
    prodStore.dataForm.skuComboList = []
  }
}

/**
* 处理输入框数据
* @param data
* @param dataFields
* @param min 最小值
* @param max 最大值
*/
const handleInputValue = (data, dataFields, min, max) => {
  if (dataFields !== 'warehouseStock') {
    data = parseFloat(data)
  }
  if (dataFields === 'warehouseStock' && (prodStore.stockPointInfo.warehouseSize === 1 || prodStore.dataForm.mold === 1 || prodStore.dataForm.mold === 3)) {
    const stockPoint = prodStore.stockPointList[0]
    const stock = (+data > max) ? max : (data || 0)
    const changeStock = (stockPoint && stockPoint.skuId) ? stock - stockPoint.stock + (stockPoint.changeStock || 0) : undefined
    // 仅有一个仓库（默认仓库）时，直接修改库存时同步修改库存点列表
    prodStore.stockPointList = [{
      ...stockPoint,
      changeStock,
      stock,
      stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
      stockPointType: 1,
      type: 0
    }]
  }
  prodStore.dataForm[dataFields] = checkInput(data)
  if (data || data === 0) {
    // 保留两位小数
    if (data > max) {
      prodStore.dataForm[dataFields] = max
    }
    if (data <= min) {
      prodStore.dataForm[dataFields] = min
    }
  }
  if (isNaN(data)) {
    prodStore.dataForm[dataFields] = 0
  }
}

const onStockInput = (stock) => {
  if (stock) {
    stock = stock.toString().replace(/[^\d]/g, '')
    stock = stock > 9999999 ? 9999999 : Number(stock)
    nextTick(() => {
      prodStore.dataForm.warehouseStock = stock
      prodStore.dataForm.totalStocks = stock
    })
  }
}

// 整数
const numHandleInputValue = (data, dataFields, min, max) => {
  handleInputValue(Math.floor(data), dataFields, min, max)
}

// 配送方式改变
const deliveryModeVoChange = (selectList) => {
  prodStore.dataForm.deliveryModeVo = {
    hasShopDelivery: false,
    hasUserPickUp: false,
    hasCityDelivery: false
  }
  for (const item of selectList) {
    prodStore.dataForm.deliveryModeVo[item.key] = item.checked
  }
  if (prodStore.dataForm.mold === 2) {
    prodStore.handleComboStock()
  }
}

const deliveryModeRef = ref()
const deliveryModeList = ref([]) // 配送方式列表
// 打开配送方式弹出层
const deliveryModeOpen = async () => {
  if (showProd.value) return
  const { hasShopDelivery, hasUserPickUp, hasCityDelivery } = prodStore.dataForm.deliveryModeVo
  const { data } = await http.request({
    url: '/admin/station/countStation',
    method: 'get'
  })
  deliveryModeList.value = [{
    label: $t('kuaiDiPeiSong'),
    key: 'hasShopDelivery',
    disabled: false,
    checked: hasShopDelivery
  }, {
    label: $t('yongHuZiTi'),
    key: 'hasUserPickUp',
    disabled: data.count === 0, // 无门店时禁用
    checked: hasUserPickUp
  }, {
    label: $t('tongChengPeiSong'),
    key: 'hasCityDelivery',
    disabled: data.count === 0, // 无门店时禁用
    checked: hasCityDelivery
  }]
  deliveryModeRef.value.open()
}

/**
* 编码输入框校验
*/
const validatePartyCode = (partyCode) => {
  // 纯空格校验
  if (validNoEmptySpace(partyCode)) {
    prodStore.dataForm.partyCode = ''
  }
}

const verifySubmot = () => {
  if (!prodStore.dataForm.prodName) {
    uni.showToast({
      title: $t('qingShuRuShangPinMingCheng-0'),
      icon: 'none'
    })
    return true
  }

  if (prodStore.dataForm.imageData.length < 1) {
    uni.showToast({
      title: $t('qingXuanZeShangPinTuPian'),
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.categoryId == null) {
    uni.showToast({
      title: $t('qingXuanZePingTaiLeiMu'),
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.shopCategoryId == null) {
    uni.showToast({
      title: $t('qingXuanZeDianPuLeiMu'),
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.mold === null) {
    // 请选择商品分类
    uni.showToast({
      title: $t('qingXuanZeShangPinLeiXing'),
      icon: 'none'
    })
    return true
  }

  if (prodStore.dataForm.preSellStatus === 1 && !prodStore.dataForm.preSellTime) {
    // 请选择商品分类
    uni.showToast({
      title: $t('qingXuanZeYuShouFaHuoShiJian'),
      icon: 'none'
    })
    return true
  }

  // 单规格效验
  if (!prodStore.dataForm.specifications) {
    if (!prodStore.dataForm.price) {
      uni.showToast({
        title: $t('qingShuRuXiaoShouJiaGe'),
        icon: 'none'
      })
      return true
    }
    if (prodStore.dataForm.warehouseStock === '') {
      uni.showToast({
        title: $t('qingShuRuShangPinKuCun'),
        icon: 'none'
      })
      return true
    }
  } else { // 多规格效验
    if (prodStore.dataForm.skuList.length < 1) {
      uni.showToast({
        title: $t('qingXuanZeShangPinGuiGe'),
        icon: 'none'
      })
      return true
    }
  }
  if (prodStore.dataForm.deliveryTemplateId === null && prodStore.dataForm.prodType !== 5 && prodStore.dataForm.mold !== 1 && prodStore.dataForm.mold !== 3 && dataForm.value.deliveryModeVo.hasShopDelivery) {
    uni.showToast({
      title: $t('qingXuanZeYunFei'),
      icon: 'none'
    })
    return true
  }

  let isStatusLen = 0
  prodStore.dataForm.skuList.forEach(item => {
    if (item.status === 0) {
      isStatusLen++
    }
  })
  if (isStatusLen === prodStore.dataForm.skuList.length && prodStore.dataForm.specifications) {
    uni.showToast({
      title: $t('zhiShaoYaoQiYongYiZhongShangPinGuiGe'),
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.mold === 2 && prodStore.dataForm.skuList.some(item => (item.skuComboList.length === 0 && item.status !== 0))) {
    uni.showToast({
      title: $t('zuHeShangPinGuiGeZhiShaoXuYaoGuanLianYiGeShangPin'),
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.mold === 3) {
    if (!prodStore.dataForm.directions) {
      uni.showToast({
        title: $t('qingShuRuShiYongShuoMing'),
        icon: 'none'
      })
      return true
    }
    let isFlag = false
    if (dataForm.value.isBindVoucher === 1) {
      prodStore.dataForm.skuList?.forEach(item => {
        // 禁用状态，规格项可以不关联卡券
        if (item.status === 1) {
          if (!item.voucherId) isFlag = true
        }
      })
      if (isFlag) {
        uni.showToast({
          title: $t('shangPinWeiGuanLianKaQuan'),
          icon: 'none'
        })
        return true
      }
    }
  }
  return false
}

// 提交发布或修改
const submit = () => {
  if (showProd.value) {
  // #ifdef H5
    history.back()
    // #endif
    // #ifndef H5
    uni.navigateBack()
    // #endif
    return
  }
  // 提交前的数据处理
  dataAlignment()

  // 防止skuComboList为空产生报错
  prodStore.dataForm.skuList = prodStore.dataForm.skuList.map(item => {
    if (!item.skuComboList) {
      item.skuComboList = []
    }
    return item
  })
  if (verifySubmot() || !Data.isSubmit) {
    return
  }

  let data = JSON.parse(JSON.stringify(prodStore.dataForm))

  // 虚拟商品
  if (data.mold === 1 || data.mold === 3) {
    // 选择"无需核销"，没有核销有效期
    if (data.writeOffNum === 0) {
      data.writeOffTime = null
    }
    // 自定义核销有效天数
    // if (data.writeOffNum !== 0 && data.writeOffTime === 2) {
    //   data.writeOffTime = parseInt(prodStore.validDays)
    // }
    data.virtualRemark = JSON.stringify(data.virtualRemark)
    // 取消组合选品，预售，配送方式,运费模板
    data.prodType = 0
    data.preSellStatus = 0
    data.preSellTime = ''
    data.deliveryModeVo.hasUserPickUp = false
    data.deliveryModeVo.hasShopDelivery = true
    data.deliveryModeVo.hasCityDelivery = false
    data.deliveryTemplateId = null
    data.deliveryTemplateName = ''
    data.weight = null
    data.volume = null
  }
  if (data.mold !== 1 && data.mold !== 3) {
    // 普通商品，清空虚拟商品信息
    data = {
      ...data,
      virtualRemark: null,
      writeOffNum: null,
      writeOffTime: null,
      writeOffStart: null,
      writeOffEnd: null,
      isRefund: null
    }
    // 组合选品
    if (data.prodType === 5) {
      // 取消预售，配送
      data.preSellStatus = 0
      data.preSellTime = ''
      data.deliveryModeVo.hasUserPickUp = true
      data.deliveryModeVo.hasShopDelivery = true
      data.deliveryModeVo.hasCityDelivery = true
      data.deliveryTemplateId = null
      data.deliveryTemplateName = ''
    }
  }
  data.deliveryTemplateId = prodStore.dataForm.tableRate < 1 ? prodStore.dataForm.tableRate : prodStore.dataForm.deliveryTemplateId
  if (data.deliveryTemplateId !== -1) {
    data.deliveryAmount = null
  }
  if ((!prodStore.dataForm.specifications && prodStore.dataForm.totalStocks === 0) || (prodStore.dataForm.specifications && Data.isNullLen === prodStore.dataForm.skuList.length)) {
    uni.showModal({
      content: $t('gaiShangPinKuCunWei_0QueRenBaoCun'),
      icon: 'none',
      cancelText: $t('quXiao-0'),
      confirmText: $t('queDing'),
      success: (res) => {
        if (res.confirm) {
          Data.isSubmit = false
          http.request({
            url: '/prod/prod',
            method: prodStore.dataForm.prodId ? 'PUT' : 'POST',
            data
          }).then(() => {
            uni.showToast({
              title: prodStore.dataForm.prodId ? $t('xiuGaiChengGong') : $t('faBuChengGong'),
              icon: 'success'
            })
            setTimeout(() => {
              uni.reLaunch({
                url: '/package-prod/pages/prod-management/prod-management'
              })
            }, 1500)
          })
          setTimeout(() => {
            Data.isSubmit = true
          }, 2000)
        }
      }
    })
  } else {
    Data.isSubmit = false

    http.request({
      url: '/prod/prod',
      method: prodStore.dataForm.prodId ? 'PUT' : 'POST',
      data
    }).then(() => {
      uni.showToast({
        title: prodStore.dataForm.prodId ? $t('xiuGaiChengGong-0') : $t('faBuChengGong-0'),
        icon: 'success'
      })
      setTimeout(() => {
        uni.reLaunch({
          url: '/package-prod/pages/prod-management/prod-management'
        })
      }, 1500)
    })
    setTimeout(() => {
      Data.isSubmit = true
    }, 2000)
  }
}

// 提交前的数据处理
// eslint-disable-next-line max-lines-per-function
const dataAlignment = () => {
  Data.isNullLen = 0
  // 图片视频格式处理
  prodStore.dataForm.deliveryMode = null
  prodStore.dataForm.imgs = prodStore.dataForm.imageData.join(',')
  prodStore.dataForm.video = prodStore.dataForm.videoData.join(',')
  prodStore.dataForm.pic = prodStore.dataForm.imageData[0]
  const isExistMasterLang = prodStore.dataForm.prodLangList.find(f => Data.masterLang === f.lang) // 当前商品语言列表信息是否存在主语言
  prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => { // 多语言名称处理
    prodLang.prodId = prodStore.dataForm.prodId || 0
    if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
      prodLang.prodName = prodStore.dataForm.prodName
      prodLang.brief = prodStore.dataForm.brief
      prodLang.content = prodStore.dataForm.content
    } else {
      prodLang.prodName = prodLang.prodName || prodStore.dataForm.prodName
      prodLang.brief = prodLang.brief || prodStore.dataForm.brief
      prodLang.content = prodLang.content || prodStore.dataForm.content
    }
  })
  if (prodStore.dataForm.specifications) { // 多规格处理
    prodStore.dataForm.price = ''
    prodStore.dataForm.skuList.forEach((item, index) => {
      const skuLangList = []
      prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => {
        const findR = item.skuLangList?.find(f => f.lang === prodLang.lang) || {}
        if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
          skuLangList.push({
            skuId: item.skuId || 0,
            lang: prodLang.lang,
            properties: item.properties,
            skuName: item.skuName,
            prodName: item.prodName
          })
        } else {
          skuLangList.push({
            skuId: item.skuId || 0,
            lang: findR.lang || prodLang.lang,
            properties: findR.properties || item.properties,
            skuName: findR.skuName || item.skuName,
            prodName: findR.prodName || item.prodName
          })
        }
      })
      item.skuLangList = skuLangList
      if (!prodStore.dataForm.price && item.status === 1) {
        prodStore.dataForm.price = item.price
      }

      if (index === 0 || prodStore.dataForm.oriPrice < item.oriPrice) {
        prodStore.dataForm.oriPrice = item.oriPrice
      }

      if (index === 0) {
        prodStore.dataForm.totalStocks = item.stocks
      } else {
        prodStore.dataForm.totalStocks += item.stocks
      }

      if (item.stocks === 0) {
        Data.isNullLen++
      }
      if (!(item.stockPointList && item.stockPointList.length)) {
        item.stockPointList = [{
          stock: 0,
          stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
          stockPointType: 1,
          type: 0
        }]
      }
    })
  } else { // 单规格处理
    prodStore.dataForm.oriPrice = prodStore.dataForm.oriPrice || 0
    const voucherName = prodStore.dataForm.skuList[0]?.voucherName || null
    const voucherId = prodStore.dataForm.skuList[0]?.voucherId || null
    prodStore.dataForm.skuList = []
    const skuLangList = []
    prodStore.dataForm.prodLangList.forEach(prodLang => {
      skuLangList.push({
        skuId: prodStore.dataForm.skuId || 0,
        lang: prodLang.lang,
        properties: '',
        skuName: '',
        prodName: prodStore.dataForm.prodName
      })
    })
    if (prodStore.dataForm.mold === 3 && dataForm.value.isBindVoucher === 1) {
      if (prodStore.dataForm.skuId) {
        if (prodStore.dataForm.stocks !== undefined) {
          prodStore.dataForm.totalStocks = prodStore.dataForm.stocks
        }
      } else {
        prodStore.dataForm.totalStocks = prodStore.dataForm.stocks
      }
    }
    prodStore.dataForm.skuList[0] = {
      changeStock: prodStore.dataForm.totalStocks - prodStore.dataForm.changeStock,
      oriPrice: prodStore.dataForm.oriPrice,
      partyCode: prodStore.dataForm.partyCode,
      price: prodStore.dataForm.price,
      prodName: prodStore.dataForm.prodName,
      skuId: prodStore.dataForm.skuId,
      properties: '',
      skuName: '',
      status: 1,
      warehouseStock: prodStore.dataForm.warehouseStock,
      stationStock: prodStore.dataForm.stationStock,
      stocks: prodStore.dataForm.totalStocks,
      volume: prodStore.dataForm.volume,
      weight: prodStore.dataForm.weight,
      stockWarning: prodStore.dataForm.stockWarning,
      skuLangList,
      stockPointList: prodStore.stockPointList || [{
        stock: 0,
        stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
        stockPointType: 1,
        type: 0
      }],
      skuComboList: prodStore.dataForm.skuComboList,
      voucherName,
      voucherId
    }
    if (prodStore.dataForm.mold === 3 && dataForm.value.isBindVoucher !== 1) {
      delete prodStore.dataForm.skuList[0].voucherName
      delete prodStore.dataForm.skuList[0].voucherId
    }
  }
  // 如果sku没有商品名称，则使用商品的商品名称
  if (prodStore.dataForm.skuList.length === 1 && !prodStore.dataForm.skuList[0].skuName) {
    prodStore.dataForm.skuList[0].prodName = prodStore.dataForm.prodName
  }

  // 多语言参数设置
  prodStore.dataForm.prodParameterList.forEach(parame => {
    parame.prodParameterId = parame.prodParameterId || 0
    parame.prodId = prodStore.dataForm.prodId || 0
    const prodParameterLangList = []
    prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => {
      const findR = parame.prodParameterLangList?.find(f => f.lang === prodLang.lang) || {}
      if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
        prodParameterLangList.push({
          prodParameterId: findR.prodParameterId || parame.prodParameterId || 0,
          lang: prodLang.lang,
          parameterKey: parame.parameterKey,
          parameterValue: parame.parameterValue
        })
      } else {
        prodParameterLangList.push({
          prodParameterId: findR.prodParameterId || parame.prodParameterId || 0,
          lang: prodLang.lang,
          parameterKey: findR.parameterKey || parame.parameterKey,
          parameterValue: findR.parameterValue || parame.parameterValue
        })
      }
    })
    parame.prodParameterLangList = prodParameterLangList
  })
}

const onChooseSuccessImages = () => { // 选择图片返回
  util.chooseImage({ count: 9 - prodStore.dataForm.imageData.length }).then((data) => {
    data.forEach((item) => {
      prodStore.dataForm.imageData.push(item.filePath)
    })
  })
}
// 删除图片
const onDeleteImage = (index) => {
  prodStore.dataForm.imageData.splice(index, 1)
}
const previewVideoSrc = ref('')
const onChooseVideo = () => {
  uni.chooseVideo({
    sourceType: ['camera', 'album'],
    success: async (res) => {
      const { name, size, tempFilePath } = res
      let videoType
      // #ifdef H5
      videoType = name.split('.')[name.split('.').length - 1]
      // #endif
      // #ifdef APP-PLUS
      videoType = tempFilePath.substring(tempFilePath.lastIndexOf('.') + 1)
      // #endif

      if (videoType !== 'mp4' && videoType !== 'mov' && videoType !== 'webm') {
        uni.showToast({
          title: $t('shiPinGeShiJinZhiChiMp4movwebm'),
          icon: 'none'
        })
        return
      }
      if (size > 20971520) {
        uni.showToast({
          title: $t('shiPinDaXiaoBuNengChaoGuo_20m'),
          icon: 'none'
        })
        return
      }
      const getPreSignUrlParams = {
        fileName: name
      }
      // #ifdef APP-PLUS
      const appFileBuffer = await util.plusIo(tempFilePath)
      getPreSignUrlParams.fileName = tempFilePath
      // #endif
      util.getPreSignUrl(getPreSignUrlParams).then(({ data }) => {
        // #ifdef H5
        uni.request({
          url: tempFilePath,
          method: 'GET',
          responseType: 'arraybuffer',
          success: (arraybufferRes) => {
            uploadVideoBuffer(data, arraybufferRes.data, size)
          }
        })
        // #endif

        // #ifdef APP-PLUS
        uploadVideoBuffer(data, appFileBuffer, size)
        // #endif
      })
    }
  })
}

const uploadVideoBuffer = (preSignUrlParams, buffer, size) => {
  uni.request({
    url: preSignUrlParams.preSignUrl,
    method: 'PUT',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: buffer
  }).then(() => {
    util.uploadSuccess([{
      filePath: preSignUrlParams.filePath,
      fileId: preSignUrlParams.fileId,
      fileSize: size
    }]).then(() => {
      prodStore.dataForm.videoData.splice(0, 1, preSignUrlParams.filePath)
    })
  })
}

const onDeleteVideo = () => {
  previewVideoSrc.value = ''
  prodStore.dataForm.videoData = []
}

const previewVideo = () => {
  previewVideoSrc.value = util.checkFileUrl(prodStore.dataForm.videoData[0])
}

// 是否预售
const preSellStatusChange = (e) => {
  e.detail.value ? prodStore.dataForm.preSellStatus = 1 : prodStore.dataForm.preSellStatus = 0
}

// 是否组合选品
const prodTypeChange = (e) => {
  if (e.detail.value) prodStore.dataForm.preSellStatus = 0
  e.detail.value ? prodStore.dataForm.prodType = 5 : prodStore.dataForm.prodType = 0
}

const moldPopupRef = ref()
// 商品类型弹出层
const moldOpen = () => {
  if (prodStore.dataForm.prodId) {
    uni.showToast({
      title: $t('yiFaBuDeShangPinBuYunXuXiuGaiShangPinLeiXing'),
      icon: 'none'
    })
    return
  }
  Data.mold = prodStore.dataForm.mold
  moldPopupRef.value.open('share')
}

const moleChange = (num) => {
  Data.mold = num
  if (Data.mold === 2 && prodStore.dataForm.preSellStatus === 1) {
    prodStore.dataForm.preSellStatus = 0
  }
  if (Data.mold === 3) {
    // 商品类型选择电子卡券，默认开启关联卡券
    prodStore.dataForm.isBindVoucher = 1
  }
}

// type 1为取消这次选择
const moldClose = (type) => {
  if (type !== 1) {
    prodStore.dataForm.mold = Data.mold
  }
  if (prodStore.dataForm.mold !== 0) prodStore.dataForm.prodType = 0
  // 修改商品类型时，清除对应的库存（新建）
  if (!prodStore.dataForm.specifications) { // 单规格处理
    prodStore.stockPointList = [{
      stock: 0,
      stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
      stockPointType: 1,
      type: 0
    }]
  } else {
    prodStore.dataForm.skuList.forEach((sku) => {
      if (sku.stocks) {
        sku.warehouseStock = 0
        sku.stationStock = 0
        sku.stocks = 0
        sku.stockPointList = [{
          stock: 0,
          stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
          stockPointType: 1,
          type: 0
        }]
      }
    })
  }
  prodStore.dataForm.warehouseStock = 0 // 仓库库存
  prodStore.dataForm.stationStock = 0 // 门店库存
  prodStore.dataForm.totalStocks = 0 // 总库存
  moldPopupRef.value.close()
}

// 选择商品类目
const toSelectType = (value) => {
  if (showProd.value) return
  prodStore.dataForm.selectType = value
  uni.navigateTo({
    url: '/package-prod/pages/select-type/select-type'
  })
}

// 选择品牌
const toCommodityBrand = () => {
  if (showProd.value) return
  if (!prodStore.dataForm.categoryId) {
    uni.showToast({
      title: $t('qingXianXuanZePingTaiLeiMu'),
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/commodity-brand'
  })
}

// 选择预售时间
const toPresellTime = () => {
  if (showProd.value) return
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/presell-time'
  })
}

// 选择规格
const toSpecificationManagement = () => {
  if (prodStore.dataForm.mold === null) {
    uni.showToast({
      title: $t('qingXianXuanZeShangPinLeiXing'),
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: '/package-prod/pages/specification-management/specification-management' + '?showProd=' + showProd.value
  })
}
// 规格明细
const toSpecificationBreakdown = () => {
  uni.navigateTo({
    url: '/package-prod/pages/specification-breakdown/specification-breakdown' + '?showProd=' + showProd.value
  })
}
// 运费模板
const toTableRate = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/table-rate'
  })
}
// 商品详情
const toCommodityDetails = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/commodity-details' + '?showProd=' + showProd.value
  })
}
// 参数设置
const toParameter = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-parameter' + '?showProd=' + showProd.value
  })
}
// 用户留言
const toMessage = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-message'
  })
}
// 核销
const toWriteOff = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-write-off'
  })
}
// 修改库存
const toChangeStock = (index, stockMode) => {
  if (showProd.value) return
  if (prodStore.dataForm.mold === 3 && dataForm.value.isBindVoucher === 1) {
    uni.showToast({
      title: $t('kuCunYouGaiKaQuanWeiFaFangShuLiangJueDingBuNengDanDuBianJi'),
      icon: 'none'
    })
    return
  }
  if (prodStore.dataForm.mold === 2) {
    uni.showToast({
      title: $t('zuHeShangPinBuNengBianJiKuCun'),
      icon: 'none'
    })
    return
  }
  const { warehouseSize, stationSize } = prodStore.stockPointInfo
  if ((stockMode === 'warehouse' && warehouseSize === 1) || (stockMode === 'station' && stationSize === 0) || prodStore.dataForm.mold === 1 || prodStore.dataForm.mold === 3) {
    return
  }
  if (prodStore.dataForm.mold === null) {
    uni.showToast({
      title: $t('qingXianXuanZeShangPinLeiXing-0'),
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: `/package-prod/pages/post-prod/stock-update?indexValue=${index}&stockModeStr=${stockMode}`
  })
}

const toAssociationGoods = () => {
  uni.navigateTo({
    url: '/package-prod/pages/association-goods/association-goods'
  })
}

/**
 * 预售时间显示为 ’YYYY-MM-DD‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  return val.slice(0, -8).trim()
}
const changeIsBindVoucher = () => {
  prodStore.dataForm.isBindVoucher = prodStore.dataForm.isBindVoucher == 1 ? 0 : 1
  if (!prodStore.dataForm.specifications) { // 单规格处理
    prodStore.stockPointList = [{
      stock: 0,
      stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
      stockPointType: 1,
      type: 0
    }]
  } else {
    prodStore.dataForm.skuList.forEach((sku) => {
      if (sku.stocks) {
        sku.warehouseStock = 0
        sku.stationStock = 0
        sku.stocks = 0
        sku.stockPointList = [{
          stock: 0
        }]
      }
    })
  }
  prodStore.dataForm.stocks = 0
  prodStore.dataForm.warehouseStock = 0 // 仓库库存
  prodStore.dataForm.stationStock = 0 // 门店库存
  prodStore.dataForm.totalStocks = 0 // 总库存
  if (prodStore.dataForm.isBindVoucher !== 1) {
    if (prodStore.dataForm.specifications) {
      prodStore.dataForm.skuList.map((item) => {
        delete item.voucherId
        delete item.voucherName
        return item
      })
    }
  }
}
const toCouponPage = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/coupon-page'
  })
}
</script>

<style lang="scss" scoped>
@use "post-prod";
</style>
