<template>
  <view class="c-links">
    <template v-if="items.loading">
      <slot name="loading">
        <view class="w-loading"></view> 加载中...
      </slot>
    </template>

    <template v-else-if="items.error">
      <slot name="error">加载错误</slot>
    </template>

    <template v-else>

      <view class="c-links-list">
        <view v-for="(item, index) in items" :key="index">
          <slot :item="item" :index="index">
            {{ item }}
          </slot>
        </view>
      </view>

    </template>
  </view>
</template>

<script setup>

import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { ref, watch, computed, onMounted } from 'vue'
import { useCacheStore } from '@/store'
import { listByType } from '@/api/system/linksApi'

const cacheStore = useCacheStore();

const key = "c-links";

const props = defineProps({
  id: {
    type: [String, Number],
    default: ""
  },
  max: {
    type: Number,
    default: 99
  }
});

const id = computed(() => props.id);

if (!cacheStore.cache[key]) {
  cacheStore.cache[key] = {};
}


const items = computed(() => cacheStore.cache[key][id.value] || {});


const loadData = async () => {
  if (!id.value) {
    return;
  }
  if (cacheStore.cache[key][id.value]) {
    return;
  }
  cacheStore.cache[key][id.value] = { loading: true };
  try {
    let r = await listByType(id.value,props.max);
    if (r) {
      r.records.forEach(item => {
        item.img = uni.$w.url(item.img);
      });
      cacheStore.cache[key][id.value] = r.records;
    } else {
      cacheStore.cache[key][id.value] = { error: true }
    }
  } catch (e) {
    cacheStore.cache[key][id.value] = { error: true }
  }
}

watch(() => id.value, () => {
  loadData();
});

// #ifdef H5
onMounted(loadData);
// #endif
// #ifndef H5
onReady(loadData);
// #endif




const reload = async () => {
  cacheStore.cache[key][id.value] = undefined;
  loadData();
}
defineExpose({ reload });

</script>

<style lang="scss" scoped>
.c-links {
  width: 100%;
  box-sizing: border-box;
  
  &-image {
    aspect-ratio: var(--aspect-ratio, 1/1);
  }

  &-list {
    display: grid;
    width: 100%;
    grid-template-columns: repeat(var(--cols, 1), 1fr);
    gap: var(--gap, 0);
  }
}
</style>
