<template>
  <div class="app-tabbar">
    <div class="app-tabbar__warpper" :style="styles">
      <template v-for="(item, index) in dataList" :key="index">
        <div class="app-tabbar__item" @click="onChange(index)">
          <slot :item="item" :index="index">
            <!--判断是否图片图标-->
            <template v-if="(item.icon instanceof Object)">
              <div :class="['g-icon', selectedIndex === index && 'active']">
                <img :src="item.icon.active" v-if="selectedIndex === index" />
                <img :src="item.icon.inactive" v-else />
                <span>{{ item.label }}</span>
              </div>
            </template>
            <template v-else>
              <div :class="['g-icon', item.icon, selectedIndex === index && 'active']">
                <span>{{ item.label }}</span>
              </div>
            </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'

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 selectedIndex = ref(props.dataIndex);
const { state } = client;

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', index, props.dataList[index]);
  }
}

watch(() => props.dataIndex, (val) => selectedIndex.value = val);
</script>

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