<template>
  <!-- #ifdef H5 -->
  <zj-page-layout>
    <view class="tab-container">
      <view class="tab-fixed">
        <scroll-view
          :scroll-x="true"
          :scroll-left="scrollLeft"
          scroll-with-animation
          :show-scrollbar="false"
          class="tabs-view"
          ref="tabs-view"
        >
          <view class="tab">
            <block v-for="(item, index) in tabList" :key="index">
              <view
                class="item"
                :ref="`tabs-item-${index}`"
                :class="[`tabs-item-${index}`, item.id == tabCurrent ? 'current' : '']"
                @tap="changeTab(item.id)"
                >{{ item.name }}</view
              >
            </block>
          </view>
        </scroll-view>
      </view>
    </view>

    <view class="card">
      <view class="row">
        <view class="left">选择品牌</view>
        <view class="right">
          <picker v-model="brand" mode="selector" :range="brandList" range-key="brandName" @change="changeBrand">
            <view class="picker">
              <view v-if="brand >= 0">{{ brandList[brand].brandName }}</view>
              <view v-else style="color: #666666">请选择</view>
              <text class="iconfont icon-arrow_right"></text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <view class="card">
      <view class="row" @tap.stop="chooseClassify">
        <view class="left">选择产品品类</view>
        <view class="right">
          <view v-if="smallName">{{ mainName }}-{{ smallName }}</view>
          <view v-else style="color: #666666">请选择</view>
          <text class="iconfont icon-arrow_right"></text>
        </view>
      </view>
    </view>

    <view class="main-container">
      <view class="title">收费标准</view>
      <view class="content">
        <image v-if="imgUrl" :src="imgUrl" mode="widthFix" @tap="previewImg()"></image>
        <Loading
          v-if="!imgUrl"
          :type="3"
          :loadStatus="2"
          :showText="isSearch ? '暂无收费标准' : '请选择条件进行查询'"
        />
      </view>
    </view>
  </zj-page-layout>
  <!-- #endif -->
  <!-- #ifndef H5 -->
  <web-view
    :src="webViewHref(`/packageHome/pages/service/chargeStandard`, pam, crossPagePam)"
    @message="crossPage.$listener"
  ></web-view>
  <!-- #endif -->
</template>

<script>
 // #ifdef H5
export default {
	data() {
		return {
			tabList: [], // 分类列表
			tabCurrent: '', // 分类当前值
			scrollLeft: 50,
			scrollViewWidth: 0,
			tabsRect: {
				left: 0
			},

			brand: '0',
			mainId: '',
			mainName: '',
			smallId: '',
			smallName: '',

			brandList: [],
			isSearch: false,
			imgUrl: '',
		}
	},

	watch: {
		tabList() {
			this.$nextTick(() => {
				this.resize()
			})
		},
	},

	onLoad() {
		this.getTabList();
		this.getBrandList();

		this.crossPage.$on('chooseClassify', res => {
			this.mainId = res.pid;
			this.mainName = res.pname;
			this.smallId = res.cid;
			this.smallName = res.cname;
			this.getList();
		})
	},

	methods: {
		getList() {
			if(this.tabCurrent && this.brand >= 0 && this.smallId) {
				this.$api.get('/charging/list', {
           type: 1,
           pageNum: 1,
           pageSize: 1,
           chargingStandardTypeId: this.tabCurrent,
           brandId: this.brandList[this.brand].id,
           twoCategoryId: this.smallId
				}).then(res => {
					if(res.data.records && res.data.records.length > 0) {
						this.imgUrl = res.data.records[0].imageUrl;
					}else {
						this.imgUrl = '';
					}
					this.isSearch = true;
				})
			}
		},

		// 获取品牌列表
		getBrandList() {
			this.$api.get('/charging/brand/list')
       .then(res => {
				this.brandList = res.data;
			})
		},

		// 获取一级菜单
		getTabList() {
			this.$api.get('/charging/type/list')
       .then(res => {
				this.tabList = res.data;
				this.tabCurrent = res.data.length > 0 ? res.data[0].id : 0;
				this.getList();
			})
		},

		// 切换一级菜单
		changeTab(current) {
			this.pageNum = 1;
			this.tabCurrent = current;
			this.resize();
			this.getList();
		},

		chooseClassify() {
			this.$navToPage({
				url: '/packageHome/pages/service/classify'
			})
		},

		changeBrand(e) {
			this.brand = e.detail.value;
			console.log(e.detail.value);
			this.getList();
		},

		setScrollLeft() {
			// 当前活动tab的布局信息，有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
			const index = this.findElem(this.tabList, 'id', this.tabCurrent);
			const tabRect = this.tabList[index]
			// 累加得到当前item到左边的距离
			const offsetLeft = this.tabList
				.slice(0, index)
				.reduce((total, curr) => {
					return total + curr.rect.width
				}, 0)
			// 此处为屏幕宽度
			const res = uni.getSystemInfoSync();
			const windowWidth = res.windowWidth;
			// 将活动的tabs-item移动到屏幕正中间，实际上是对scroll-view的移动
			let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect.right) / 2 + this.tabsRect.left / 2

			// 这里做一个限制，限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
			scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width)
			this.scrollLeft = Math.max(0, scrollLeft)
		},
		// 获取所有标签的尺寸
		resize() {
			// 如果不存在list，则不处理
			if(this.tabList.length === 0) {
				return
			}
			Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
				this.tabsRect = tabsRect
				this.scrollViewWidth = 0
				itemRect.map((item, index) => {
					// 计算scroll-view的宽度，这里
					this.scrollViewWidth += item.width
					// 另外计算每一个item的中心点X轴坐标
					this.tabList[index].rect = item
				})
				// 获取了tabs的尺寸之后，设置滑块的位置
				this.setScrollLeft()
			})
		},
		// 获取导航菜单的尺寸
		getTabsRect() {
			return new Promise(resolve => {
				this.queryRect('tabs-view').then(size => resolve(size))
			})
		},
		// 获取所有标签的尺寸
		getAllItemRect() {
			return new Promise(resolve => {
				const promiseAllArr = this.tabList.map((item, index) => this.queryRect(
					`tabs-item-${index}`, true))
				Promise.all(promiseAllArr).then(sizes => resolve(sizes))
			})
		},
		// 获取各个标签的尺寸
		queryRect(el, item) {
			const query = uni.createSelectorQuery().in(this);
			return new Promise(resolve => {
				query.select(`.${el}`).boundingClientRect(data => {
					resolve(data)
				}).exec();
			})
		},

		findElem(array, attr, val) {
		    for (var i = 0; i < array.length; i++) {
		        if (array[i][attr] == val) {
		            return i; //返回当前索引值
		        }
		    }
		    return -1;
		},

		previewImg() {
			uni.previewImage({
				urls: [this.imgUrl]
			})
		}
	}
}
 // #endif
 // #ifndef H5
 export default {
   data() {
     return {
       pam: {},
     }
   },

   onLoad(pam) {
     this.pam = pam;
   },
 }
 // #endif
</script>

<style scoped lang="scss">
.tab-container {
  height: 80rpx;
  .tab-fixed {
    display: flex;
    background: #ffffff;
    .tab {
      display: flex;
      margin-left: -10rpx;
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex-shrink: 0;
        font-size: 28rpx;
        color: #666666;
        height: 80rpx;
        line-height: 80rpx;
        position: relative;
        padding: 0 30rpx;
        &.current {
          color: $theme-color;
          font-weight: 600;
          &::after {
            content: '';
            display: block;
            width: 50rpx;
            height: 6rpx;
            background: $theme-color;
            position: absolute;
            bottom: 0;
            left: 50%;
            margin-left: -25rpx;
          }
        }
      }
    }
  }
}

.card {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 0;
  .row {
    border-bottom: 1px solid #f4f2f2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    min-height: 88rpx;
    box-sizing: border-box;
    &:last-child {
      border: none;
    }
    .left {
      font-size: 28rpx;
      color: #333333;
      flex-shrink: 0;
    }
    .right {
      flex: 1;
      margin-left: 40rpx;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .iconfont {
        color: #999999;
      }
      input,
      textarea {
        width: 100%;
        font-size: 28rpx;
        text-align: right;
      }
      picker {
        flex: 1;
      }
      .picker {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        flex: 1;
      }
      image {
        width: 16rpx;
        height: 28rpx;
        margin-left: 10rpx;
      }
    }
  }
}
.main-container {
  margin-top: 40rpx;
  .title {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 20rpx;
    padding: 0 20rpx;
  }
  .content {
    img,
    image {
      width: 100%;
      display: block;
    }
  }
}
</style>
