<template>
  <div class="app-tabbar">
    <div class="app-tabbar__wrapper" :style="styles">
      <template v-for="(item, index) in dataList" :key="index">
        <div :class="['app-tabbar__item', 'app-tabbar__item--' + item.name, selectedIndex === index && 'is-active']"
          @click="onChange(index)">
          <slot :item="item" :index="index">
            <!--判断是否图片图标-->
            <template v-if="item.iconType === 'image'">
              <div :class="['g-icon', selectedIndex === index && 'active']">
                <img :src="item.icon" v-if="selectedIndex === index" />
                <img :src="item.activeIcon" v-else />
                <span>{{ item.label }}</span>
              </div>
            </template>
            <template v-else>
              <app-iconfont label-direction="bottom" :icon="item.icon" :active-icon="item.activeIcon"
                :active="selectedIndex === index">{{ item.label }}</app-iconfont>
            </template>
          </slot>
        </div>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { PropType, ref, watch, computed } from 'vue'
import { Tabbar } from './interface'
import client from '@/utils/client'
import AppIconfont from '@mobile/components/base/iconfont/index.vue'

const emit = defineEmits(['change', 'update:dataIndex'])

const props = defineProps({
  // 数据列表
  dataList: {
    type: Array as PropType<Tabbar[]>,
    default: () => ([]),
  },
  // 当前标签索引
  dataIndex: {
    type: Number,
    default: 0,
  },
  // 是否固定在底部
  fixed: {
    type: Boolean,
    default: false,
  }
})

const { state } = client
const selectedIndex = ref(props.dataIndex)

const styles = computed(() => ({
  position: props.fixed ? 'fixed' : 'static',
  width: state.clientWidth + 'px',
}))

const onChange = (index: number) => {
  if (selectedIndex.value !== index) {
    selectedIndex.value = index
    emit('update:dataIndex', index)
    emit('change', props.dataList[index], index)
  }
}

watch(() => props.dataIndex, (val) => onChange(val))
</script>

<style lang="less" scoped>
@import './index.less';
</style>