<template>
  <view class="xd-custom-bar" v-if="initDone" :style="{height: barNavHeight + barStatusHeight  + 'rpx'}">
    <view
      class="xd-custom-bar__fixed"
      :style="{
        backgroundColor: (customBg === null) ? (uiBgImage ? '': uiBgColor): 'rgba(0,0,0,0)',
        backgroundImage:  customBg === null ? getBackgroundImage:(this.scrollDetail > 5 ?getBackgroundImage : 'none'),
        height: barNavHeight + barStatusHeight  + 'rpx'
      }"
    >
      <!-- 状态栏 -->
      <view :style="{ height: barStatusHeight+'rpx'}"></view>
      <!-- 状态栏 -->
      <!-- 导航栏内容 -->
      <view
        class="xd-custom-bar__fixed-content"
        :style="{
          height: barNavHeight + 'rpx',
          lineHeight: barNavHeight + 'rpx',
          width : barWidth + 'px',
          paddingLeft: isSlotTopBar ? 0: (paddingLeftAndright + 'px')
         }"
      >
        <!--返回上一个界元素-->
        <view class="xd-custom-bar__fixed-content-icon" @click.stop="back" v-if="!isSlotTopBar">
          <xd-font-icon
            v-if="isTopIcon"
            :style="[topIconComp]"
            :icon="isPrev ? 'iconxiangzuo_xian' : 'iconshouye_mian'"
            :color="uiTextColor"
            :size="uiIconSize"
          ></xd-font-icon>
          <text v-if="isIcbStatus" @click.stop="icbClickBack">关闭</text>
        </view>
        <!--返回上一个界元素-->
        <view class="xd-custom-bar__fixed-content-slot" v-if="isSlotTopBar">
          <slot>{{title}}</slot>
        </view>
        <template v-else>
          <view
            v-if="textAlign === 'left'"
            class="xd-custom-bar__fixed-content-left"
            :style="{
              color: uiTextColor,
              fontSize: uiFontSize + 'rpx'
            }">{{title}}</view>
          <view
            v-else
            class="xd-custom-bar__fixed-content-center"
            :style="{
              color: uiTextColor,
              width: barWidth - (paddingLeftAndright + menuButtonInfoWidth) + 'px',
              fontSize: uiFontSize + 'rpx',
              fontWeight: uiFontWeight,
            }">{{title}}</view>
        </template>
        <view class="xd-custom-bar__fixed-content-icon" v-if="paddingRight && !isSlotTopBar"></view>
      </view>
      <!-- 导航栏内容 -->
    </view>
  </view>
</template>

<script>
  import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
  import {Base64} from 'js-base64';
  import {isThirdLogin} from "@/utils/xd.base";

  /**
   * XdBar 全局UI
   * @description header tabbar 当前组件一定要放在页面跟节点下（不可放在组件当中使用，应该是编译问题导致）
   * @tutorial
   * @property {String}  title             标题名称（可选）默认：''
   * @property {Boolean}  showBack         是否显示返回按钮（可选）默认：true
   * @property {String}  bgColor           背景颜色，默认使用全局主色调（可选）默认：主色掉
   * @property {String}  bgImage           背景图片，默认无
   * @property {String}  color             文字颜色（可选）使用主色调时候文字颜色为 #333
   *
   * @event {Function} click               按钮点击事件e
   */

  export default {
    name: "XdBar",
    components: {
      XdFontIcon
    },
    props: {
      //页面滚动的值
      scrollDetail:{
        type: Number,
        default: 0,
      },
      barNavHeight: {
        type: Number,
        default: 100
      },

      isSlotTopBar: {
        type: Boolean,
        default: false
      },

      barStatusHeight:{
        type: Number,
        default: 0
      },
      title: {
        type: String,
        default: ''
      },
      showBack: {
        type: Boolean,
        default: true
      },
      bgColor: {
        type: String,
        default: ''
      },
      bgImage: {
        type: String,
      },
      color: {
        type: String,
        default: '#fff'
      },
      textAlign: {
        type: String,
        default: 'center' //center,left
      }
    },
    data() {
      return {
        initDone: false, //是否加载完成
        isIpad: null,

        //返回键显示相关数据
        isPrev: null, //是否可以返回页面
        noPrevToIndex: false, //是否设置无返回页面是否跳转到首页
        xdRedirectUrl: null, //返回上一个地址

        //胶囊的计算
        paddingLeftAndright: 0, //px 计算左右padding默认值
        menuButtonInfoWidth: 0, //胶囊宽度
        barWidth: 0, //bar宽度
        paddingRight: true,

        //样式风格
        uiBgColor: '', //自定义背景颜色
        uiTextColor: '#fff', //自定义标题文本与返回ICON颜色
        uiBgImage:'', //背景图片
        uiIconSize: 40,
        uiFontSize: 34,
        uiFontWeight: 'normal',

        //自定义背景
        customBg: null,
      };
    },
    computed:{
      topIconComp(){
        // #ifdef H5
        return {}
        // #endif
        // #ifdef MP-WEIXIN
        return {
          fontWeight: '400'
        }
        // #endif
      },
      isIcbStatus(){
        // #ifdef H5
        return isThirdLogin().isICB && !this.isPrev
        // #endif
        // #ifdef MP-WEIXIN
        return false
        // #endif
      },
      getBackgroundImage(){
        if(this.customBg !== null) {
          return `url("${this.customBg}")`;
        }

        let isGradient = this.bgColor.indexOf('linear-gradient') !== -1;
        let bgc = `url(${this.bgImage})`;
        // #ifdef H5
        if ((this.bgImage === 'none'|| this.bgImage === '') && isGradient) {
          bgc = this.uiBgImage = this.bgColor;
        }
        // #endif

        return bgc;

      },
      isTopIcon(){
        // #ifdef H5
        return this.noPrevToIndex && this.showBack && this.isPrev !== null
        // #endif
        // #ifdef MP-WEIXIN
        //自定义导航并且不显示导航设置
        if(this.$parent.navigationStyle && !this.showBack) {
          return this.noPrevToIndex && this.isPrev !== null
        }
        return this.noPrevToIndex && this.showBack && this.isPrev !== null
        // #endif
      }
    },
    created(){
      this.noPrevToIndex = this.$settings['noPrevPageToIndex'] === undefined ? false : this.$settings['noPrevPageToIndex'];

      // #ifdef MP-WEIXIN
      let systemInfo = uni.getSystemInfoSync();

      //开发模式
      if(systemInfo.platform === 'devtools') {
        this.uiIconSize = 34;
        this.uiFontSize = 26;
        this.uiFontWeight = 'normal';
      }
      else {
        this.uiIconSize = 34;
        this.uiFontSize = 34;
        this.uiFontWeight = 500;
      }

      wx.onMenuButtonBoundingClientRectWeightChange(()=>{
        this.initDone = false;
        this.setNavBar();
      })

      // let tempInfo = {
      //   platform: uni.getSystemInfoSync().platform,
      //   app: uni.getSystemInfoSync().app,
      //   env: uni.getSystemInfoSync().host,
      //   brand: uni.getSystemInfoSync().brand,
      //   model:  uni.getSystemInfoSync().model,
      //   system:  uni.getSystemInfoSync().system,
      //   width: uni.getSystemInfoSync()['safeArea'].width,
      //   bar: uni.getMenuButtonBoundingClientRect().width * this.$pxNum
      // }
      // this.$xdConfirm({content: JSON.stringify(tempInfo, null, 2)})
      // #endif

      //背景颜色设置
      this.uiBgColor = this.bgColor || this.$mainColor;
      if(this.color) this.uiTextColor = this.color;
      this.uiBgImage = this.bgImage;

      /**
       * @description 设置样式
       */
      uni.onWindowResize(() => {
        this.setNavBar()
      });

      this.$xdRoot.$on('setLayoutPageBg', (bg)=>{
        this.customBg = bg || null;
      });

    },
    mounted() {
      this.setNavBar();
      this.checkPrevPages();
    },
    methods: {

      /**
       * @description 检查上一个页面
       */
      checkPrevPages(){
        //判断是否有上一个页面
        let pages = getCurrentPages();//当前页
        let beforePageStatus = false;
        if (pages.length >= 2) {
          beforePageStatus = true;
        }

        //有项目内跳转地址
        let xdRedirect = false;
        if(this.$xdUniHelper.getParmater('xdRedirect')) {
          try {
            if(Base64.decode(this.$xdUniHelper.getParmater('xdRedirect'))) xdRedirect = true;
          } catch (e) {
            xdRedirect = false;
          }
        }

        //项目外地址
        let xdProjectCallback = false;
        if (this.$xdUniHelper.getParmater('xdProjectCallback')) {
          try {
            if (Base64.decode(this.$xdUniHelper.getParmater('xdProjectCallback'))) xdProjectCallback = true;
          } catch (e) {
            xdProjectCallback = false;
          }
        }
        this.isPrev = beforePageStatus || xdRedirect || xdProjectCallback;
      },

      setNavBar() {
        // 获取手机系统信息
        const info = uni.getSystemInfoSync();

        //导航宽度
        this.barWidth = info['safeArea'].width;

        // 获取胶囊的位置
        // #ifdef MP-WEIXIN || APP-PLUS || MP-ALIPAY
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
        this.paddingLeftAndright = info['safeArea'].width - menuButtonInfo.right;
        let menuButtonInfoWidth = menuButtonInfo.width;

        //安卓首次进入获取值有误问题
        if(info.platform === 'android') {
          let menuButtonDefaultWidth = 200 * this.$rpxNum;
          menuButtonInfoWidth = Math.min(menuButtonDefaultWidth, menuButtonInfoWidth)
        }

        this.barWidth = info['safeArea'].width - (this.paddingLeftAndright + this.menuButtonInfoWidth);
        this.paddingRight = false;
        // #endif


        this.initDone = true;
      },

      icbClickBack(){
        //工行处理
        if(isThirdLogin().isICB) {
          window.ICBC_SDK.back();
        }
      },

      back(){
        // #ifdef MP-WEIXIN
        //自定义导航并且不显示导航设置
        if(this.$parent.navigationStyle && !this.showBack) {
          this.$xdUniHelper.navigateBack();
          return;
        }
        // #endif

        if(!this.showBack) return;

        //临时兼容
        if(this.noPrevToIndex === 'back') {
          //其他正常跳转
          this.$emit('click');
          this.$emit('back');
          return;
        }

        //有上一个路径的返回到上一个路径
        if(this.$xdUniHelper.getParmater('xdRedirect')) {
          try {
            this.$xdUniHelper.redirectTo({
              url: Base64.decode(this.$xdUniHelper.getParmater('xdRedirect'))
            }, false);
            return;
          }catch (e) {}
        }


        //有上一个路径的返回到上一个路径
        if (this.$xdUniHelper.getParmater('xdProjectCallback')) {
          try {
            window.location.href = Base64.decode(this.$xdUniHelper.getParmater('xdProjectCallback'));
            return;
          } catch (e) {
          }
        }


        //无上一个页面返回到首页
        if(this.noPrevToIndex && !this.isPrev) {
          let {query, ...other} = this.$xdUniHelper.parseURL();
          let url = this.$settings.index;
          if(query) url += `?${query}`;
          // #ifdef MP-WEIXIN
          wx.reLaunch({url})
          // #endif
          // #ifdef H5
          this.$xdUniHelper.redirectTo({
            url: url
          }, false);
          // #endif
          return;
        }


        //未开启无返回页面跳首页功能不处理
        if (!this.noPrevToIndex && !this.isPrev) return;

        //其他正常跳转
        this.$emit('click');
        this.$emit('back');
      },
    }
  }
</script>

<style lang="less">
  .xd-custom-bar {
    overflow: hidden;

    &__fixed {
      position: fixed;
      top: 0;
      left: 0;
      z-index: 99;
      width: 100%;
      background-size: 100%;
      background-position: top center;
      background-repeat: no-repeat;

      &-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;

        &-slot {
          width: 100%;
          display: block;
        }

        &-icon {
          display: flex;
          width: 34rpx;
          height: 100%;
          padding-left: 10rpx;
          justify-content: flex-start;
          align-items: center;
          flex-shrink: 0;
          position: relative;

          & > view {
            font-size: 20rpx;
            color: #fff;
            text-align: center;
            vertical-align: middle;
          }

          & > text {
            font-size: 28rpx;
            color: #fff;
            text-align: center;
            vertical-align: middle;
            position: absolute;
            right: -60rpx;
          }
        }

        &-left {
          flex: 1;
          width: 0;
          & > view:last-child {
            .uni-max-cut(1, 90);
            .uni-break-word();
          }
        }

        &-center {
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;
          margin-right: 44rpx;
          & > view:last-child {
            .uni-max-cut(1, 90);
            .uni-break-word();
          }
        }
      }
    }

  }
</style>

