<template>
  <view
    class="xd-footer-tabbar"
    :style="[{
      height: height +'rpx',
      backgroundColor: bgColor,
      zIndex: zIndex,
    },tabbar['bodyStyle']]"
  >
    <view class="xd-footer-tabbar__border">
      <template v-if="view">
        <view
          v-for="(item) in dataList"
          :key="item.key"
          class="xd-footer-tabbar__item"
        >
          <view class="xd-footer-tabbar__item-badge"
                v-if="item.num"
                :style="{
              background: 'red',
              padding: item.num === '99+' ? '0 8rpx': '0'
            }"
          >{{item.num}}</view>
          <view class="xd-footer-tabbar__item-link"
                open-type="redirect"
                :url="item.path + '?' + params"
          >
            <view class="xd-footer-tabbar__icon">
              <view v-if="item.image" class="image">
                <image :src="(activeUrl === getPath(item.path))?item['actImage']:item.image" />
              </view>
              <xd-font-icon
                v-else-if="item.icon"
                :size="item.size ? item.size * 2 : 36"
                :icon="item.icon"
                :style="{
                color: (activeUrl === getPath(item.path)) ? selectedTextColor : textColor
              }"
              ></xd-font-icon>
            </view>

            <view class="xd-footer-tabbar__text"
                  :style="{
                color: (activeUrl === getPath(item.path))?  selectedTextColor : textColor
              }"
            >{{item.name}}</view>
          </view>
        </view>
      </template>
      <template v-else>
        <view
          v-for="(item) in dataList"
          :key="item.key"
          class="xd-footer-tabbar__item"
        >
          <view class="xd-footer-tabbar__item-badge"
                v-if="item.num"
                :style="{
              background: 'red',
              padding: item.num === '99+' ? '0 8rpx': '0'
            }"
          >{{item.num}}</view>
          <navigator class="xd-footer-tabbar__item-link"
                     open-type="redirect"
                     :url="item.path + '?' + params"
          >
            <view class="xd-footer-tabbar__icon">
              <view v-if="item.image" class="image">
                <image :src="(activeUrl === getPath(item.path))?item['actImage']:item.image" />
              </view>
              <xd-font-icon
                v-else-if="item.icon"
                :size="item.size ? item.size * 2 : 36"
                :icon="item.icon"
                :style="{
                color: (activeUrl === getPath(item.path)) ? selectedTextColor : textColor
              }"
              ></xd-font-icon>
            </view>
            <view class="xd-footer-tabbar__text"
                  :style="{
                color: (activeUrl === getPath(item.path))?  selectedTextColor : textColor
              }"
            >{{item.name}}</view>
          </navigator>
        </view>
      </template>
    </view>
  </view>
</template>

<script>
import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
import {
  PLATFORM_PARAM_SETTING,
  getPlatformParamsValue,
  getPlatformParamsForGroup
} from "@/project";
import storage from "@/common/storage";
import {
  getParentsStyle,
} from '@/utils/xd.base';

/**
 * XdFooterTabbar 全局Ui
 * @description 底部功能
 * @tutorial
 * @property {Number} zIndex          层级数字 （可选）
 * @property {Number} height          tabbar高度（可选）
 * @property {Boolean} view           view显示模式（可选）
 * @property {Object} styles          模版风格（可选）
 * @property {Object} tabbar
 *  tabbar.selectedColor  {String} tabbar当前选中文字颜色
 *  tabbar.bgColor  {String} tabbar背景颜色值
 *  tabbar.list {Array} tabbar列表
 *  tabbar.list.name  {String} tabbar文案（4个汉字）
 *  tabbar.list.path  {String} 链接路径
 *  tabbar.list.icon  {String} iconfont图标
 */

export default {
  name: "XdFooterBar",
  components: {
    XdFontIcon
  },
  props: {
    styles:{
      type: Object,
      default(){
        return {}
      },
    },
    view: {
      type:Boolean,
      default: false,
    },
    zIndex: {
      type: Number,
      default: 1500 //rpx
    },
    tabbar: {
      type: Object,
      required: true
    },
    height: {
      type: Number,
      default: 100 //rpx
    },
    baseUrl: {
      type: String,
      required: true
    }
  },

  data(){
    return {
      show: false, //是否显示底部导航

      dataList: [],
      activeUrl: null, //当前路径
      params: null, //系统透传参数

      bgColor: '',
      selectedTextColor: null,
      textColor:null,

      styleMainColor: null, //插件主题风格样式
    }
  },

  watch:{
    tabbar(){
      this.init();
    }
  },


  async created() {
    this.styleMainColor = await getParentsStyle(this.$parent, '$mainColor');

    //设置活动参数
    let params = [];
    let xParamsKey = getPlatformParamsForGroup([]);
    xParamsKey.map(key=>{
      let {paramKey, storageKey} = getPlatformParamsValue(key);
      let value = storage.get(storageKey);
      if(value) params.push(`${paramKey}=${value}`);
    })
    // let event = storage.get(PLATFORM_PARAM_SETTING.EVENT_PARAM_SAVE_KEY);
    // let all = storage.get(PLATFORM_PARAM_SETTING.OVER_ALL_PARAM_NAME_SAVE_KEY);
    // let test = storage.get(PLATFORM_PARAM_SETTING.TEST_PARAM_NAME_SAVE_KEY);
    // if (event) params.push(`${PLATFORM_PARAM_SETTING.EVENT_PARAM_NAME}=${event}`);
    // if (all) params.push(`${PLATFORM_PARAM_SETTING.OVER_ALL_PARAM_NAME}=${all}`);
    // if (test) params.push(`${PLATFORM_PARAM_SETTING.TEST_PARAM_NAME}=${test}`);
    this.params = params.join("&");

    this.init();
  },

  mounted() {
    this.$nextTick(() => {
      this.getActive()
    })
  },

  methods:{

    getPath(path){
      if(this.baseUrl) path = require('path').normalize(`/${this.baseUrl}/${path}`);
      console.warn(`XdFooterBar.getPath, {url: ${path}`);
      return path;
    },

    getActive(){
      let routes = this.$xdUniHelper.getCurrentPages(this.tabbar.home);
      this.activeUrl = routes['path'];
      console.warn(`XdFooterBar.getActive, {activeUrl: ${this.activeUrl},baseUrl: ${this.baseUrl}}`)
    },

    /**
     * @description
     * @param list
     * @param find
     * @returns {boolean}
     */
    inArray(list,find){
      return this.$xdUniHelper.inArray(list,find)
    },


    /**
     * @description 初始化数据
     */
    init(){
      this.bgColor = this.tabbar['bgColor'];
      this.selectedTextColor = this.tabbar['selectedColor'] || this.styleMainColor;
      this.textColor = this.tabbar['color'] || '#333';
      this.dataList = this.tabbar.list.map(item=>{
        return {
          key : this.$xdUniHelper.randomChar(20),
          ...item
        }
      });
    },
  }
}
</script>

<style scoped lang="less">
.xd-footer-tabbar {
  height: 100%;
  width: 100%;
  overflow: hidden;

  &__icon {
    width: 64rpx;
    height: 64rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &__text {
    line-height:1.2rem;
  }

  &__border {
    border-top: 1px solid #eee;
    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
    height: 100%;
    box-sizing: border-box;
  }

  &__item {
    height: 100%;
    flex: 1;
    font-size: @xd-font-size-sm;
    text-align: center;
    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
    position: relative;

    &-link {
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
    }

    & > view:nth-child(2) {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }

    &-badge {
      position: absolute;
      top: unit(0, rpx);
      left: 50%;
      color: #fff;
      transform: translateX(unit(10,rpx));
      min-width: unit(32, rpx);
      height: unit(32, rpx);
      line-height: unit(32, rpx);
      border-radius: unit(16, rpx);
      font-size: unit(18, rpx);
      z-index: 20;
    }
  }


  &__image {
    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
  }

  .image {
    width: 100%;
    height: 100%;

    & > image {
      max-width: 100%;
      max-height: 100%;
    }
  }

}
</style>
