<!-- 增加了点击跳转到指定路由及列表条件过滤功能 -->
<template>
  <u-swiper
    v-if="swiperList.length"
    :list="swiperList"
    :keyName="imgPro"
    :current="current"
    :interval="interval"
    :duration="duration"
    :circular="circular"
    :previousMargin="previousMargin"
    :nextMargin="nextMargin"
    :easingFunction="easingFunction"
    :height="height"
    :bgColor="bgColor"
    :radius="radius"
    @click="clickEvt"
  >
  </u-swiper>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch, watchEffect } from "vue";
interface Props {
  list?: any[]; // 图片列表
  current?: number | string;
  interval?: number | string;
  duration?: number | string;
  circular?: boolean;
  previousMargin?: string | number;
  nextMargin?: string | number;
  easingFunction?: string;
  height?: string | number;
  bgColor?: string;
  radius?: number | string;
  customStyle?: any;

  imgPro?: string; // 图片对应的属性名
  imgServerUrl?: string; // 图片服务器根地址
  condPro?: string; //条件属性名
  condValue?: string; //条件属性值

  linkUrl?: string; //跳转Url
  linkType?: string; //跳转类型
  linkPro?: string; // 跳转属性参数
}

const props = withDefaults(defineProps<Props>(), {
  imgPro: "url",
  current: 0,
  interval: 3000,
  duration: 300,
  circular: false,
  previousMargin: 0,
  nextMargin: 0,
  easingFunction: "default",
  height: "130px",
  bgColor: "#f3f4f6",
  radius: 4,
  linkPro: "id",
  list: () => [],
});

const emit = defineEmits(["click"]);

// 图片列表
const swiperList = ref<any>([]);
// 点击图片
const clickEvt = (index: number) => {
  if (props.linkUrl) {
    if (props.linkPro) {
      // 点击跳转
      uni[props.linkType]({
        url:
          props.linkUrl +
          "?" +
          props.linkPro +
          "=" +
          swiperList.value[index][props.linkPro],
      });
    } else {
      uni[props.linkType]({
        url: props.linkUrl,
      });
    }
  } else {
    emit("click", index, swiperList.value[index]);
  }
};
// 监听props.list的变化, 过滤出符合条件的图片列表
watchEffect(() => {
  if (
    props.list.length &&
    Object.prototype.toString.call(props.list[0]) == "[object Object]"
  ) {
    let amList = JSON.parse(JSON.stringify(props.list));
    if (props.condPro && props.condValue) {
        // 如果有条件属性和条件值，则过滤出符合条件的图片列表  {TYPE:2,AGE:18}
      swiperList.value = amList.filter((item: any) => {
        return item[props.condPro] == props.condValue;
      });
    } else {
      swiperList.value = amList;
    }
  } else {
    swiperList.value = props.list;
  }
});
watch(swiperList, () => {
  if (
    props.imgServerUrl &&
    swiperList.value.length &&
    Object.prototype.toString.call(swiperList.value[0]) == "[object Object]"
  ) {
    swiperList.value.forEach((item: any) => {
      if (item[props.imgPro] && item[props.imgPro].startsWith("[{")) {
        item[props.imgPro] =
          props.imgServerUrl + JSON.parse(item[props.imgPro])[0].url;
      }
    });
  }
});
</script>
<style lang="scss" scoped></style>
