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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <div class="Mall4j sypplier-product-components">
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="rules"
      label-width="90px"
    >
      <!-- 基本信息 -->
      <div class="basic">
        <div class="title">
          {{ $t('product.prodInfo.baseInfo') }}
        </div>
        <el-form-item
          label-width="120px"
          :label="$t('product.prodInfo.SelectedClassification')"
        >
          <div>
            <div class="platform-type shop-type">
              <div class="text-box">
                {{ $t('product.prodInfo.platformClassification') }}：<span class="text"> {{ selectedCategories[0].name }} >
                  {{ selectedCategories[1].name }} > {{ selectedCategories[2].name }}</span>
              </div>
              <div
                v-if="!dataForm.spuId"
                class="amend"
                @click="changeCategory"
              >
                {{ $t('table.modify') }}
              </div>
            </div>
            <div class="platform-type-text">
              {{ $t('product.prodInfo.platformClassificationNoModified') }}
            </div>
          </div>
        </el-form-item>
        <!-- 基本属性 -->
        <el-form-item
          v-if="dataForm.spuAttrValues.length > 0"
          label-width="120px"
          :label="$t('product.prodInfo.basicProperties')"
        >
          <div class="base-box">
            <el-form-item
              v-for="(item, index) in dataForm.spuAttrValues"
              :key="index"
              label-width="180px"
              :label="language === 'en' && item.attrLangList.length > 1 ? item.attrLangList[1].name : item.attrLangList[0].name"
              :required="item.searchType === 1"
            >
              <el-select
                v-if="item.attrValues.length > 0"
                v-model="item.attrValueId"
                :placeholder="$t('tip.select')"
              >
                <el-option
                  v-for="el in item.attrValues"
                  :key="el.attrValueId"
                  :label="el.values[0].value"
                  :value="el.attrValueId"
                />
              </el-select>
              <el-input
                v-else
                v-model="item.attrValueName"
                label-width="180px"
                :placeholder="$t('tip.input') + language === 'en' && item.attrLangList.length > 1 ? ' ' + item.attrLangList[1].name : item.attrLangList[0].name"
              />
            </el-form-item>
          </div>
          <div class="base-tip">
            {{ $t('product.prodInfo.baseTipBefore') }}<span style="color:#FF0000">*</span>{{
              $t('product.prodInfo.baseTipAfter') }}
          </div>
        </el-form-item>
        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.shopName')"
          prop="name"
        >
          <el-input
            v-model="dataForm.name"
            class="w514"
            width="120px"
            maxlength="60"
            :placeholder="$t('product.prodInfo.shopNameTips')"
          />
          <div class="hint">
            {{ $t('product.prodInfo.shopNameHint') }}
          </div>
        </el-form-item>

        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.shopPoints')"
        >
          <el-input
            v-model="dataForm.sellingPoint"
            class="w514"
            width="120px"
            maxlength="60"
            :placeholder="$t('product.prodInfo.shopPointsTips')"
          />
          <div class="hint">
            {{ $t('product.prodInfo.shopPointsHint') }}
          </div>
        </el-form-item>

        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.imgUrls')"
          prop="imgUrls"
        >
          <imgs-upload
            v-model:modelValue="dataForm.imgUrls"
            :type="'min'"
            :limit="9"
            @update:model-value="onPropChage('imgUrls')"
          />
          <div class="hint top0">
            {{ $t('product.prodInfo.imgUrlsHint') }}
          </div>
        </el-form-item>

        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.video')"
        >
          <video-upload
            v-model:value="dataForm.video"
            :type="'min'"
            :limit="1"
          />
          <div class="hint">
            {{ $t('product.prodInfo.videoHint') }}
          </div>
          <el-button
            v-if="dataForm.video"
            type="danger"
            @click="dataForm.video = null"
          >
            {{ $t("biz.videobox.deleteVideo") }}
          </el-button>
        </el-form-item>
        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.spuCode')"
        >
          <el-input
            v-model="dataForm.spuCode"
            maxlength="13"
            class="w246"
            :placeholder="$t('product.prodInfo.spuCodeTips')"
          />
          <div class="hint">
            {{ $t('product.prodInfo.spuCodeHint') }}
          </div>
        </el-form-item>

        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.brandName')"
        >
          <div class="brand">
            <span>
              <span class="brand-name">{{ dataForm.brandName }}</span>
              <el-icon
                v-if="dataForm.brandId && dataForm.brandName"
                class="el-icon-close del-brand"
                @click="handleCloseBrand"
              >
                <Close />
              </el-icon>
            </span>
            <span
              class="select"
              @click="selectBrand"
            >{{ $t('product.prodInfo.select') }}
            </span>
          </div>
        </el-form-item>

        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.number')"
        >
          <el-input
            v-model="dataForm.seq"
            class="w160"
            oninput="value=value.replace(/[^0-9]/g,'')"
            @input="value => dataForm.seq = Math.min(value, 32767)"
          />
        </el-form-item>
      </div>
      <!-- 规格库存 -->
      <div class="specification">
        <div class="title">
          {{ $t('product.prodInfo.speStock') }}
        </div>
        <sku-tag
          ref="skuTagRef"
          @has-sku-img-change="hasSkuImgChange"
        />
        <sku-table
          ref="skuTableRef"
          :spu-mold="spuMold"
          :is-update="!!dataForm.spuId"
          @on-change-data="handleChangeData"
        />
      </div>
      <!-- 运费设置 -->
      <div class="freight">
        <div class="title">
          {{ $t('product.prodInfo.freightSettings') }}
        </div>
        <el-form-item
          class="item"
          label-width="120px"
          :label="$t('product.prodInfo.distributionMethod')"
          required
        >
          <el-checkbox
            v-model="checked"
            disabled
          >
            {{ $t('product.prodInfo.expressDelivery') }}
          </el-checkbox>
        </el-form-item>
        <!-- 运费模板 -->
        <el-form-item
          class="item"
          label="运费设置"
          label-width="120px"
        >
          <el-radio
            v-model="dataForm.tableRate"
            :label="0"
          >
            包邮
          </el-radio>
          <el-radio
            v-model="dataForm.tableRate"
            :label="-1"
            @change="onHandleFreight"
          >
            固定运费
          </el-radio>
          <el-radio
            v-model="dataForm.tableRate"
            :label="1"
          >
            运费模板
          </el-radio>
        </el-form-item>
        <el-form-item
          v-if="dataForm.tableRate>0"
          class="item"
          label-width="120px"
          label="运费模板"
          prop="deliveryTemplateId"
        >
          <div class="freightSelect">
            <el-select
              v-model="dataForm.deliveryTemplateId"
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="item in freightList"
                :key="item.transportId"
                :label="item.transName"
                :value="item.transportId"
              />
            </el-select>
            <div
              class="flush"
              @click="getFreightList"
            >
              {{ $t('tagsView.refresh') }}
            </div>
            <el-divider direction="vertical" />
            <div
              class="add"
              @click="addFreight"
            >
              {{ $t('product.prodInfo.add') }}
            </div>
          </div>
          <div class="hint">
            {{ $t('product.prodInfo.freightHint') }}
          </div>
        </el-form-item>
        <el-form-item
          v-if="dataForm.tableRate===-1"
          class="item"
          label="固定运费"
          prop="deliveryAmount"
          label-width="120px"
        >
          <div class="freight-inp">
            <el-input
              v-model="dataForm.deliveryAmount"
              :min="0.01"
              maxlength="10"
              placeholder="请输入金额"
              @blur="handleInputValue(dataForm.deliveryAmount,'deliveryAmount',0.01,9999)"
            />
          </div>
        </el-form-item>
      </div>
    </el-form>
    <!-- 平台分类弹窗 -->
    <category-selector
      v-if="editPlatformCategoriesSelect"
      ref="categorySelectRef"
      @get-category-selected="getCategorySelected"
    />
    <!-- 选择品牌弹窗 -->
    <brand-selector
      v-if="visibleBrandPopUp"
      ref="selectBrandRef"
      :is-single="true"
      @refresh-select-brand="refreshSelectBrand"
    />
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="getFreightList()"
    />
  </div>
</template>

<script setup>
import skuTag from './sku-tag.vue'
import skuTable from './sku-table.vue'
import * as apiTransport from '@/api/distribution-manage/transport'
import Big from 'big.js'
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce'
import * as api from '@/api/product/prod-info'
import addOrUpdate from '@/views/modules/order/delivery-manage/transport/add-or-update.vue'
import { onBeforeMount } from 'vue'

const emit = defineEmits(['nextStep'])

const props = defineProps({
  // 0-普通商品;1-虚拟商品;2-组合商品
  spuMold: {
    default: 0,
    type: Number
  }
})

const Data = reactive({
  dataForm: {
    tableRate: -1, // 0 包邮 -1 固定运费 大于0运费模板id
    deliveryAmount: 0.01,
    spuId: null,
    name: '',
    sellingPoint: '',
    imgUrls: '',
    video: '',
    spuCode: '',
    seq: 0,
    brandName: '',
    deliveryMode: {
      hasCityDelivery: false,
      hasShopDelivery: true,
      hasUserPickUp: false
    },
    deliveryTemplateId: null,
    spuAttrValues: [], // 基本属性列表
    hasSkuImg: 1, // sku是否含有图片 0无 1有
    spuMold: props.spuMold // 是否为组合商品0普通商品，1组合商品
  },
  freightList: [],
  addOrUpdateVisible: false,
  editPlatformCategoriesSelect: false,
  visibleBrandPopUp: false,
  checked: true,
  skuTableData: [], // sku表格返回数据
  skus: [] // 编辑返回的skus
})

const { dataForm, freightList, addOrUpdateVisible, editPlatformCategoriesSelect, visibleBrandPopUp, checked } = toRefs(Data)

watch(() => props.spuMold, (newVal) => {
  Data.dataForm.spuMold = newVal
})

const prodStore = useProdStore()

const validateNameZh = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error('不能全为空格'))
  } else {
    callback()
  }
}

const rules = computed(() => {
  return {
    name: [
      { required: true, message: $t('product.prodInfo.shopNameEmpty'), trigger: 'blur' },
      { validator: validateNameZh, trigger: 'blur' }
    ],
    imgUrls: [
      { required: true, message: $t('product.prodInfo.imgUrlsEmpty') }
    ],
    video: [
      { required: true, message: $t('product.prodInfo.videoEmpty'), trigger: 'blur' }
    ],
    deliveryTemplateId: [
      { required: true, message: $t('product.prodInfo.freightSettingsEmpty'), trigger: 'change' }
    ],
    deliveryAmount: [
      { required: true, message: '请输入金额', trigger: 'change' }
    ]
  }
})

const selectedCategories = computed(() => {
  return [
    Object.assign({}, prodStore.platProdCategory.firstCat),
    Object.assign({}, prodStore.platProdCategory.secondCat),
    Object.assign({}, prodStore.platProdCategory.threeCat)
  ]
})

onBeforeMount(() => {
  getFreightList()
})

const skuTableRef = ref(null)
// 回显数据
const init = (dataForm) => {
  Data.dataForm.spuId = dataForm.spuId
  Data.dataForm.spuMold = dataForm.spuMold
  Data.dataForm.name = dataForm.spuLangList[0].spuName
  Data.dataForm.sellingPoint = dataForm.spuLangList[0].sellingPoint
  Data.dataForm.imgUrls = dataForm.imgUrls
  Data.dataForm.video = dataForm.video
  Data.dataForm.spuCode = dataForm.spuCode
  Data.dataForm.brandName = dataForm.brand ? dataForm.brand.name : ''
  Data.dataForm.brandId = dataForm.brandId
  Data.dataForm.seq = dataForm.seq
  Data.dataForm.priceFee = dataForm.priceFee
  Data.dataForm.marketPriceFee = dataForm.marketPriceFee
  Data.dataForm.totalStock = dataForm.totalStock
  // 运费设置
  Data.dataForm.tableRate = dataForm.deliveryTemplateId > 0 ? 1 : dataForm.deliveryTemplateId
  Data.dataForm.deliveryTemplateId = dataForm.deliveryTemplateId > 0 ? dataForm.deliveryTemplateId : ''
  Data.dataForm.deliveryAmount = new Big(dataForm.deliveryAmount || 0).div(100).valueOf()
  // sku和table回显
  Data.skus = dataForm.skus
  Data.dataForm.hasSkuImg = dataForm.hasSkuImg
  skuTableRef.value.Data.skuList = dataForm.skus
  skuTagRef.value.init(dataForm)
}

const categorySelectRef = ref(null)
const changeCategory = () => {
  // 显示平台分类选择框
  Data.editPlatformCategoriesSelect = true
  nextTick(() => {
    categorySelectRef.value.init(0, 'platform', selectedCategories.value)
  })
}

// 获取分类选择组件返回数据
const getCategorySelected = (selectedCategories) => {
  Data.editPlatformCategoriesSelect = false
  Data.dataForm.categoryId = selectedCategories[2].id
  getAttrsByCategoryId(Data.dataForm.categoryId) // 请求基本属性
  updatePlatProdCategory({
    firstCat: selectedCategories[0],
    secondCat: selectedCategories[1],
    threeCat: selectedCategories[2]
  },
  true
  )
}

const updatePlatProdCategory = (platProdCategory, selectUpdate) => {
  if (selectUpdate) {
    // 选择更新
    if (platProdCategory.firstCat) {
      prodStore.platProdCategory.firstCat = platProdCategory.firstCat
    }
    if (platProdCategory.secondCat) {
      prodStore.platProdCategory.secondCat = platProdCategory.secondCat
    }
    if (platProdCategory.threeCat) {
      prodStore.platProdCategory.threeCat = platProdCategory.threeCat
    }
    if (platProdCategory.composeType) {
      prodStore.platProdCategory.composeType = platProdCategory.composeType
    }
  } else {
    // 全部更新
    prodStore.platProdCategory = platProdCategory
  }
}

// 选择品牌
const selectBrandRef = ref(null)
const selectBrand = () => {
  Data.visibleBrandPopUp = true
  nextTick(() => {
    selectBrandRef.value.init(null, Data.dataForm.brandId)
  })
}

const refreshSelectBrand = (brands) => {
  if (brands) {
    Data.dataForm.brandId = brands.brandId
    Data.dataForm.brandName = brands.name
  }
}

const getFreightList = () => {
  apiTransport.transportPage().then(data => {
    Data.freightList = data
  })
}

const addOrUpdateRef = ref(null)
const addFreight = () => {
  Data.addOrUpdateVisible = true
  nextTick(() => {
    addOrUpdateRef.value.init()
  })
}

// SkuTable返回数据
const handleChangeData = (data, defaultWarehouse) => {
  Data.skuTableData = data
  const salePrices = []
  const marketPrices = []
  let totalStock = 0
  Data.skuTableData?.forEach((sku) => {
    if (!sku.marketPriceFee) {
      sku.marketPriceFee = 0
    }
    if (sku.stocks) {
      totalStock += Number(sku.stocks) // 库存累加
    }
    if (sku.status === 1) {
      salePrices.push(sku.price) // 售价
      marketPrices.push(sku.marketPriceFee) // 市场价
    }
    if ((!sku.stockPointList || !sku.stockPointList.length)) {
      sku.stockPointList = [{
        stock: 0,
        stockPointId: defaultWarehouse,
        stockPointType: 1,
        type: 0
      }]
    }
  })
  Data.dataForm.priceFee = parseFloat(bigProductTotalAmount(parseFloat(Math.min.apply(null, salePrices)), 100)) // 最低价-售价
  Data.dataForm.marketPriceFee = parseFloat(bigProductTotalAmount(parseFloat(Math.min.apply(null, marketPrices)), 100)) // 最低价-市场价
  Data.dataForm.totalStock = totalStock // 总库存
}

// 精度运算-乘法
const bigProductTotalAmount = (a, b) => {
  return new Big(a).times(b).valueOf()
}

// 下一步
const dataFormRef = ref(null)
const submitFormNext = () => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      const flag = Data.dataForm.spuAttrValues.some(item => item.searchType === 1 && !item.attrValueId)
      if (flag) {
        return ElMessage({
          message: $t('product.prodInfo.basicAttrsEmpty'),
          duration: 1000
        })
      }

      const flag2 = Data.skuTableData.some(item => item.status === 1)
      if (!flag2) {
        return ElMessage({
          message: $t('product.prodInfo.speMustEnabled'),
          duration: 1000
        })
      }

      const flag3 = Data.skuTableData.some(item => !item.skuComboList || item.skuComboList.length === 0)
      if (Data.dataForm.spuMold === 2 && flag3) {
        return ElMessage({
          message: '组合商品规格至少关联一个商品',
          duration: 1000
        })
      }
      emit('nextStep')
    }
  })
}

// 保存
const skuTagRef = ref(null)
const userStore = useUserStore()
const submitForm = Debounce(() => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      const flag = Data.dataForm.spuAttrValues.some(item => item.searchType === 1 && !item.attrValueId)
      if (flag) {
        return ElMessage({
          message: $t('product.prodInfo.basicAttrsEmpty'),
          duration: 1000
        })
      }
      const flag2 = Data.skuTableData.some(item => item.status === 1)
      if (!flag2) {
        return ElMessage({
          message: $t('product.prodInfo.speMustEnabled'),
          duration: 1000
        })
      }
      const flag3 = Data.skuTableData.some(item => !item.skuComboList || item.skuComboList.length === 0)
      if (Data.dataForm.spuMold === 2 && flag3) {
        return ElMessage({
          message: '组合商品规格至少关联一个商品',
          duration: 1000
        })
      }
      // 校验是否含有空规格值
      if (!skuTagRef.value.vaildSkuTag()) {
        return
      }
      Data.dataForm.categoryId = Data.dataForm.categoryId || selectedCategories.value[2].id
      Data.dataForm.supplierId = userStore.tenantId
      // 基本属性处理
      Data.dataForm.spuAttrValues.forEach(item => {
        if (item.attrValues.length > 0) {
          item.attrName = item.attrLangList[0].name
          const arr = item.attrValues.filter(el => el.attrValueId === item.attrValueId)
          item.attrValueName = arr.length > 0 ? arr[0].values[0].value : null
        }
      })
      // sku数据格式转换
      Data.dataForm.skuList = []
      if (prodStore.skuTags.length === 0) {
        Data.dataForm.skuList = [{
          skuLangList: [],
          imgUrl: '',
          marketPriceFee: parseFloat(bigProductTotalAmount(parseFloat(Data.skuTableData[0].marketPriceFee), 100)),
          modelId: Data.skuTableData[0].modelId || '',
          partyCode: Data.skuTableData[0].partyCode,
          priceFee: parseFloat(bigProductTotalAmount(parseFloat(Data.skuTableData[0].price), 100)),
          spuSkuAttrValues: [],
          status: Data.skuTableData[0].status,
          stock: Data.skuTableData[0].stocks,
          stockPointList: Data.skuTableData[0].stockPointList,
          volume: Data.skuTableData[0].volume,
          weight: Data.skuTableData[0].weight,
          stockWarning: Data.skuTableData[0].stockWarning,
          skuId: Data.skuTableData[0].skuId || '',
          skuComboList: Data.skuTableData[0].skuComboList || []
        }]
      } else {
        changeSkuFormat(0, [], '')
      }
      // 修改sku信息添加skuId
      if (Data.skus.length > 0 && Data.dataForm.skuList.length === Data.skus.length) {
        if (!Data.skus[0].spuSkuAttrValues.length && !Data.dataForm.skuList[0].spuSkuAttrValues.length) {
          // 已存在skuId&无属性的情况下，修改sku信息时应带上原本的skuId，避免skuId被更新
          Data.dataForm.skuList[0].skuId = Data.skus[0].skuId
          Data.dataForm.skuList[0].changeStock = parseInt(Data.dataForm.skuList[0].stock) - parseInt(Data.skus[0].stock)
        } else {
          // 有属性且没改变
          const flag = Data.dataForm.skuList.some((item, index) => item.skuLangList[0]?.skuName !== Data.skus[index]?.skuName)
          if (!flag) {
            Data.dataForm.skuList.forEach((item, index) => {
              item.skuId = Data.skus[index].skuId
              item.changeStock = parseInt(item.stock) - parseInt(Data.skus[index].stock)
            })
          }
        }
      }
      // 配送方式
      if (typeof (Data.dataForm.deliveryMode) !== 'string') {
        Data.dataForm.deliveryMode = JSON.stringify(Data.dataForm.deliveryMode)
      }
      // 轮播图首图为主图mainImgUrl
      Data.dataForm.mainImgUrl = (Data.dataForm.imgUrls).split(',')[0]
      Data.dataForm.spuLangList = [
        {
          detail: Data.dataForm.detail,
          lang: 1,
          sellingPoint: Data.dataForm.sellingPoint,
          spuName: Data.dataForm.name
        },
        {
          detail: '',
          lang: 2,
          sellingPoint: '',
          spuName: ''
        }
      ]
      const paramDataForm = JSON.parse(JSON.stringify(Data.dataForm))
      // 运费设置
      paramDataForm.deliveryTemplateId = paramDataForm.tableRate > 0 ? paramDataForm.deliveryTemplateId : paramDataForm.tableRate
      if (paramDataForm.tableRate === -1) {
        paramDataForm.deliveryAmount = new Big(paramDataForm.deliveryAmount || 0).times(100).valueOf()
      } else {
        paramDataForm.deliveryAmount = ''
      }
      // 请求提交表单
      dataFormSubmit(paramDataForm)
    }
  })
}, 1500)

// 处理提交的skuList的数据格式
const changeSkuFormat = (i, spuSkuAttrValues, pic) => {
  if (i >= prodStore.skuTags.length) return
  prodStore.skuTags[i].tagItems.forEach(item => {
    if (i === 0) {
      spuSkuAttrValues = []
      pic = item.pic || ''
    }
    const obj = [{
      attrId: prodStore.skuTags[i].tagId,
      attrName: prodStore.skuTags[i].tagName,
      attrNameEn: prodStore.skuTags[i].tagNameEn,
      attrValueId: item.attrId,
      attrValueName: item.propValue,
      attrValueNameEn: item.propValueEn
    }]
    const values = spuSkuAttrValues.concat(obj)
    if (i < prodStore.skuTags.length - 1) {
      changeSkuFormat(i + 1, values, pic)
    } else {
      Data.dataForm.skuList.push({
        skuLangList: [
          {
            attrs: values.map(item => item.attrName).join(','),
            lang: 1,
            skuName: values.map(item => item.attrValueName).join(' ')
          },
          {
            attrs: values.map(item => item.attrNameEn).join(','),
            lang: 2,
            skuName: values.map(item => item.attrValueNameEn).join(' ')
          }
        ],
        imgUrl: pic,
        marketPriceFee: parseFloat(bigProductTotalAmount(parseFloat(Data.skuTableData[Data.dataForm.skuList.length].marketPriceFee), 100)),
        modelId: Data.skuTableData[Data.dataForm.skuList.length].modelId || '',
        partyCode: Data.skuTableData[Data.dataForm.skuList.length].partyCode,
        priceFee: parseFloat(bigProductTotalAmount(parseFloat(Data.skuTableData[Data.dataForm.skuList.length].price), 100)),
        spuSkuAttrValues: values,
        status: Data.skuTableData[Data.dataForm.skuList.length].status,
        stock: Data.skuTableData[Data.dataForm.skuList.length].stocks,
        stockPointList: Data.skuTableData[Data.dataForm.skuList.length].stockPointList,
        volume: Data.skuTableData[Data.dataForm.skuList.length].volume,
        weight: Data.skuTableData[Data.dataForm.skuList.length].weight,
        stockWarning: Data.skuTableData[Data.dataForm.skuList.length].stockWarning,
        skuId: Data.skuTableData[Data.dataForm.skuList.length].skuId || '',
        skuComboList: Data.skuTableData[Data.dataForm.skuList.length].skuComboList || []
      })
    }
  })
}
const router = useRouter()
// 表单提交
const commonStore = useCommonStore()
const dataFormSubmit = Debounce((dataForm) => {
  const request = Data.dataForm.spuId ? api.update(dataForm) : api.save(dataForm)
  request.then(() => {
    ElMessage({
      message: $t('table.actionSuccess'),
      type: 'success',
      duration: 1000,
      onClose: () => {
        const routeList = commonStore.routeList
        let flag = 0
        routeList.forEach(item => {
          if (item.children) {
            item.children.forEach(el => {
              if (el.path === '/product' && el.children) {
                el.children.forEach(element => {
                  if (element.path === 'list') {
                    flag = 1
                  }
                })
              }
            })
          }
        })
        if (!flag) {
          return ElMessage.error($t('dashboard.notPermissionAccess'))
        }
        router.push({ path: '/product/list' })
      }
    })
  })
}, 1500)

// 根据分类获取基本属性列表
const getAttrsByCategoryId = (categoryId, dataForm) => {
  const param = {
    categoryId
  }
  api.getAttrsByCategoryId(param).then((data) => {
    Data.dataForm.spuAttrValues = data
    if (dataForm) {
      // 基本属性回显
      dataForm.spuAttrValues.forEach((item, index) => {
        if (item.spuAttrValueLangList) {
          if (Data.dataForm.spuAttrValues[index].attrValues.length > 0) {
            Data.dataForm.spuAttrValues[index].attrValueId = item.attrValueId
          } else {
            Data.dataForm.spuAttrValues[index].attrValueName = item.spuAttrValueLangList[0].attrValueName
          }
        }
      })
    }
  })
}

const hasSkuImgChange = (val) => {
  Data.dataForm.hasSkuImg = val
}

const handleCloseBrand = () => {
  Data.dataForm.brandId = ''
  Data.dataForm.brandName = null
}

const onHandleFreight = () => {
  dataForm.value.deliveryAmount = dataForm.value.deliveryAmount < 0.01 ? 0.01 : dataForm.value.deliveryAmount
}

/**
 * 处理输入框数据
 * @param data
 * @param dataFields
 * @param min 最小值
 * @param max 最大值
 */
const handleInputValue = (data, dataFields, min, max) => {
  dataForm.value[dataFields] = checkInput(data)
  if (data || data === 0) {
    // 保留两位小数
    if (data > max) {
      dataForm.value[dataFields] = max
    }
    if (data < min) {
      dataForm.value[dataFields] = min
    }
  }
}
/**
 * 只允许输入正数和小数(保留小数点后两位)
 */
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 updateDetail = (content) => {
  Data.dataForm.detail = content || ''
}

defineExpose({
  init,
  submitFormNext,
  submitForm,
  getAttrsByCategoryId,
  updateDetail
})

/**
 * 触发表单校验
 * @param prop 校验项
 */
const onPropChage = (prop) => {
  if (dataForm.value.imgUrls) {
    dataFormRef.value?.validateField(prop)
  }
}
</script>

<style lang="scss" scoped>
.sypplier-product-components {
  font-size: 14px;
  color: #333;

  .basic,
  .specification,
  .freight {
    .base-box {
      width: 860px;
      background: #F7F8FA;
      border-radius: 2px;
      padding: 20px;
      display: grid;
      gap: 20px 20px;
      grid: repeat(1, auto) / repeat(2, 380px);
    }

    .base-tip {
      font-size: 12px;
      color: #999999;
    }

    .title {
      height: 40px;
      background-color: #f9f9f9;
      line-height: 40px;
      font-size: 16px;
      font-weight: bold;
      padding-left: 20px;
      margin-bottom: 20px;
    }

    .freight-inp{
      width: 175px;
    }

    .platform-type-text {
      font-size: 12px;
      color: #999999;
    }

    .platform-type {
      width: 514px;
      height: 32px;
      line-height: 30px;
      border: 1px solid #E8E9EC;
      border-radius: 2px;
      padding: 0 10px;
      color: #C0C4CC;
      // margin-left: 130px;

    }

    .shop-type {
      display: flex;
      justify-content: space-between;

      .text-box {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 90%;

        .text {
          color: #333;
        }
      }

      .amend {
        cursor: pointer;
        color: #155BD4;
      }
    }

    .hint {
      font-size: 12px;
      line-height: 16px;
      margin-top: 5px;
      color: #999999;
    }

    .brand {
      width: 246px;
      height: 36px;
      border: 1px solid #dcdfe6;
      border-radius: 2px;
      display: flex;
      justify-content: space-between;
      padding: 0 10px;

      .brand-name {
        display: inline-block;
        max-width: 170px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
      }

      .del-brand {
        color: #155bd4;
        vertical-align: middle;
      }

      .del-brand:hover {
        cursor: pointer;
      }

      .select {
        color: #155BD4;
        cursor: pointer;
      }
    }
  }

  .specification {
    margin-top: 30px;
  }

  .freight {
    .freightSelect {
      display: flex;
      align-items: center;

      .flush {
        margin-left: 10px;
        cursor: pointer;
        color: #155BD4;
      }

      .add {
        cursor: pointer;
        color: #155BD4;
      }
    }
  }

  :deep(.w514) {
    width: 514px;
  }

  :deep(.w246) {
    width: 246px;
  }

  :deep(.w160) {
    width: 160px;
  }

  :deep(.inline-block) {
    display: inline-block;
    vertical-align: top;
  }

  :deep(.item) {
    margin-bottom: 0;
    margin-top: 30px;
  }

  :deep(.el-form-item__content) {
    display: block;
  }

}
</style>
