<template>
  <TabBarPage title="扳手会" :fixed="true" @click="goTop">
    <view class="content-view">
      <scroll-view
        style="height: 100%;"
        scroll-y
        @scrolltolower="reachBottom"
        :scroll-top="scrollTop"
        @scroll="scroll"
        scroll-anchoring
        refresher-enabled="true"
        :refresher-triggered="triggered"
        :refresher-threshold="100"
        refresher-background="#F4F5F7"
        @refresherrefresh="onRefresh"
        @refresherrestore="onRestore"
        enable-back-to-top
      >
        <image
          class="banner-image"
          :src="bannerImage"
          @click="handleClickBanner"
        ></image>

        <view class="msg-view">
          <view class="msg-title">最新消息</view>
          <view class="msg-list-view">
            <view
              class="msg-content"
              v-for="(item, index) in messageList"
              :key="index"
              @click="toNewsDetail(item)"
            >
              <view class="msg-content-view">
                <view class="left-view">
                  <image
                    class="msg-icon"
                    :src="msgStyleImage[item.is_top]"
                  ></image>
                  <text class="msg-text">{{ item.title }}</text>
                </view>
                <image class="right-icon" :src="shouyeyouImage"></image>
              </view>
              <view class="line-view" v-if="index != 1"></view>
            </view>
          </view>
        </view>
        <view class="sticky">
          <text>订单推荐</text>
        </view>
        <view class="order-view">
          <!-- 入驻成功之后显示推荐订单列表 -->
          <view class="order-list-view" v-if="loaded">
            <!-- 入驻前-->
            <view v-if="needSettled" class="tip-view">
              <image :src="weiruzhuImage" class="tip-view-image"></image>
              <view class="tip-other">入驻后平台将向您分配或推荐订单</view>
              <u-button
                class="settle-button"
                type="primary"
                shape="circle"
                @click="immediatelyIn"
                :custom-style="buttonStyle"
              >
                立即入驻
              </u-button>
            </view>
            <template v-else>
              <!-- 入驻成功之后无推荐订单 -->
              <view
                v-if="orderList.length <= 0 && loadedOrder"
                class="no-order-view"
              >
                <NoOrder />
              </view>
              <view v-else-if="orderList.length > 0" class="order-item-view">
                <view v-for="(item, index) in orderList" :key="index">
                  <OrderCell
                    :orderData="item"
                    type="waitAccept"
                    :location="location"
                    @click="handleClick"
                    @action="handleClick"
                  >
                  </OrderCell>
                </view>
                <view
                  class="load-more-view"
                  v-show="
                    (search.pageNumber == 1 && loadedOrder) ||
                      search.pageNumber > 1
                  "
                >
                  <u-loadmore
                    :status="currentLoadStatus"
                    bgColor="#F4F5F7"
                  ></u-loadmore>
                </view>
              </view>
            </template>
          </view>
        </view>
        <view class="bottom-view" v-if="needSettled || orderList.length <= 0">
          <view class="bottom-line-view"></view>
          <view class="bottom-text">我也是有底线哒</view>
          <view class="bottom-line-view"></view>
        </view>
      </scroll-view>
      <!-- 悬浮按钮 -->
      <!-- <EusingList /> -->
    </view>
    <upload-progress />
    <MaskTip
      :show="showMask"
      imageName="mengceng2.png"
      :imageStyle="imageStyle"
      name="upload_tip"
    />
  </TabBarPage>
</template>

<script>
import TabBarPage from '@/components/tabBarList/index.vue'
import NoOrder from '@/components/order/noOrder.vue'
import MaskTip from '@/components/mask-tip/index.vue'
const app = getApp()
import OrderCell from '@/components/order/index.vue'
// import EusingList from '@/components/order/eusingList.vue'

export default {
  components: {
    OrderCell,
    TabBarPage,
    NoOrder,
    MaskTip,
    // EusingList,
  },
  data() {
    return {
      status: 0, // 入驻状态:0=>'待提交',1=>'待审核',2=>'已通过',3=>'备选',4=>'已驳回',6=>'已签约',7=>'已支付保证金',8=>'已通过考试',9=>'待提交'
      location: [], // 经纬度
      title: false,
      title: 'Hello',
      loaded: false,
      loadedOrder: false,
      needSettled: false,
      count: 0, // 推荐订单数量
      messageList: [],
      currentLoadStatus: 'loading',
      orderList: [],
      search: {
        token: '',
        pageNumber: 0,
        pageSize: 15,
      },
      waitInit: false, // 当token为空时，等待自动登录结束
      triggered: true,
      scrollTop: 0,
      old: {
        scrollTop: 0,
      },
      showMask: false,
    }
  },
  watch: {
    vuex_token(val, oldVal) {
      // 监听token变化，如果更新则重新加载页面数据
      val && this.waitInit && this.getData()
    },
  },
  computed: {
    buttonStyle() {
      return {
        width: '300rpx',
        height: '80rpx',
        'font-size': '32rpx',
        'font-weight': 'bold',
      }
    },
    countKeys() {
      return [
        'toAppointmentCount',
        'toCheckinCount',
        'toFinishCount',
        'reviewingCount',
        'exceptionCount',
      ]
    },
    msgStyleImage() {
      return {
        '1': process.uniEnv.qn_base_url + 'zhiding.png', // 置顶
        '0': process.uniEnv.qn_base_url + 'tongzhi.png', // 通知
        // '3': process.uniEnv.qn_base_url + "xiaoxi.png", // 消息
      }
    },
    bannerImage() {
      return process.uniEnv.qn_base_url + 'banner-1.png'
    },
    shouyeyouImage() {
      return process.uniEnv.qn_base_url + 'shouyeyou.png'
    },
    weiruzhuImage() {
      return process.uniEnv.qn_base_url + 'weiruzhu.png'
    },
    imageStyle() {
      return  'width:628rpx; margin-top:816rpx; margin-left:122rpx'
    }
  },
  onLoad(e) {
    app.trackPage('自营平台首页')
    this._freshing = false
    if (this.vuex_token) {
      this.getOrderCount()
    } else {
      this.waitInit = true
    }
    this.showMaskTip()
  },
  onShow() {
    // 每次进入页面都刷新入驻状态
    this.pageNumber = 0

    this.initSettleInfo()
  },
  methods: {
    getData() {
      this.getOrderCount()
      this.initSettleInfo()
    },
    handleClick(item, type, showCountTime) {
      // 跳转工单详情页面 showCountTime：是否显示倒计时
      // type类型
      // 'waitAccept': 待接单、待抢单;'waitAppointment': 待预约;'waitCheckIn': 待签到;'waitFinish': 待完工;'audit': 审核中;'exception': 异常单;'finish': 已完工;'other': 工单结算信息
      uni.navigateTo({
        url:
          'pages/order/detail?id=' +
          item.orderId +
          '&type=' +
          type +
          '&showCountTime=' +
          showCountTime,
      })
    },
    async initSettleInfo() {
      let self = this
      // 加载消息列表
      this.loadMessageList()
      if (this.vuex_token) {
        const callBack = (vm, result) => {
          // 后台自动判断入驻流程是否完成，前台通过status确定状态
          if (result && result.record) {
            // 不返回该字段或返回true代表需要入驻
            vm.needSettled = result.needSettled == undefined ? true : result.needSettled
            vm.status = Number(result.record.status || '0')
            // vm.status = 8
          }
        }
        self.search.pageNumber = 0
        self.loadedOrder = false
        await app.getBaseInfo(self, callBack)
        if (this.status == 7) {
          this.getLocation()
          self.loadOrderList()
        }
        this.loaded = true
      } else {
        this.loaded = true
      }
    },
    loadMessageList() {
      let self = this
      self.$u.api.listByNotice().then((res) => {
        uni.stopPullDownRefresh() // 结束下拉刷新
        if (res.code == 200) {
          if (res.data && res.data.length > 2) {
            self.messageList = res.data.slice(0, 2)
          } else {
            self.messageList = res.data || []
          }
        } else {
          console.log(res.message, '初始化消息列表异常')
        }
      })
    },
    async loadOrderList() {
      this.search.pageNumber += 1
      let self = this
      // 加载订单列表
      self.search.token = self.vuex_token
      self.$u.api.listByRecommendOrder(self.search).then((res) => {
        self.loadedOrder = true

        if (res.code == 200 && res.data) {
          if (self.search.pageNumber == 1) {
            self.orderList = []
          }
          if (res.data.list) {
            // self.orderList.push(...res.data.list)

            // 更新每一条时间戳，防止后台返回的数据和原先一样，不触发ordercell的时间计算
            var time = new Date().getTime()
            for (var item of res.data.list) {
              item.currentCellTime = time
              self.orderList.push(item)
            }
          }

          self.currentLoadStatus =
            res.data.total > self.orderList.length &&
            (res.data.list || []).length == self.search.pageSize
              ? 'loadmore'
              : 'nomore'
        } else {
          console.log(res.message, '初始化订单列表异常')
        }
        self.$nextTick(() => {
          if (self._freshing) {
            self.triggered = false
            self._freshing = false
          }
        })
      })
    },
    reachBottom() {
      if (this.vuex_token) {
        if (this.currentLoadStatus != 'loadmore') return
        this.currentLoadStatus == 'loading'
        this.loadOrderList()
      }
    },
    onRefresh() {
      if (this._freshing) return
      this._freshing = true
      this.initSettleInfo()
    },
    onRestore() {
      this.triggered = 'restore' // 需要重置
    },
    scroll(e) {
      this.old.scrollTop = e.detail.scrollTop
    },
    goTop(e) {
      this.scrollTop = this.old.scrollTop
      this.$nextTick(function() {
        this.scrollTop = 0
      })
    },
    /* 立即入驻 */
    immediatelyIn() {
      if (this.vuex_token) {
        // 用户已登录
        var pageIndex = 1
        // 0=>'待提交',1=>'待审核',2=>'已通过',3=>'备选',4=>'已驳回',5=>'已签约',6=>'未支付保证金',7=>'已支付保证金',8=>'已通过考试',9=>'待提交'
        switch (this.status) {
          case 1:
          case 2:
          case 3:
          case 4:
            pageIndex = 2
            break
          case 8:
            pageIndex = 3
            break
          case 5:
          case 6:
            pageIndex = 4
            break
          case 7:
            pageIndex = 5
            break
          default:
            pageIndex = 1
            break
        }

        uni.navigateTo({
          url:
            this.status > 0
              ? '/pages/settle/prompt?pageIndex=' + pageIndex
              : '/pages/settle/index',
        })
      } else {
        // 用户未登录
        uni.navigateTo({
          url: 'pages/login/index',
        })
      }
    },
    // 获取订单数量
    getOrderCount() {
      var self = this // 加载订单列表
      self.$u.api.listOrderCount().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            var count = 0
            for (var item of this.countKeys) {
              count += res.data[item] || 0
            }
            // 修改tab总数
            if (count > 0) {
              uni.setTabBarBadge({
                index: 1,
                text: String(count),
              })
            } else {
              uni.removeTabBarBadge({
                index: 1,
              })
            }
          }
        } else {
          console.log(res.message, '获取订单数量失败！')
        }
      })
    },
    /**
     * 获取当前位置的经纬度
     */
    getLocation() {
      let self = this
      uni.getLocation({
        type: 'gcj02',
        success: function(res) {
          self.location = [res.latitude, res.longitude]
        },
        complete: function(res) {
          if (res.errMsg.indexOf('auth') != -1) {
            uni.showModal({
              title: '提示',
              content: '获取权限失败，请到设置页面开启权限',
              confirmText: '好的',
              success(res) {
                if (res.confirm) {
                  uni.openSetting({
                    success(res) {
                      console.log(res.authSetting)
                    },
                  })
                }
              },
            })
          }
        },
        fail: function(err) {},
      })
    },
    toNewsDetail(item) {
      wx.navigateTo({
        url: '/pages/learn/news-details',
        success: function(res) {
          res.eventChannel.emit('acceptDataFromLearn', item)
        },
      })
    },
    handleClickBanner() {
      uni.navigateTo({
        url: '/pages/mine/customer/index' + '?type=exclusive',
      })
    },
    // 显示提示蒙版
    showMaskTip() {
      this.showMask = true
    },
  },
}
</script>

<style lang="scss" scoped>
.banner-image {
  width: 730rpx;
  height: 280rpx;
  margin-left: -16rpx;
}
.content-view {
  height: 100%;
  overflow: auto;
}

.msg-view {
  .msg-title {
    color: #333333;
    font-size: 32rpx;
    font-weight: bold;
    padding: 1rpx 0rpx 30rpx 0rpx;
  }

  .msg-list-view {
    border-radius: 12rpx;
    background-color: #ffffff;
    padding: 12rpx 30rpx;
    height: 174rpx;
  }

  .msg-content {
    color: #333333;
    font-size: 26rpx;

    .msg-content-view {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20rpx;
      margin-bottom: 20rpx;

      .left-view {
        display: flex;
        align-items: center;

        .msg-icon {
          width: 80rpx;
          height: 36rpx;
          margin-right: 20rpx;
        }

        .msg-text {
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          width: 448rpx;
        }
      }

      .right-icon {
        width: 14rpx;
        height: 24rpx;
      }
    }

    .line-view {
      height: 2rpx;
      background-color: #f4f5f7;
    }
  }
}

.logo {
  height: 200 rpx;
  width: 100%;
  margin: 0 rpx auto 50 rpx auto;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36 rpx;
  color: #8f8f94;
}

// .sticky-view {
// 	position: sticky;
// 	position: -webkit-sticky;
// 	top: 0rpx;
// 	width: 100%;
// 	height: 200rpx;
// 	background-color: black;
// }

.sticky {
  background-color: #f4f5f7;
  color: #fff;
  padding: 24 rpx;
  text-align: left;
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  padding: 46rpx 0 28rpx 0;
}

.order-view {
  text-align: center;

  .order-list-view {
    .tip-view {
      padding: 30rpx;
      background-color: #ffffff;
      border-radius: 12rpx;
      min-height: 460rpx;

      .tip-view-image {
        width: 328rpx;
        height: 200rpx;
        margin-top: 30rpx;
      }

      .tip-other {
        font-size: 28rpx;
        color: #666666;
        margin-bottom: 30rpx;
      }

      .settle-button {
      }
    }

    .order-item-view {
      background-color: #f4f5f7;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      .load-more-view {
        padding-bottom: 44rpx;
      }
    }
  }
}

.bottom-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 50rpx 40rpx 50rpx 40rpx;

  .bottom-line-view {
    background-color: #d5d5d5;
    height: 2rpx;
    width: 30%;
  }

  .bottom-text {
    color: #999999;
    font-size: 24rpx;
  }
}
.fixed-button {
  position: fixed;
  right: 10rpx;
  bottom: 64rpx;
}
</style>
