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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <div class="Mall4j mod-prod-list app-container">
    <!-- 1.条件筛选 -->
    <div class="search-bar">
      <el-form
        :inline="true"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <!-- 商品名称 -->
          <el-form-item :label="$t('product.prodName') + '：'">
            <el-input
              v-model="searchForm.spuName"
              :placeholder="$t('product.list.prodNameTips')"
              maxlength="100"
              clearable
            />
          </el-form-item>
          <!-- 商品编码 -->
          <el-form-item :label="$t('product.list.skuCode') + '：'">
            <el-input
              v-model="searchForm.skuCode"
              :placeholder="$t('product.list.skuCodeTips')"
              clearable
            />
          </el-form-item>
          <!-- 商品编码 -->
          <el-form-item :label="$t('product.list.spuCode') + '：'">
            <el-input
              v-model="searchForm.spuCode"
              :placeholder="$t('product.list.spuCodeTips')"
              clearable
            />
          </el-form-item>
          <!-- 商品类型 -->
          <el-form-item label="商品类型：">
            <el-select
              v-model="searchForm.spuMold"
              placeholder="商品类型"
              clearable
            >
              <el-option
                label="普通商品"
                :value="0"
              />
              <el-option
                label="组合商品"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('product.status') + '：'"
          >
            <el-select
              v-model="searchForm.spuStatus"
              :placeholder="$t('product.list.statusTips')"
              clearable
            >
              <el-option
                v-for="item in spuStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!--库存预警-->
          <el-form-item

            :label="$t('product.list.stockWarning') + '：'"
          >
            <el-select
              v-model="searchForm.stockWarning"
              :placeholder="$t('product.list.stockWarningTips')"
              clearable
            >
              <el-option
                label="是"
                :value="1"
              />
              <el-option
                label="否"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item

            :label="$t('product.platforation') + '：'"
          >
            <el-cascader
              v-model="selectedPlatformCategories"
              clearable
              expand-trigger="hover"
              :options="platformCategories"
              :props="platformCategoriesTreeProps"
              change-on-select
              :placeholder="$t('product.list.platforationTips')"
              @change="handlePlatformCategoryChange"
            />
          </el-form-item>
          <!-- 查询按钮 -->
          <div class="btn-row">
            <el-button
              type="primary"
              @click="onSearch(true)"
            >
              {{ $t('table.search') }}
            </el-button>
            <el-button
              plain
              @click="onResetSearch()"
            >
              {{ $t('table.clear') }}
            </el-button>
          </div>
        </div>
      </el-form>
    </div>

    <div class="main-content">
      <!-- 2.发布/展示/处理商品操作 -->
      <div class="operation-bar">
        <el-checkbox
          v-if="pageData.dataList.length"
          v-model="selectedAll"
          :indeterminate="isIndeterminate"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{ $t('product.list.allSelect') }}
        </el-checkbox>
        <span
          v-if="checkedCount"
          class="had-selected-tips"
        >{{ $t('product.list.selectedItem') }} {{ selectedProdList.length }}</span>
        <div class="inline-btn-row">
          <el-button
            v-show="pageData.dataList.length"
            v-permission="['product:spu:soldExcel']"
            plain
            @click="onSoldExcel()"
          >
            {{ $t('product.list.exportProduct') }}
          </el-button>
          <el-button
            v-permission="['product:spu:upload']"
            plain
            @click="uploadSpu()"
          >
            {{ $t('product.importGoods') }}
          </el-button>
          <div
            v-show="pageData.dataList.length"
            v-permission="['product:spu:prodSale','product:spu:prodNotSale','product:spu:batchDelete']"
            style="display:inline-block; margin-left: 10px"
            @click="showBatchSetting=true"
          >
            <el-dropdown
              class="batch-setting-dropdown"
              :hide-on-click="true"
              trigger="click"
              @command="onBatchSetting"
              @visible-change="onVisibleChange"
            >
              <el-button
                plain
              >
                {{ $t('product.list.batchSet') }}
                <el-icon
                  v-if="showBatchSetting"
                  class="el-icon-arrow-down el-icon--right"
                >
                  <ArrowUp />
                </el-icon>
                <el-icon
                  v-else
                  class="el-icon-arrow-down el-icon--right"
                >
                  <ArrowDown />
                </el-icon>
              </el-button>
              <!-- 批量设置功能列表 -->
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-permission="['product:spu:prodSale']"
                    command="1"
                  >
                    {{ $t('product.batchUp') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-permission="['product:spu:prodNotSale']"
                    command="0"
                  >
                    {{ $t('product.batchDown') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-permission="['product:spu:batchDelete']"
                    command="-1"
                  >
                    {{ $t('product.list.batchDelete') }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 商品展示表格 -->
      <div
        ref="closePopoverRef"
        class="table-con"
      >
        <el-table
          ref="prodListTableRef"
          :data="pageData.dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @cell-mouse-enter="onCellMouseEnter"
          @cell-mouse-leave="onCellMouseLeave"
          @selection-change="onSelectSome"
          @sort-change="prodConditionSort"
        >
          <el-table-column
            type="selection"
            align="center"
            width="45"
          />
          <el-table-column
            :label="$t('product.productInfo')"
            width="200"
          >
            <template #default="{ row }">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow
                    :src="row.mainImgUrl"
                    :img-style="{width:'60px',height:'60px'}"
                  />
                </div>
                <div class="table-cell-text">
                  <el-popover
                    placement="top-start"
                    trigger="hover"
                    :content="row.spuName"
                  >
                    <template #reference>
                      <div class="prod-name">
                        {{ row.spuName }}
                      </div>
                    </template>
                  </el-popover>
                  <el-popover
                    placement="bottom"
                    trigger="click"
                    width="200"
                    @show="onGetProdName(row.spuId)"
                    @after-enter="onGetCurrentSpuId(row.spuId, 'prodName')"
                    @hide="onInitProdInf(row)"
                  >
                    <div class="spu-name-input-con">
                      <el-input
                        v-model="currentModifyProdName.spuNameZh"
                        type="textarea"
                        :rows="2"
                        maxlength="100"
                        :placeholder="$t('product.list.prodNameZhTips')"
                      />
                    </div>
                    <div class="popover-bottom">
                      <el-button
                        @click="onClosePopover()"
                      >
                        {{ $t('table.cancel') }}
                      </el-button>
                      <el-button
                        type="primary"
                        @click="onModifyProdName(row)"
                      >
                        {{ $t('table.save') }}
                      </el-button>
                    </div>
                    <template #reference>
                      <el-icon
                        v-show="row.spuId===currentMoveSpuId || (row.spuId===currentClickSpuId && currentShowPopover==='prodName')"
                        v-permission="['product:spu:modifyProdName']"
                      >
                        <EditPen />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.list.supplyPrice')"
            prop="priceFee"
            min-width="120"
            sortable="custom"
          >
            <template #default="{ row }">
              <div class="table-cell-text">
                <span>{{ row.priceFee }}</span>
                <el-popover
                  placement="bottom"
                  trigger="click"
                  width="auto"
                  @show="onGetProdSku(row.spuId)"
                  @after-enter="onGetCurrentSpuId(row.spuId, 'priceFee')"
                  @after-leave="onClearCShowPopoverInf()"
                >
                  <div v-if="currentModifyProdSkuList.length===1">
                    <div class="single-input-number">
                      <el-input-number
                        v-model="currentModifyProdSkuList[0].priceFee"
                        :min="0.01"
                        :max="9999999.99"
                        :step="0.1"
                        :precision="2"
                        controls-position="right"
                      />
                      <div class="popover-bottom">
                        <el-button
                          @click="onClosePopover()"
                        >
                          {{ $t('table.cancel') }}
                        </el-button>
                        <el-button
                          v-permission="['product:spu:modifyProdPrice']"
                          type="primary"
                          @click="onModifyProdPrice(row.spuId, currentModifyProdSkuList)"
                        >
                          {{ $t('table.save') }}
                        </el-button>
                      </div>
                    </div>
                  </div>
                  <div
                    v-if="currentModifyProdSkuList.length>1"
                    class="popover-table-con"
                  >
                    <el-table
                      :data="currentModifyProdSkuList"
                      header-cell-class-name="table-header"
                    >
                      <el-table-column
                        width="200"
                        prop="skuName"
                        :label="$t('product.list.skuName')"
                      />
                      <el-table-column
                        width="150"
                        prop="priceFee"
                        :label="$t('product.list.price')"
                      >
                        <template #default="scope">
                          <el-input-number
                            v-model="scope.row.priceFee"
                            :min="0.01"
                            :max="9999999.99"
                            :step="0.1"
                            :precision="2"
                            style="width:100%"
                            controls-position="right"
                            :disabled="scope.row.status!==1"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="popover-bottom">
                      <el-button
                        @click="onClosePopover()"
                      >
                        {{ $t('table.cancel') }}
                      </el-button>
                      <el-button
                        type="primary"
                        @click="onModifyProdPrice(row.spuId, currentModifyProdSkuList)"
                      >
                        {{ $t('table.save') }}
                      </el-button>
                    </div>
                  </div>
                  <template #reference>
                    <el-icon
                      v-show="row.spuId===currentMoveSpuId || (row.spuId===currentClickSpuId && currentShowPopover==='priceFee')"
                      :ref="`editPriceBtn${row.spuId}`"
                      v-permission="['product:spu:modifyProdPrice']"
                    >
                      <EditPen />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.list.stock')"
            prop="stock"
            sortable="custom"
            min-width="120"
          >
            <template #default="{ row, $index }">
              <div class="table-cell-text">
                <span>{{ row.stock }}</span>
                <el-popover
                  v-if="row.spuMold !== 2"
                  :visible="row.visible"
                  placement="bottom"
                  trigger="click"
                  width="auto"
                  class="popover-box-height"
                  @show="onGetProdSku(row.spuId)"
                  @after-enter="onGetCurrentSpuId(row.spuId, 'prodStock')"
                  @hide="onClearCShowPopoverInf()"
                >
                  <div v-if="currentModifyProdSkuList.length === 1">
                    <div class="single-input-number">
                      <div class="stock-number">
                        <el-input
                          v-model="currentModifyProdSkuList[0].stock"
                          :min="1"
                          :max="9999999"
                          type="number"
                          oninput="value=value.replace(/[^\d]/g,'')"
                          controls-position="right"
                          @blur="onChangeMoldStock(currentModifyProdSkuList[0])"
                        />
                        <div
                          v-if="stockPointInfo.warehouseSize > 1"
                          class="shade"
                          @click="onSetStock(row, currentModifyProdSkuList[0], 0);visibleIndex = $index"
                        />
                      </div>
                      <div class="popover-bottom">
                        <el-button
                          @click="onClosePopover()"
                        >
                          {{ $t('table.cancel') }}
                        </el-button>
                        <el-button
                          v-permission="['product:spu:modifyProdStock']"
                          type="primary"
                          @click="onModifyProdStock(row.spuId, currentModifyProdSkuList)"
                        >
                          {{ $t('table.save') }}
                        </el-button>
                      </div>
                    </div>
                  </div>
                  <div
                    v-if="currentModifyProdSkuList.length > 1"
                    class="popover-table-con"
                  >
                    <el-table
                      :data="currentModifyProdSkuList"
                      header-cell-class-name="table-header"
                    >
                      <el-table-column
                        width="200"
                        prop="skuName"
                        :label="$t('product.list.skuName')"
                      />
                      <el-table-column
                        width="150"
                        prop="stock"
                        :label="$t('product.list.stocks')"
                      >
                        <template #default="scope">
                          <div class="stock-number">
                            <el-input
                              v-model="scope.row.stock"
                              :max="9999999"
                              :min="0"
                              type="number"
                              style="width:100%"
                              oninput="value=value.replace(/[^\d]/g,'')"
                              controls-position="right"
                              :disabled="scope.row.status!==1"
                              @blur="onChangeMoldStock(scope.row)"
                            />
                            <div
                              v-if="scope.row.status===1 && stockPointInfo.warehouseSize > 1"
                              class="shade"
                              @click="onSetStock(row, scope.row, scope.$index);visibleIndex = $index"
                            />
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="popover-bottom">
                      <el-button
                        @click="onClosePopover()"
                      >
                        {{ $t('table.cancel') }}
                      </el-button>
                      <el-button
                        type="primary"
                        @click="onModifyProdStock(row.spuId, currentModifyProdSkuList)"
                      >
                        {{ $t('table.save') }}
                      </el-button>
                    </div>
                  </div>
                  <template #reference>
                    <el-icon
                      v-show="row.spuId===currentMoveSpuId || (row.spuId===currentClickSpuId && currentShowPopover==='prodStock')"
                      :ref="`editStockBtn${row.spuId}`"
                      v-permission="['product:spu:modifyProdStock']"
                    >
                      <EditPen />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.status')"
            prop="spuStatus"
          >
            <template #default="{ row }">
              <span>{{ spuStatusList[row.spuStatus] ? spuStatusList[row.spuStatus].label : '' }}</span>
            </template>
          </el-table-column>
          <!-- SPU编码 -->
          <el-table-column
            :label="$t('product.list.spuCode')"
            prop="spuCode"
          >
            <template #default="scope">
              <span
                v-if="scope.row.spuCode"
                class="table-cell-text"
              >
                {{ scope.row.spuCode }}
              </span>
              <span
                v-else
                class="table-cell-text"
              >-</span>
            </template>
          </el-table-column>
          <!-- 平台类目 -->
          <el-table-column
            :label="$t('product.platforation')"
            prop="categoryNames"
          />
          <!-- 品牌 -->
          <el-table-column
            :label="$t('product.list.brand')"
            prop="brandName"
          >
            <template #default="scope">
              <span
                v-if="scope.row.brandName"
                class="table-cell-text"
              >
                {{ scope.row.brandName }}
              </span>
              <span
                v-else
                class="table-cell-text"
              >-</span>
            </template>
          </el-table-column>

          <el-table-column
            label="商品类型"
            prop="spuType"
            width="auto"
          >
            <template #default="{ row }">
              <div>
                {{ row.spuMold === 2 ? '组合商品' : '普通商品' }}
              </div>
            </template>
          </el-table-column>
          <!-- 序号 -->
          <el-table-column
            class="table-item"
            prop="seq"
            :label="$t('table.id')"
            sortable="custom"
          >
            <template #default="{ row }">
              <div class="table-cell-text">
                <span>{{ row.exhibitionSeq }}</span>
                <el-popover
                  placement="bottom"
                  trigger="click"
                  @after-enter="onGetCurrentSpuId(row.spuId, 'seq')"
                  @hide="onInitProdInf(row)"
                >
                  <el-input
                    v-model="row.seq"
                    type="number"
                    :max="32767"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    controls-position="right"
                  />
                  <div class="popover-bottom">
                    <el-button
                      @click="onClosePopover()"
                    >
                      {{ $t('table.cancel') }}
                    </el-button>
                    <el-button
                      type="primary"
                      @click="onModifySeq(row)"
                    >
                      {{ $t('table.save') }}
                    </el-button>
                  </div>
                  <template #reference>
                    <el-icon
                      v-show="row.spuId===currentMoveSpuId || (row.spuId===currentClickSpuId && currentShowPopover==='seq')"
                      v-permission="['product:spu:modifySeq']"
                    >
                      <EditPen />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('table.actions')"
            width="250"
          >
            <template #default="{ row }">
              <div class="table-btn-con">
                <el-button
                  v-permission="['product:spu:edit']"
                  link
                  type="primary"
                  @click="onAddOrUpdate(row.spuId)"
                >
                  {{ $t('table.edit') }}
                </el-button>
                <el-button
                  v-show="row.spuStatus === 0"
                  v-permission="['product:spu:prodSale']"
                  link
                  type="primary"
                  @click="onProdSale(row.spuId)"
                >
                  {{ $t('product.list.onShelf') }}
                </el-button>
                <el-button
                  v-show="row.spuStatus === 1"
                  v-permission="['product:spu:prodNotSale']"
                  link
                  type="primary"
                  @click="onProdNotSale(row.spuId)"
                >
                  {{ $t('product.list.offShelf') }}
                </el-button>
                <el-button
                  v-show="row.spuStatus === 2"
                  v-permission="['product:spu:applyOnline']"
                  link
                  type="primary"
                  @click="onOfflineManageHandle(row)"
                >
                  {{ $t('product.list.applyOnline') }}
                </el-button>
                <el-button
                  v-show="row.spuStatus === 3"
                  v-permission="['product:spu:viewAudit']"
                  link
                  type="primary"
                  @click="onOfflineManageHandle(row)"
                >
                  {{ $t('product.list.reviewed') }}
                </el-button>
                <el-button
                  v-permission="['product:spu:delete']"
                  link
                  type="primary"
                  @click="onDelete(row.spuId)"
                >
                  {{ $t('table.delete') }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        v-if="pageData.dataList.length"
        class="operation-bar bottom-bar"
      >
        <div class="inline-btn-row">
          <!-- 上架按钮 -->
          <el-button
            v-if="prodStatusRadio !== 0 && prodStatusRadio !== 1 && prodStatusRadio !== 2"
            @click="changeProdStatus('onTheShelf')"
          >
            {{ $t('product.list.onShelf') }}
          </el-button>
          <!-- 下架按钮 -->
          <el-button
            v-if="prodStatusRadio!==0 && prodStatusRadio!==3"
            @click="changeProdStatus('offTheShelf')"
          >
            {{ $t('product.list.offShelf') }}
          </el-button>
        </div>
      </div>
    </div>
    <!-- 分页条 -->
    <pagination
      v-show="pageData.total > 0"
      v-model:page="searchForm.pageNum"
      v-model:limit="searchForm.pageSize"
      style="text-align: right"
      :total="pageData.total"
      @pagination="getPageData"
    />
    <!-- 下架管理 -->
    <offline-manage
      v-if="operateDialogVisible"
      ref="offlineDataRef"
      @rereapply-data-submit="onSubmitApply"
    />
    <SpuUpload
      v-if="uploadVisible"
      ref="spuUploadRef"
      @refresh-data-list="getWaitingConsignmentExcel"
    />

    <!-- 库存设置 -->
    <stock-update
      v-if="prodinventoryVisible"
      ref="prodInventoryRef"
      @set-stock-callback="onSetStockCallback"
      @close="onClose"
    />
  </div>
</template>

<script setup>
import * as api from '@/api/product/list'
import * as categoryApi from '@/api/product/category'
import { getStockPointInfo } from '@/api/stock/stock.js'
import SpuUpload from './spu-upload.vue'
import { treeDataTranslate } from '@/utils'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'

let tempSearchForm = null
const uploadVisible = ref(false)
const isSubmit = ref(false)
const searchForm = reactive({
  pageSize: 10,
  pageNum: 1,
  spuName: '',
  spuStatus: '',
  skuCode: '',
  spuCode: '',
  stockWarning: '',
  spuMold: null
})
const selectedPlatformCategories = ref([])
const platformCategories = ref([]) // 平台分类
const platformCategoriesTreeProps = reactive({
  value: 'categoryId',
  label: 'name',
  checkStrictly: true
})
const prodStatusRadio = ref(0)
const currentMoveSpuId = ref('') // 移入项的spuId
const currentClickSpuId = ref('') // 点击项的spuId
const currentShowPopover = ref('') // 当前展示的弹窗
// 多选
const selectedAll = ref(false)
const isIndeterminate = ref(false)
const checkedCount = ref(0)
const selectedProdList = ref([]) // 被选中的商品列表
// 查询的参数
const searchParam = ref({})
// 返回参数
const pageData = ref({
  dataList: [], // 返回的列表
  total: 0, // 一共多少条数据
  pages: 0 // 一共多少页
})
// loading
const pageLoading = ref(true)
const currentModifyProdSkuList = ref([]) // 当前准备修改的商品的规格列表
const currentModifyProdName = reactive({ spuNameZh: null, spuNameEn: null }) // 当前准备修改的商品的规格列表
const router = useRouter()
const currentSpuId = ref(null) // 商品id
const operateDialogVisible = ref(false) // 操作对话框
const editItem = ref('') // 编辑项的ref值
const showBatchSetting = ref(false)
const spuStatusList = computed(() => {
  return [
    {
      value: 0,
      label: $t('product.list.offShelf')
    },
    {
      value: 1,
      label: $t('product.list.onShelf')
    },
    {
      value: 2,
      label: $t('product.list.illegalOffShelf')
    },
    {
      value: 3,
      label: $t('product.list.illegalOffReviewed')
    },
    {
      value: 4,
      label: $t('product.list.reviewed')
    }
  ]
})

const { query } = useRoute()
onMounted(() => {
  isSubmit.value = false
  searchForm.spuName = query.spuName ? query.spuName : searchForm.spuName
  if (query.spuStatus) {
    searchForm.spuStatus = parseInt(query.spuStatus)
    searchForm.spuStatus = parseInt(query.spuStatus)
  }
  if (query.stockWarning) {
    searchForm.stockWarning = parseInt(query.stockWarning)
    searchForm.stockWarning = parseInt(query.stockWarning)
  }
  getPageData()
  getPlatformCategories() // 平台分类
  onGetStockPointInfo()
})

// 条件搜索
const onSearch = (newData = false) => {
  loadSearchForm()
  getPageData(newData)
}
const loadSearchForm = () => {
  const dataType = parseInt(prodStatusRadio.value)
  searchForm.pageNum = 1
  searchForm.spuName = searchForm.spuName || undefined
  // 平台一级分类id
  searchForm.primaryCategoryId = searchForm.primaryCategoryId || undefined
  // 平台二级分类id
  searchForm.secondaryCategoryId = searchForm.secondaryCategoryId || undefined
  // 平台三级分类id
  searchForm.categoryId = searchForm.categoryId || undefined
  searchForm.isCompose = searchForm.currentyuPreSaleStatus === '' ? undefined : searchForm.currentyuPreSaleStatus
  searchForm.dataType = dataType
  searchForm.sort = searchForm.sort || undefined
}

const stockPointInfo = ref({})
// 获取库存点信息
const onGetStockPointInfo = () => {
  getStockPointInfo().then((res) => {
    stockPointInfo.value = res
  })
}

/**
 * 获取商品列表
 */
const getPageData = (newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = { ...searchForm }
  } else {
    tempSearchForm.pageNum = searchForm.pageNum
    tempSearchForm.pageSize = searchForm.pageSize
  }
  if (tempSearchForm.pageNum > 1 && pageData.value.dataList.length === 1) {
    tempSearchForm.pageNum--
  }
  pageLoading.value = true
  uploadVisible.value = false
  tempSearchForm.keyword = tempSearchForm.spuName
  api.page(tempSearchForm).then(res => {
    res.list.forEach(item => {
      item.showSpuName = item.spuName
      item.exhibitionSeq = item.seq
      item.isSelected = false
      item.priceFee = new Big(item.priceFee).div(100).toFixed(2)
      item.marketPriceFee = new Big(item.marketPriceFee).div(100).toFixed(2)
    })
    pageData.value.dataList = res.list
    pageData.value.pages = res.pages
    pageData.value.total = res.total
    pageLoading.value = false
  }).catch(() => {
    pageLoading.value = false
  })
  selectedAll.value = false
  isIndeterminate.value = false
  selectedProdList.value = []
  checkedCount.value = 0
}
/**
 * 获取平台分类
 */
const getPlatformCategories = () => {
  pageLoading.value = true
  categoryApi.getMySigningCategoryList().then(pageData => {
    platformCategories.value = treeDataTranslate(pageData, 'categoryId', 'parentId')
    pageLoading.value = false
  }).catch(() => {
    pageLoading.value = false
  })
}
/**
 * 监听平台分类选择变化
 */
const handlePlatformCategoryChange = (val) => {
  searchForm.primaryCategoryId = undefined
  searchForm.secondaryCategoryId = undefined
  searchForm.categoryId = undefined
  if (val && val.length === 1) { // 长度为1，表明当前选择的是一级分类（点击了一级分类）
    searchForm.primaryCategoryId = val[0] // 平台一级分类id
  } else if (val && val.length === 2) { // 长度为2，表明当前选择的是二级分类（点击了二级分类）
    searchForm.secondaryCategoryId = val[1] // 平台二级分类id
  } else if (val && val.length === 3) { // 长度为3，表明当前选择的是三级分类（点击了三级分类）
    searchForm.categoryId = val[2] // 平台三级分类id
  }
}
const commonStore = useCommonStore()
// 跳转发布商品页
const onAddOrUpdate = (spuId) => {
  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 === 'prod-info') {
              flag = 1
            }
          })
        }
      })
    }
  })
  if (!flag) {
    return ElMessage.error($t('dashboard.notPermissionAccess'))
  }
  if (spuId === -1) {
    router.push({ path: '/product/prod-info' })
  } else {
    let query = {}
    spuId && (query = { spuId })
    router.push({
      path: '/product/prod-info',
      query
    })
  }
}
// 导出excel
const onSoldExcel = () => {
  loadSearchForm()
  if (pageData.value.total === 0) {
    ElMessage({
      message: $t('product.list.noProductExport'),
      duration: 1500
    })
    return
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true

  const dataType = parseInt(prodStatusRadio.value)
  searchParam.value = {
    name: searchForm.spuName || undefined,
    primaryCategoryId: searchForm.primaryCategoryId || undefined, // 平台一级分类id
    secondaryCategoryId: searchForm.secondaryCategoryId || undefined, // 平台二级分类id
    categoryId: searchForm.categoryId || undefined, // 平台三级分类id
    isCompose: searchForm.currentyuPreSaleStatus === '' ? undefined : searchForm.currentyuPreSaleStatus,
    dataType,
    status: searchForm.spuStatus
  }

  api.soldExcel({ ...searchParam.value }).then((data) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    // var blob = data
    const fileName = `${$t('order.order.product')}.xlsx`
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
    isSubmit.value = false
  }).catch((e) => {
    ElMessage.error(e)
    isSubmit.value = false
  })
}
const spuUploadRef = ref(null)
const uploadSpu = () => {
  uploadVisible.value = true
  nextTick(() => {
    spuUploadRef.value.init()
  })
}
const getWaitingConsignmentExcel = () => {
  getPageData()
}

/**
 * 监听表格选中
 */
const onSelectSome = (val) => {
  selectedProdList.value = val
  checkedCount.value = val.length
  selectedAll.value = val.length === pageData.value.dataList.length
}

const prodListTableRef = ref()
/**
 * 全选按钮
 */
const onSelectAll = () => {
  selectedAll.value = prodListTableRef.value.getSelectionRows().length < pageData.value.dataList.length
  prodListTableRef.value.toggleAllSelection()
}

/**
 * 条件排序
 * priceFee:当前价       5-正序 4-倒序
 * stock:库存            11-正序 10-倒序
 * seq:序号              13-正序 12-倒序
 * marketPriceFee:市场价 8-正序 7-倒序
 * actualSoldNum:实际销量      18-正序 17-倒序
 */
const prodConditionSort = (data) => {
  const { order, prop: sortType } = data
  let sort = null
  searchForm.pageNum = 1
  searchForm.pageSize = 10
  if (sortType === 'priceFee') {
    sort = order ? order === 'ascending' ? 5 : 4 : null
  } else if (sortType === 'stock') {
    sort = order ? order === 'ascending' ? 11 : 10 : null
  } else if (sortType === 'spuStatus') {
    sort = order ? order === 'ascending' ? 24 : 23 : null
  } else if (sortType === 'spuCode') {
    sort = order ? order === 'ascending' ? 22 : 21 : null
  } else if (sortType === 'seq') {
    sort = order ? order === 'ascending' ? 13 : 12 : null
  }
  searchForm.sort = sort
  getPageData(true)
}

// 改变商品状态
// onTheShelf:上架
// offTheShelf:下架
const changeProdStatus = (status) => {
  // 如果没选商品，提示选择商品
  if (selectedProdList.value.length <= 0) {
    ElMessage({
      message: $t('product.list.selectProductTips'),
      type: 'warning'
    })
    return
  }

  if (status === 'onTheShelf') {
    onProdSale(selectedProdList.value)
  } else if (status === 'offTheShelf') {
    onProdNotSale(selectedProdList.value)
  }
}
// 商品上架
const onProdSale = (spuIdOrSpuIds) => {
  // 是否操作单个商品
  const isSingle = typeof (spuIdOrSpuIds) === 'number'
  const param = {
    status: 1,
    spuId: isSingle ? spuIdOrSpuIds : undefined,
    spuIds: isSingle ? undefined : spuIdOrSpuIds.map(item => { return item.spuId })
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.updateProdStatus(param).then(() => {
    ElMessage({
      message: $t('product.list.productOnSuccessTips'),
      type: 'success',
      duration: 1500,
      onClose: () => getPageData()
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}
// 商品下架
const onProdNotSale = (spuIdOrSpuIds) => {
  // 是否操作单个商品
  const isSingle = typeof (spuIdOrSpuIds) === 'number'
  const prodList = pageData.value.dataList.filter(item => {
    return item.spuStatus === 0
  })
  let flag = 0
  for (let i = 0; i < prodList.length; i++) {
    for (let j = 0; j < spuIdOrSpuIds.length; j++) {
      if (spuIdOrSpuIds[j].spuId === prodList[i].spuId) {
        flag = 1
        break
      }
    }
    if (flag) {
      break
    }
  }
  if (flag) {
    ElMessage.error($t('product.list.noSelectProductTips'))
    return
  }
  const param = {
    status: 0,
    spuId: isSingle ? spuIdOrSpuIds : undefined,
    spuIds: isSingle ? undefined : spuIdOrSpuIds.map(item => { return item.spuId })
  }
  if (isSubmit.value) {
    return
  }
  ElMessageBox.confirm($t('order.order.offlineTip'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    isSubmit.value = true
    api.updateProdStatus(param).then(() => {
      ElMessage({
        message: $t('product.list.productOffSuccessTips'),
        type: 'success',
        duration: 1500,
        onClose: () => getPageData()
      })
      isSubmit.value = false
    }).catch(() => {
      isSubmit.value = false
    })
  }).catch(() => { })
}

/**
 * 商品违规下架操作
 */
const onOfflineManageHandle = (row) => {
  operateDialogVisible.value = true
  currentSpuId.value = row.spuId
  onGetOfflineDetailByProdId(row.spuId)
}

const offlineDataRef = ref(null)
/**
 * 获取最新下线商品的事件
 */
const onGetOfflineDetailByProdId = (spuId) => {
  api.getOfflineHandleEvent(spuId).then((data) => {
    nextTick(() => {
      offlineDataRef.value?.init(data)
    })
  })
}

/**
 * 提交上架申请
 */
const onSubmitApply = (data) => {
  const param = {
    handleId: currentSpuId.value,
    eventId: data.eventId,
    reapplyReason: data.reapplyReason // 申请理由
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.auditApply(param).then(() => {
    operateDialogVisible.value = false
    ElMessage({
      message: $t('table.actionSuccess'),
      type: 'success',
      duration: 1000,
      onClose: () => getPageData()
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}

// 商品删除
const onDelete = (spuId) => {
  if (isSubmit.value) {
    return
  }
  ElMessageBox.confirm($t('order.order.deleteTip'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    isSubmit.value = true
    api.deleteById(spuId).then(() => {
      ElMessage({
        message: $t('table.delSuccess'),
        type: 'success',
        duration: 1500,
        onClose: () => getPageData()
      })
      isSubmit.value = false
    }).catch(() => {
      isSubmit.value = false
    })
  }).catch(() => { })
}

/**
 * 鼠标移入单元格
 */
const onCellMouseEnter = (row) => {
  currentMoveSpuId.value = row.spuId
}
/**
 * 鼠标移出单元格
 */
const onCellMouseLeave = () => {
  currentMoveSpuId.value = ''
}

// 获取弹出弹窗项信息
const onGetCurrentSpuId = (spuId, currentShowPopoverVal) => {
  currentClickSpuId.value = spuId
  currentShowPopover.value = currentShowPopoverVal
}

// 清空选中项弹窗信息
const onClearCShowPopoverInf = () => {
  editItem.value = ''
  currentClickSpuId.value = ''
  currentShowPopover.value = ''
}

/**
 * 获取商品sku列表
 */
const onGetProdSku = (spuId) => {
  currentModifyProdSkuList.value.splice(0, currentModifyProdSkuList.length)
  api.get(spuId).then(data => {
    currentModifyProdSkuList.value = data.skus
    currentModifyProdSkuList.value.forEach(item => {
      item.originalStock = item.stock
      item.priceFee = parseFloat(new Big(item.priceFee).div(100).toFixed(2))
      item.oldPriceFee = item.priceFee
      item.marketPriceFee = parseFloat(new Big(item.marketPriceFee).div(100).toFixed(2))
    })
  })
}

/**
 * 获取商品名称列表
 */
const onGetProdName = (spuId) => {
  api.get(spuId).then(data => {
    data.spuLangList.forEach(spuLang => {
      if (spuLang.lang === 1) {
        currentModifyProdName.spuNameZh = spuLang.spuName
        currentModifyProdName.spuNameZhOld = spuLang.spuName
      } else {
        currentModifyProdName.spuNameEn = spuLang.spuName
        currentModifyProdName.spuNameEnOld = spuLang.spuName
      }
    })
  })
}

// 关闭弹窗后,初始化数据
const onInitProdInf = (row) => {
  row.spuName = row.showSpuName
  row.seq = row.exhibitionSeq
  onClearCShowPopoverInf()
}

const closePopoverRef = ref(null)
// 关闭popover弹窗
const onClosePopover = () => {
  closePopoverRef.value.click()
}

// 修改商品名称
const onModifyProdName = (row) => {
  const nameObject = currentModifyProdName
  if (nameObject.spuNameZh.trim() === '') {
    ElMessage({
      message: $t('product.list.prodNameZhTips'),
      type: 'warning'
    })
    return
  } else if (nameObject.spuNameZh === nameObject.spuNameZhOld && nameObject.spuNameEn === nameObject.spuNameEnOld) {
    onClosePopover()
    return
  }
  const spuLangList = [{ lang: 1, spuName: nameObject.spuNameZh }]
  if (nameObject.spuNameEn) {
    spuLangList.push({ lang: 2, spuName: nameObject.spuNameEn })
  }
  const param = {
    spuId: row.spuId,
    spuLangList
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.updatePartProdStatus({ ...param }).then(() => {
    ElMessage({
      message: $t('table.saveSuccess'),
      type: 'success',
      duration: 2000,
      onClose: () => {
        getPageData()
        onClosePopover()
      }
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}

// 修改商品价格
const onModifyProdPrice = (spuId, skus) => {
  const skuList = []
  let isChangePriceFee = false
  let minPriceFee = 0
  // 判断是否价格有变动,没有变动不更新价格,关闭弹窗即可
  for (let i = 0; i < skus.length; i++) {
    if (skus[i].oldPriceFee !== skus[i].priceFee) {
      isChangePriceFee = true
      break
    }
  }

  if (isChangePriceFee === false) {
    onClosePopover()
    return
  }
  // 把需要传递的参数,单独取出来
  for (let i = 0; i < skus.length; i++) {
    if (skus[i].priceFee === '') {
      ElMessage({
        message: $t('product.list.priceFeeTips'),
        type: 'warning'
      })
      return
    } else if (parseFloat(skus[i].priceFee) < 0.01) {
      ElMessage({
        message: $t('product.list.minPriceFee'),
        type: 'warning'
      })
      return
    } else {
      skuList.push({
        priceFee: accuracyCount(skus[i].priceFee, 100, 2),
        skuId: skus[i].skuId
      })
    }
  }
  // 获取多种规格下的最小价格
  minPriceFee = skuList[0].priceFee
  for (let i = 1; i < skuList.length; i++) {
    if (minPriceFee > skuList[i].priceFee) {
      minPriceFee = skuList[i].priceFee
    }
  }
  const param = {
    spuId,
    priceFee: minPriceFee,
    skuList
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.updatePartProdStatus({ ...param }).then(() => {
    ElMessage({
      message: $t('table.saveSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getPageData()
        onClosePopover()
      }
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}

// 修改规格库存（虚拟商品/无库存点时）
const onChangeMoldStock = (row) => {
  if (stockPointInfo.value.warehouseSize === 1) {
    row.stock = row.stock ? Number(row.stock) : 0
    row.stockPointList[0].changeStock = row.stock - (row.stockPointList[0].stock - (row.stockPointList[0].changeStock || 0))
    row.stockPointList[0].stock = row.stock || 0
  }
}

// 修改商品库存
const onModifyProdStock = (spuId, skus) => {
  const skuList = []
  let totalChangeStock = 0
  for (let i = 0; i < skus.length; i++) {
    let changeStock = 0
    if (skus[i].stock === '' || skus[i].stock === undefined) {
      ElMessage({
        message: $t('product.list.stockTips'),
        type: 'warning'
      })
      return
    } else {
      changeStock = parseInt(skus[i].stock - skus[i].originalStock)
      totalChangeStock += changeStock
      skuList.push({
        changeStock,
        skuId: skus[i].skuId,
        stockPointList: skus[i].stockPointList
      })
    }
  }
  // 如果库存没有发生改变,就不更新库存,只关闭弹窗
  let skuChange = false

  for (let skuIndex = 0; skuIndex < skuList.length; skuIndex++) {
    if (skuList[skuIndex].changeStock !== 0) {
      skuChange = true
      break
    }
    for (let stockPointIndex = 0; stockPointIndex < skuList[skuIndex].stockPointList.length; stockPointIndex++) {
      if (skuList[skuIndex].stockPointList[stockPointIndex].changeStock && skuList[skuIndex].stockPointList[stockPointIndex].changeStock !== 0) {
        skuChange = true
        break
      }
    }
    if (skuChange) {
      break
    }
  }
  if (!skuChange) {
    onClosePopover()
    return
  }
  const param = {
    spuId,
    changeStock: totalChangeStock,
    skuList
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.updatePartProdStatus({ ...param }).then(() => {
    ElMessage({
      message: $t('table.saveSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getPageData()
        onClosePopover()
      }
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}
// 修改序号
const onModifySeq = (scope) => {
  if (scope.seq === '') {
    ElMessage({
      message: $t('product.list.seqTips'),
      type: 'warning'
    })
    return
  } else if (scope.exhibitionSeq === scope.seq) {
    onClosePopover()
    return
  } else if (scope.seq > 32767) {
    scope.seq = 32767
  }
  const param = {
    spuId: scope.spuId,
    seq: scope.seq
  }
  if (isSubmit.value) {
    return
  }
  isSubmit.value = true
  api.updatePartProdStatus({ ...param }).then(() => {
    ElMessage({
      message: $t('table.saveSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getPageData()
        onClosePopover()
      }
    })
    isSubmit.value = false
  }).catch(() => {
    isSubmit.value = false
  })
}
/**
 * 精度运算
 * @param {Number} a:第一个计算数(例如:被除数/被减数)
 * @param {Number} b:第二个计算数(例如:除数/减数)
 * @param {Number} countMode:计算方式(0:加 1:减 2:乘 3:除)
 */
const accuracyCount = (a, b, countMode) => {
  if (!a && a !== 0) {
    return null
  }
  let finalResult = 0
  if (countMode === 0) {
    finalResult = new Big(a).plus(b).valueOf()
  } else if (countMode === 1) {
    finalResult = new Big(a).minus(b).valueOf()
  } else if (countMode === 2) {
    finalResult = new Big(a).times(b).valueOf()
  } else if (countMode === 3) {
    finalResult = new Big(a).div(b).valueOf()
  } else {
    return
  }
  return parseInt(finalResult)
}
/**
 * 清空
 */
const onResetSearch = () => {
  searchForm.primaryCategoryId = ''
  searchForm.secondaryCategoryId = ''
  searchForm.categoryId = ''
  searchForm.spuName = ''
  searchForm.skuCode = ''
  searchForm.spuCode = ''
  searchForm.spuStatus = ''
  searchForm.stockWarning = ''
  searchForm.spuMold = null
  selectedPlatformCategories.value = []
}
const onBatchSetting = (command) => {
  const commands = Number(command)
  if (!selectedProdList.value.length) {
    ElMessage.warning($t('product.list.selectProductTips'))
    return
  }
  if (commands === 1) {
    changeProdStatus('onTheShelf')
  } else if (commands === 0) {
    changeProdStatus('offTheShelf')
  } else {
    onDelete(selectedProdList.value.map(item => item.spuId))
  }
}
/**
 * 批量设置菜单显隐
 */
const onVisibleChange = (val) => {
  showBatchSetting.value = val
}

const prodinventoryVisible = ref(false)
const prodInventoryRef = ref(null)
const onSetStock = (listValue, row, index) => {
  listValue.visible = true
  prodinventoryVisible.value = true
  nextTick(() => {
    prodInventoryRef.value.init(row, index)
  })
}

// 修改库存弹窗回调
const onSetStockCallback = (res, sum, index) => {
  currentModifyProdSkuList.value[index].stock = sum
  currentModifyProdSkuList.value[index].stockPointList = res
}
const visibleIndex = ref(undefined)
// 修改库存弹窗关闭执行
const onClose = () => {
  pageData.value.dataList[visibleIndex.value].visible = undefined
}
</script>

<style lang="scss" scoped>
.table-btn-con {
  display: flex;
  flex-wrap: wrap;
}
.mod-prod-list {
  // 1.筛选条件搜索
  .search-bar {
    padding: 20px;
    background: #f9f9f9;
    :deep(.el-input__wrapper){
      width: 197px;
    }
  }
  .main-content {
    .operation-bar {
      .had-selected-tips {
        font-size: 12px;
        margin-right: 10px;
        color: #155bd4;
      }
      .all-check-btn {
        margin: 0 15px;
      }
      .inline-btn-row {
        display: inline-flex;
      }
    }
    .operation-bar.bottom-bar {
      margin-top: 20px;
      margin-bottom: 0;
    }
    .table-con {
      .table-cell-con {
        .table-cell-text {
          display: flex;
          justify-content: space-between;
          .prod-name {
            text-overflow: ellipsis;
            -o-text-overflow: ellipsis;
            word-break: break-word;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }
      }
      .table-cell-text {
        display: flex;
        align-items: center;
        :deep(.el-icon) {
          margin-left: 5px;
          cursor: pointer;
        }
      }
    }
  }
}

.single-input-number,
.popover-table-con {
  .stock-number {
    position: relative;
    .shade {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      cursor: pointer;
    }
  }
}
.popover-table-con {
  max-height: 400px;
  overflow-y: auto;
}
.spu-name-input-con {
  display: flex;
}
.popover-bottom {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
