<!-- 商品中心 - 商品列表  -->

<template>
  <!-- 列表 -->
  <ContentWrap style="" class="container">
    <div class="search" v-if="!userId">
      <!-- 	左侧的 -->
      <el-tabs
        v-model="queryParams.tabType"
        @tab-click="handleTabClick"
        class="parent-tabs"
        v-if="!mobile"
      >
        <el-tab-pane
          v-for="item in tabsData"
          :key="item.type"
          :label="item.name + '(' + item.count + ')'"
          :name="item.type"
        />
      </el-tabs>
      <div style="text-align: right" class="search-input">
        <el-input
          v-model="queryParams.name"
          placeholder="商品名称"
          @keyup.enter="handleQuery"
          class="!w-240px"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleQuery" style="cursor: pointer">
              <Search />
            </el-icon>
          </template>

          <template #append>
            <el-button :icon="Operation" @click="showSearchMore" />
          </template>
        </el-input>

        <!-- <el-button v-hasPermi="['product:spu:create']" @click="openForm('create', '', 0)" class="ml-5px"
					v-if="!mobile && !isDetail && !merchantId">
					<Icon class="mr-5px " icon="ep:plus" />
					新增
				</el-button> -->
      </div>
    </div>
    <div class="searchMore" v-show="searchMoreShow">
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="80px"
      >
        <el-form-item label="店铺名称" v-if="!merchantId && !userId">
          <el-select v-model="queryParams.shopId" placeholder="请选择" filterable>
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            v-model="queryParams.categoryId"
            :options="categoryList"
            :props="defaultProps"
            clearable
            filterable
            placeholder="请选择商品分类"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="">
          <el-select v-model="queryParams.tabType" placeholder="全部">
            <el-option
              v-for="dict in tabsData"
              :key="dict.type"
              :label="dict.name"
              :value="dict.type"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            style="margin-right: unset; width: auto !important"
            v-model="queryParams.createTime"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            end-placeholder="结束日期"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-row class="pb-20px flex justify-end">
          
          <el-button @click="hideSearchMore"> 收起 </el-button>
          <el-button @click="resetQuery"> 重置 </el-button>
          <el-button @click="handleQuery" plain type="primary">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
        </el-row>
      </el-form>
    </div>

    <el-row>
      <el-col
        v-for="(o, index) in list"
        class="card"
        :key="index"
        :span="7"
        :xl="7"
        :lg="7"
        :md="7"
        :sm="24"
        :xs="24"
        @mouseover="handleMouseOver(index)"
        @mouseout="handleMouseOut(index)"
      >
        <el-card
          @click="openDetail('view', o, ProductSpuStatusEnum.RECYCLE.status, queryParams.tabType)"
        >
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 5px;
            "
          >
            <p
              style="
                width: 100%;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
                font-size: 16px;
                color: #000;
              "
              :title="o.name"
              >{{ o.name }}
            </p>
            <!-- 20240527注释 隐藏操作 -->
            <div
              @click.stop="
                openForm('update', o, ProductSpuStatusEnum.RECYCLE.status, queryParams.tabType)
              "
              v-show="o.showSetting && !mobile && !merchantId && !userId"
              class="setting"
            >
              <el-icon size="20" color="rgb(220 223 231)">
                <Setting />
              </el-icon>
            </div>
          </div>
          <ImageCard :url="o.picUrl" :width="178" :height="100">
            <template #label>
              <p
                >{{ o.spuPayType == 2 ? '佣金:' : '¥' }}
                {{
                  o.highPrecision ? (o.highPrecisionPrice / 100).toFixed(6) : fenToYuan(o.price)
                }}</p
              >
              <p>销量:{{ o.salesCount }}</p>
              <p>库存:{{ o.stock }}</p>
              <p>状态:{{ !o.checkStatus ? '审核中' : o.status == 1 ? '上架' : '下架' }}</p>
            </template>
          </ImageCard>
        </el-card>
      </el-col>
    </el-row>
    <div v-if="list.length == 0">
      <p style="text-align: center; margin-top: 100px">暂无商品</p>
    </div>

    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
    <!-- 表单弹窗：添加/修改 -->
    <SpuIndex ref="formRef" @success="getList" />
  </ContentWrap>
</template>

<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import { Setting, Search, Operation } from '@element-plus/icons-vue'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import ImageCard from '@/components/ImageCard/ImageCard.vue'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'

import * as ProductCategoryApi from '@/api/mall/product/category'
import SpuIndex from './form/index.vue'
// 从路由中引入store中的app仓库
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
// 从商户选项卡中传过来的id 如果有的话即证明是从商户中传过来的
const props = defineProps({
  merchantId: {
    type: Number,
    default: undefined
  },
  userId: {
    type: Number,
    default: undefined
  },
  isDetail: {
    type: Boolean,
    default: false
  }
})

defineOptions({ name: 'ProductSpu' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
const minWidth = ref(178)
// 计算最小图片宽度
const calculateMinWidth = () => {
  nextTick(() => {
    const images = document.querySelectorAll('.card-img')
    let minWidthVal = Infinity

    // 遍历所有图片，找出最小宽度
    images.forEach((img) => {
      const imgWidth = img.clientWidth
      if (imgWidth < minWidthVal) {
        minWidthVal = imgWidth
      }
    })

    // 更新最小宽度
    if (minWidthVal !== Infinity) {
      minWidth.value = minWidthVal
    }
  })
}
// tabs 数据
const tabsData = reactive([
  {
    name: '待审核',
    type: '-1',
    count: 0
  },
  {
    name: '全部',
    type: '',
    count: 0
  },
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: '-1',
  name: '',
  categoryId: undefined,
  createTime: undefined,
  shopId: undefined,
  checkStatus: 1
}) // 查询参数

const queryFormRef = ref() // 搜索的表单Ref
const searchMoreShow = ref(false)
// 鼠标移入显示变动图标
function handleMouseOver(index) {
  list.value[index].showSetting = true
}
// 鼠标移出不显示图标
function handleMouseOut(index) {
  list.value[index].showSetting = false
}

// 打开更多搜索条件
const showSearchMore = () => {
  searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
  searchMoreShow.value = false
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  if (queryParams.value.tabType === '-1') {
    queryParams.value.checkStatus = 0
  } else {
    queryParams.value.checkStatus = 1
  }
  if (props.merchantId) {
    queryParams.value.merchantId = props.merchantId
  }

  try {
    let data
    if (props.userId) {
      console.log(props.userId)
      queryParams.value.userId = props.userId
      data = await ProductSpuApi.getFavoriteByUser(queryParams.value)
    } else {
      data = await ProductSpuApi.getSpuPage(queryParams.value)
    }

    data.list.forEach((obj) => {
      obj.showSetting = false
    })

    list.value = data.list
    // console.log(list.value)
    total.value = data.total
  } finally {
    loading.value = false
    searchMoreShow.value = false
    getTabsCount()
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as string
  getList()
}

/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
  const obj = ref({ ...queryParams.value })
  if (props.merchantId) {
    obj.value.merId = props.merchantId
  }
  const res = await ProductSpuApi.getTabsCount(obj.value)
  for (let i in tabsData) {
    if (tabsData[i].type === '-1') {
      tabsData[i].count = res['-1']
    } else if (tabsData[i].type === '') {
      tabsData[i].count = res['0'] + res['1'] + res['4']
    } else {
      tabsData[i].count = res[tabsData[i].type]
    }
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.categoryId = undefined
  queryParams.value.createTime = undefined
  queryParams.value.name = ''
  queryParams.value.tabType = ''
  queryParams.value.shopId = undefined
  handleQuery()
}

const formRef = ref()
/** 新增或修改 */
const openForm = (type: string, row: any, newStatus: number, tabType: number) => {
  formRef.value.open(type, row, newStatus, tabType)
}
/** 查看商品详情 */
const openDetail = (type: string, row: any, newStatus: number) => {
  if (mobile.value) {
    push({
      name: 'ProductSpuMobileDetail',
      params: { id: row.id, applyMemberUserId: row.applyMemberUserId, checkStatus: row.checkStatus }
    })
  } else {
    formRef.value.open(type, row, newStatus)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams)
    download.excel(data, '商品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
// onActivated(() => {
// 	getList()
// })
// 所有的店铺
let shopList = ref([])
// 获得所有店铺
const getAllShop = async () => {
  loading.value = true
  const res = await AfterSaleApi.getAllShop()
  shopList.value = res
}
/** 初始化 **/
onMounted(async () => {
  await getAllShop()
  await getTabsCount()
  await getList().then(() => {
    if (total.value === 0) {
      queryParams.value.tabType = ''
      getList()
    }
  })
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
  calculateMinWidth()
})
</script>

<style src="@/styles/SearchIndex.css" lang="scss" scoped></style>
