<template>
	<el-table ref="spuListRef" v-loading="loading" :data="list" :stripe="true" row-key="id">
		<el-table-column v-if="multiple" type="selection" width="55" />
    <el-table-column label="商品图片" align="center" min-width="80" prop="picUrl">
      <template #default="scope">
        <img :src="scope.row.picUrl" alt="" class="h-40px" />
      </template>
    </el-table-column>
    <el-table-column label="商品名称" align="center" prop="name" />
    <el-table-column v-if="!multiple" label="操作" align="center" min-width="80" prop="url">
      <template #default="scope">
      <el-button link type="primary" @click.stop="emit('select', scope.row)">选择</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getSpuList" />
</template>

<script setup lang="ts">
defineOptions({ name: 'SpuList'})
import * as ProductSpuApi from '@/api/mall/product/spu'

const emit = defineEmits(['refresh', 'select'])

const props = defineProps({
	// 是否选择，是否多选
	multiple: {
		type: Boolean,
		default: false
	},
	// 选中的数据
	select: {
		type: Array,
		default: () => []
	}
})

const spuListRef = ref()

const total = ref(0)
const list = ref([])
const loading = ref(false)
const queryParams = reactive({
  pageNo: 1,
	pageSize: 10
})
const selectedRows = ref(props.select)

const getSpuList = async () => {
  loading.value = true
  try {
    const res = await ProductSpuApi.getSpuPage(queryParams)
    list.value = res.list
    total.value = res.total

		// 回显已选中的数据
		if (props.multiple && selectedRows.value && selectedRows.value.length) {
			nextTick(() => {
				selectedRows.value.forEach(item => {
					const index = list.value.findIndex(row => row.id === item.id)
					if (index > -1) {
						spuListRef.value.toggleRowSelection(list.value[index], true)
					}
				})
			})
		}
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await getSpuList()
})

defineExpose({
	spuListRef
})
</script>