<template>
  <view class="tabbar-wrap">
    <view class="tabbar">
      <view 
        v-for="(item, index) in tabs" 
        :key="index" 
        class="tab-item" 
        @tap="routerPush(item.url)"
      >
        <img :src="curtTab === item.name ? item.activeIcon : item.icon" class="tab-icon"/>
        <text :class="['base-text', curtTab === item.name && 'checked']">{{ item.label }}</text>
      </view>
      <view v-if="!isScanCondeRentalCar" class="center-entrance" @tap="navToInputPage">
        <img src="https://qiniu.bms16.com/Fm_kDVr1TIeIbbBW6-5bz0r-cECO" style="width: 122rpx; height: 122rpx;"/>
        <!-- <img src="https://qiniu.bms16.com/FhCHLz8rQJ5mpJ6nUA4RbKiVkUOo" style="width: 120rpx; height: 24rpx;"/> -->
      </view>
	  <view v-else class="center-entrance" @tap="navToInputPage">
		<img src="https://qiniu.bms16.com/FqcCjRjhzHFUkZj76SMHNXCZHwb3" style="width: 122rpx; height: 122rpx;margin-bottom: 14rpx;"/>
	  	<view class="scan-text">扫一扫</view>
	  </view>
    </view>
  </view>
</template>

<script>
var app = getApp();
const storage = require('@/common/storage.js');
const http = require('@/common/http.js');
const config = require('@/common/config.js');
const common = require('@/common/common.js');
const appWhiteListFilter = require('@/common/appWhiteListFilter.js');


export default {
  props: {
    curtTab: {
      type: String,
      default: 'home'
    }
  },
  data() {
    return {
      selectedTab: uni.getStorageSync('selectedIndex') || 0,
      tabs: [
          { label: '设备', name: 'home', url: '/pages/index/index', 
            icon: '/static/resource/images/home_i.png', 
            activeIcon: '/static/resource/images/home_s.png' ,
          },
              { label: '服务', name: 'service', url: '/pages/service/service', 
            icon: '/static/resource/images/service_i.png',
            activeIcon: '/static/resource/images/service_s.png' ,
          },
              { label: '活动', name: 'active', url: '/pages/activity/activity', 
            icon: '/static/resource/images/active_i.png',
            activeIcon: '/static/resource/images/active_s.png' ,
          },
              { label: '我的', name: 'my', url: '/pages/my/my', 
            icon: '/static/resource/images/my_i.png',
            activeIcon: '/static/resource/images/my_s.png' ,
          },
      ],
      userInfo: {
        is_auth: 0,
        status: 0
      },
	  // accountInfo: uni.getAccountInfoSync(),
	  plate_number: '',
	  isScanCondeRentalCar: false,
    };
  },
  created: function () {
    if (appWhiteListFilter.isScanCondeRentalCar()) {
    	this.setData({
    		isScanCondeRentalCar: true
    	})
    }
  },
  methods: {
    routerPush(url) {
      
      // uni.setStorageSync('selectedIndex', data.index);
      uni.switchTab({ url });
      // uni.navigateTo({ url })
    },
    loadFaceToken() {
      const me = this
      http.postApi(config.API_USER_FACE_TOKEN, {}, (resp) => {
        if (resp.data.code === 200) {
          me.face_token = resp.data.data.token
          me.face_key = resp.data.data.key
          uni.navigateTo({
            url: '/pages/livenessView/livenessView?face_token=' + me.face_token +
              '&face_key=' + this.face_key,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
        } else {
          common.simpleToast(resp.data.msg)
        }
      })
    },
    _getParams() {
      return new Promise((reslove ,reject) => {
        http.postApi(config.API_DAYHIRE_CAR_CAR_LIST, {}, res => {
            const { data = [], wait_active_predetermine = null } = res.data.data
            const obj = {
              carList: data,
              wait_active_predetermine,
              order_status: data.length ? data[0].order_status : 0
            }
            reslove(obj)
        })
      })
    },
	
	loadScanCode(location,battery_sn) {
		const pData = {
			longitude: location.longitude,
			latitude: location.latitude,
			battery_sn: battery_sn
		}
		const me = this
		http.postApi(config.API_DAYHIRE_CAR_CAR_INFO, pData, (resp) => {
			uni.hideLoading()
			if (resp.data.code === 200) {
				const timestamp = Date.now(); // 获取当前时间戳（毫秒）  
				const isOffline = (Math.floor(timestamp / 1000) - resp.data.data.last_comm_time) > 1800
				me.plate_number = resp.data.data.license_plate_number
				if (resp.data.data.last_comm_time === 0 || isOffline) {
					common.simpleToast('此车辆已离线，请选择其他车辆')
				} else {
					let carInfo = JSON.stringify(resp.data.data)
					const car_model = resp.data.data.model_info.car_model
					const model_images = resp.data.data.model_info.model_images.split(',')
					const return_imgs = resp.data.data.return_imgs
					var model_id = resp.data.data.model_info.model_id
					if (resp.data.data.has_owner) { //车辆正在被使用
						if (resp.data.data.is_mine) { //是本人在使用
							uni.showModal({
								title: '提示',
								content: '已有正在使用的车辆，是否跳转至车辆详情页?',
								cancelText: '取消',
								confirmText: '确定',
								success: function(res) {
									this.isReturnHome = false
									uni.navigateTo({
										url: '/pages/battery/battery?plate_number=' +
											this.plate_number
									});
								},
								fail: function(res) {},
								complete: function(res) {},
							})
						} else {
							common.simpleToast('此车辆正在被使用')
						}
					} else {
						if (me.order_sn&&me.order_sn != '') {
							if (this.order_model_id != model_id) { // 预租车型与之前预约车型不一致
								common.simpleToast('与预约车型不符')
							} else {
								this.isReturnHome = false
								uni.navigateTo({
									url: '/pages/activation/activation?plate_number=' +
										this.plate_number + '&order_sn=' + this.order_sn +
										'&car_model=' + car_model + '&model_image=' +
										model_images[0] + '&return_imgs=' + JSON.stringify(
											return_imgs),
									fail() {}
								})
							}
		
						} else {
							this.setData({
								flashValue: 'off',
								isReturnHome: false
							})
							// this.isReturnHome = false
							uni.redirectTo({
								url: '/pages/carIntroduce/carIntroduce?carInfo=' +
									encodeURIComponent(carInfo) + '&plate_number=' + this
									.plate_number,
								fail() {}
							})
						}
					}
				}
			} else {
				common.simpleToast(resp.data.msg)
			}
		})
	},
	
    async navToInputPage() {
      const me = this
      const { userInfo = '' } = storage.getUserInfoData()
      if (userInfo.is_auth - 0 == 1 && userInfo.status - 0 == 2) {
        const params =  await this._getParams()
		var plate_number = params.carList.length!=0&&params.carList[0].license_plate_number?params.carList[0].license_plate_number:me.plate_number
		if (params.wait_active_predetermine != null) { //预约车辆为待激活状态
          if (params.wait_active_predetermine.order_status == 2) {
            uni.showModal({
              title: '提示',
              content: '您有等待激活的车辆，是否跳转至订单详情页?',
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/orderStatus/orderStatus?order_sn=' + params
                      .wait_active_predetermine.order_sn
                  });
                }
              }
            })
          }
          return
        }
        if (params.carList.length == 0) {
			if(me.isScanCondeRentalCar) {
				uni.scanCode({
					onlyFromCamera: true,
					success: function (res) {
						var location = uni.getStorageSync('user_current_location')
						me.loadScanCode(location,res.result)
					},
					fail: function (res) { },
					complete: function (res) { },
				})
			} else {
				uni.navigateTo({
					url: '/pages/scanCar/scanCar'
				});
			}
        } else {
          if (params.order_status == 3 || params.order_status == 4) { // 车辆状态为未激活
            uni.showModal({
              title: '提示',
              content: '已有正在使用的车辆，是否跳转至车辆详情页?',
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  const isReturnIndex = false
                  uni.navigateTo({
                    url: '/pages/battery/battery?plate_number=' + plate_number +'&isReturnIndex=' + isReturnIndex
                  });
                }
              }
            })
          } else if (params.order_status == 5) {
            uni.showModal({
              title: '提示',
              content: '请等待商家确认还车,是否跳转至订单详情页?',
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/orderStatus/orderStatus?order_sn=' + params
                      .carList[0].order_sn
                  });
                }
              }
            })
          } else {
            uni.showModal({
              title: '提示',
              content: '已有正在进行的订单，是否跳转至订单详情页?',
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/orderStatus/orderStatus?order_sn=' + params
                      .carList[0].order_sn
                  });
                }
              }
            })
          }
        }
      } else if (userInfo.is_auth == 1 && userInfo.status != 2) {
        uni.showModal({
          title: '身份认证提示',
          content: '尚未完成身份认证，是否进行身份认证?',
          cancelText: '取消',
          confirmText: '确定',
          success: function(res) {
            if (res.confirm) {
              me.loadFaceToken()
            }
          }
        })
      } else {
        uni.showModal({
          title: '提示',
          content: '您还未登录，请先登录',
          showCancel: false,
          confirmText: '确定',
          success: function(res) {
            if (res.confirm) {
              //#ifdef MP-ALIPAY
              uni.navigateTo({
                url: '/pages/phoneLogin/phoneLogin',
              })
              //#endif
              //#ifdef MP-WEIXIN
              uni.navigateTo({
                url: '/pages/login/login',
              })
              //#endif
            }
          }
        })
      }
    }
  }
};
</script>

<style scoped>
.tabbar-wrap {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  border-bottom: env(safe-area-inset-bottom) solid #fff;
  z-index: 9999;
}
.tabbar {
  height: 188rpx;
  width: 100%;
  /* background: url('https://qiniu.bms16.com/FiYy2ZOV_hGSJx32YAQSLZSbAOFq') no-repeat; */
  background: url('https://qiniu.bms16.com/Fk8jEU5-RbARagKDYZy0tKWErKNF') no-repeat;
  background-size: 100%;
  display: flex;
  justify-content: space-between;
  padding-top: 60rpx;
  position: relative;
  bottom: -5rpx;
}
.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}
.tab-item:nth-child(2) {
  margin-right: 20%;
}
.tab-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 4px;
}
.center-entrance {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 28rpx;
  display: flex;
  flex-direction: column;
}
.scan-text {
	font-size: 10px;
	text-align: center;
	color: #828DA2;
	font-weight: 600;
}
.base-text {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 22rpx;
  color: #9EA9BB;
  line-height: 20rpx;
  text-align: center;
  font-style: normal;
}
.checked {
	color: #060809;
}
</style>