<template>
  <el-dialog title="选择商品" width="800px" v-model="visible">
    <div class="scroll">
      <div class="list">
        <div class="item" v-for="item in list" :key="item.id" @click="selectItem(item)">
          <div class="img">
            <el-image :src="item.coverImg" style="width: 100%;height: 100%;border-radius: 4px;"></el-image>
          </div>
          <div class="info">
            <div class="name">{{ item.name }}</div>
            <div class="price">{{ multiplyAndFormat(returnPrice(item.skuList) || 0) }}</div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getProductList } from '@/api/coupon/index'
import { multiplyAndFormat } from '@/utils'

const visible = ref(false)

const list = ref([])

// 返回规格最高价
function returnPrice(skuList) {
  return Math.max(...skuList.map(item => item.salePrice));
}

// 选择商品
const emits = defineEmits(['success'])
function selectItem(item) {
  emits('success', {
    id: item.id,
    coverImg: item.coverImg,
    name: item.name,
    price: returnPrice(item.skuList)
  })
  visible.value = false
}

// 获取商品-列表
async function getProductListAjax() {
  try {
    list.value = await getProductList()
  } catch (error) {
    console.log(error);
  }
}

function show() {
  visible.value = true
}

defineExpose({
  show
})

onMounted(() => {
  getProductListAjax()
})
</script>

<style scoped lang="scss">
.scroll {
  height: 60vh;
  overflow-y: auto;
  padding-bottom: 10px;
}

.list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 14px;
  grid-row-gap: 14px;

  .item {
    border-radius: 4px;
    border: 1px solid #ececec;
    padding: 10px;
    display: flex;
    transition: all .3s ease-in-out;

    &:hover {
      cursor: pointer;
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }

    .img {
      --size: 50px;
      height: var(--size);
      width: var(--size);
    }

    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;

      .name {
        font-size: 16px;
        color: 333;
      }

      .price {
        font-size: 16px;
        color: var(--el-color-danger);
      }
    }
  }
}
</style>