<template>
  <TabBarPage title="订单" :fixed="true" @click="goTop">
    <view class="tools-box">
      <view class="search-sub">
        <u-subsection
          :current="curNow"
          :list="subList"
          active-color="white"
          bg-color="white"
          inactive-color="#666"
          button-color="#2272FF"
          border-radius="36"
          @change="sectionChange"
          height="72"
          bold
        >
        </u-subsection>
      </view>
      <view class="search-btn" @click="handleClickSearch">
        <image class="search-image" mode="widthFix" :src="sousuoImage"></image>
        <text class="search-btn-text">搜订单</text>
      </view>
    </view>
    <view class="u-tabs-box">
      <!-- 写两个是避免切换subsection时候，current不是0的时候底部蓝条有初始动画 -->
      <view v-for="index of [0, 1]" :key="index">
        <u-tabs
          v-show="curNow == index"
          height="66"
          activeColor="#2272FF"
          bg-color="none"
          inactive-color="#999"
          bar-height="4"
          bar-width="44"
          :offset="offset[index]"
          :list="list[index]"
          count="total"
          :current="current[index]"
          @change="change"
          :is-scroll="false"
          font-size="28"
          bold
        ></u-tabs>
      </view>
    </view>

    <view class="tab-view">
      <scroll-view
        scroll-y
        style="height: 100%;width: 100%;"
        @scrolltolower="reachBottom"
        scroll-anchoring
        refresher-enabled="true"
        :refresher-triggered="triggered"
        :refresher-threshold="100"
        :scroll-top="scrollTop"
        refresher-background="#F4F5F7"
        @refresherrefresh="onRefresh"
        @refresherrestore="onRestore"
        @scroll="scroll"
        enable-back-to-top
      >
        <NoOrder
          v-if="noMore"
          imageName="zwdd.png"
          :customStyle="noOrderCustomStyle"
        />
        <template v-else>
          <view
            v-for="item in orderList[curNow][current[curNow]]"
            :key="item.orderId"
          >
            <OrderCell
              :orderData="item"
              :type="cellType"
              :location="dataValue"
              @click="handleClick"
              @action="handleClickCellButton"
            >
            </OrderCell>
          </view>
          <view
            class="load-more-view"
            v-show="(pageNumber == 1 && loaded) || pageNumber > 1"
          >
            <u-loadmore :status="loadStatus" bgColor="#F4F5F7"></u-loadmore>
          </view>
        </template>
        <view class="loading-view" v-if="!loaded && !_freshing">
          <u-loading mode="flower"></u-loading>
        </view>
      </scroll-view>
    </view>
    <!-- 悬浮按钮 -->
    <!-- <EusingList type="collapse" /> -->
    <MaskTip
      :show="showMask"
      imageName="mengceng1.png"
      :imageStyle="imageStyle"
      name="today_tip"
    />
  </TabBarPage>
</template>

<script>
import TabBarPage from '@/components/tabBarList/index.vue'
import OrderCell from '@/components/order/index.vue'
import NoOrder from '@/components/order/noOrder.vue'
import upload from '@/components/upload/task.js'
import MaskTip from '@/components/mask-tip/index.vue'

// import EusingList from '@/components/order/eusingList.vue'

export default {
  components: {
    TabBarPage,
    OrderCell,
    NoOrder,
    MaskTip,
    // EusingList,
  },
  data() {
    return {
      curNow: 0,
      pageNumber: 0,
      orderList: [
        // 用多个数组存储可以优化用户切换体验，但是会增加内存
        [[], [], [], [], [], []],
        [[], [], []],
      ],
      list: [
        [
          {
            name: '待预约',
            total: 0,
          },
          {
            name: '待签到',
            total: 0,
          },
          {
            name: '待完工',
            total: 0,
          },
          {
            name: '审核中',
            total: 0,
          },
          {
            name: '异常单',
            total: 0,
          },
          {
            name: '已完工',
            total: 0,
          },
        ],
        [
          {
            name: '待联系',
            total: 0,
          },
          {
            name: '待完工',
            total: 0,
          },
          {
            name: '异常单',
            total: 0,
          },
        ],
      ],
      current: { 0: 0, 1: 0 },
      loadStatus: 'loading',
      dataValue: [],
      loaded: false,
      triggered: true,
      _freshing: false,
      scrollTop: 0,
      old: {
        scrollTop: 0,
      },
      showMask: false,
    }
  },
  computed: {
    subList() {
      return ['全部订单', '今日订单']
    },
    // 0 全部订单: 0:'待预约', 1:'待签到', 2:'待完工', 3:'审核中', 4:'异常单', 5'已完工'
    // 1 今日订单: 0:'今日待联系', 1:'今日待完工', 2:'今日异常单'
    orderType() {
      return this.indexStatus[this.curNow][this.current[this.curNow]]
    },
    pageSize() {
      // 待预约, 待签到，待完工，因为需要排序，所以暂时去掉分页，一次要完所有
      return this.pageSizes[this.curNow][this.current[this.curNow]]
    },
    needSort() {
      // 待预约, 待签到，待完工需要排序
      return this.curNow + this.current[this.curNow] < 3
    },
    pageSizes() {
      // 待预约, 待签到，待完工，因为需要排序，所以暂时去掉分页，一次要完所有
      return [
        [10000, 10000, 10000, 15, 15, 15],
        [10000, 10000, 15],
      ]
    },
    offset() {
      return [
        [0, 0],
        [0, 44],
      ]
    },
    sousuoImage() {
      return process.uniEnv.qn_base_url + 'sousuo.png'
    },
    // 每一种状态对应的tab的index
    types() {
      return [
        {
          waitAppointment: 0, // 待预约、
          waitCheckIn: 1, // 待签到、
          waitFinish: 2, // 待完工、
          audit: 3, // 审核中、
          exception: 4, // 异常单、
          finish: 5, //已完工
        },
        {
          todayWaitContact: 0, // 今日待联系、
          todayWaitFinish: 1, // 今日待完工、
          todayException: 2, // 今日异常单、
        },
      ]
    },
    // 每一个tab对应的状态
    indexStatus() {
      return [
        [
          'waitAppointment',
          'waitCheckIn',
          'waitFinish',
          'audit',
          'exception',
          'finish',
        ],
        ['todayWaitContact', 'todayWaitFinish', 'todayException'],
      ]
    },
    // 订单数量接的返回数量的key
    countKeys() {
      return [
        [
          'toAppointmentCount',
          'toCheckinCount',
          'toFinishCount',
          'reviewingCount',
          'exceptionCount',
          '', // 待完工没有数量
        ],
        ['todayContactCount', 'todayFinishCount', 'todayExceptionCount'],
      ]
    },
    isFinish() {
      return this.orderType == 'finish'
    },
    noMore() {
      return (
        this.orderList[this.curNow][this.current[this.curNow]].length == 0 &&
        this.loaded
      )
    },
    cellTypes() {
      return [
        [
          'waitAppointment',
          'waitCheckIn',
          'waitFinish',
          'audit',
          'exception',
          'finish',
        ],
        ['', 'waitFinish', 'exception'],
      ]
    },
    // 仅用于传给OrderCell的type
    cellType() {
      return this.cellTypes[this.curNow][this.current[this.curNow]]
    },
    noOrderCustomStyle() {
      return 'margin-top: 100rpx;background-color: #F4F5F7'
    },
    imageStyle() {
      return  'width:546rpx; margin-top:80rpx; margin-left:100rpx'
    }
  },
  onLoad(e) {
    getApp().trackPage('订单首页')
    this._freshing = false
    // 跳转到本页是否带了跳到那个tab的参数
    if (e && e.type) {
      this.current[this.curNow] = Math.max(
        0,
        this.indexStatus[this.curNow].indexOf(e.type)
      )
    }
  },
  onShow() {
    if (this.uploadTask.length > 0) {
      upload.uploadImageTask(this)
    }
    this.reloadOrderInfo()
  },
  methods: {
    sectionChange(index) {
      this.curNow = index
      this.reloadOrderList()
    },
    // tab栏切换
    change(index) {
      this.current[this.curNow] = index
      this.reloadOrderList()
    },
    // 滚动底部
    reachBottom(e) {
      if (this.loadStatus != 'loadmore') return
      this.loadStatus == 'loading'
      this.getOrderList()
    },
    // 页面数据
    getOrderList() {
      // 状态处理
      this.pageNumber += 1
      if (this.pageNumber == 1) {
        this.loaded = false
      }
      var param = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        keyword: '',
        type: this.orderType,
      }
      var self = this
      self.$u.api.listOrder(param).then((res) => {
        if (res.code == 200) {
          if (res.data.type != self.orderType) return // 已切换到其他tab，则不处理后台返回的数据

          if (self.pageNumber == 1) {
            // 下拉刷新或切换到新tab，清空对应数组
            self.orderList[this.curNow][this.current[this.curNow]] = []
          }
          if (res.data.list) {
            self.orderList[this.curNow][this.current[this.curNow]].push(
              ...res.data.list
            )
            // 更新tab数字
            if (
              !this.isFinish &&
              self.list[this.curNow][self.types[this.curNow][res.data.type]]
            ) {
              self.list[this.curNow][
                self.types[this.curNow][res.data.type]
              ].total = res.data.total
            }
            // 待预约, 待签到，待完工需要排序
            if (this.needSort) {
              self.orderList[this.curNow][this.current[this.curNow]].sort(
                (x, y) => {
                  return x.currentOverTime < y.currentOverTime ? 1 : -1
                }
              )
            }
            // 更新底部加载状态
            self.loadStatus =
              res.data.total >
                self.orderList[this.curNow][this.current[this.curNow]].length &&
              res.data.list.length == self.pageSize
                ? 'loadmore'
                : 'nomore'
          }
        } else {
          console.log(res.message, '获取订单数量失败！')
        }
        self.$nextTick(() => {
          if (self._freshing) {
            self.triggered = false
            self._freshing = false
          }
        })
        this.loaded = true
      })
    },

    // 获取订单数量
    getOrderCount() {
      this.$u.api.listOrderCount().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            // 修改各个tab数量
            var j = 0
            var count = 0
            for (var items of this.list) {
              var i = 0
              for (var item of items) {
                item.total = res.data[this.countKeys[j][i]] || 0
                if (j == 0) {
                  // 非今日订单数量加起来
                  count += item.total
                }
                i++
              }
              j++
            }
            // 修改tab总数
            if (count > 0) {
              uni.setTabBarBadge({
                index: 1,
                text: String(count),
              })
            } else {
              uni.removeTabBarBadge({
                index: 1,
              })
            }
          }
        } else {
          console.log(res.message, '获取订单数量失败！')
        }
      })
    },
    handleClickCellButton(item) {
      if (!this.loaded) return
      uni.navigateTo({
        url:
          'pages/order/complete?orderId=' +
          item.orderId +
          '&categoryId=' +
          item.categoryId +
          '&orderServiceType=' +
          item.orderServiceType +
          '&inGuaranteePeriod=' +
          item.inGuaranteePeriod +
          '&partnerCompanyId=' +
          item.partnerCompanyId +
          '&maintainStep=' +
          item.maintainStep +
          '&orderStatus=' +
          item.orderStatus +
          '&brandId=' +
          item.lianbaoBrandId +
          '&auditResults=' +
          (item.auditResults ? item.auditResults.join() : '') +
          '&orderNumber=' +
          item.orderNumber,
      })
    },
    handleClick(item, type, showCountTime) {
      if (!this.loaded) return
      // type:类型，showCountTime：是否显示倒计时。详情页面情况太多，提前传值可以避免页面晃动
      //type类型
      // 'waitAccept': 待接单、待抢单;'waitAppointment': 待预约;'waitCheckIn': 待签到;'waitFinish': 待完工;'audit': 审核中;'exception': 异常单;'finish': 已完工;'other': 工单结算信息
      uni.navigateTo({
        url:
          'pages/order/detail?id=' +
          item.orderId +
          '&type=' +
          type +
          '&showCountTime=' +
          showCountTime,
      })
    },
    handleClickSearch() {
      uni.navigateTo({
        url: 'pages/order/search',
      })
    },
    onRefresh() {
      if (this._freshing) return
      this._freshing = true
      this.reloadOrderInfo()
    },
    onRestore() {
      this.triggered = 'restore' // 需要重置
    },
    reloadOrderInfo() {
      this.reloadOrderList()
      this.getOrderCount()
    },
    reloadOrderList() {
      this.pageNumber = 0
      this.loadStatus = 'loading'
      this.getOrderList()
    },
    scroll(e) {
      this.old.scrollTop = e.detail.scrollTop
    },
    goTop(e) {
      this.scrollTop = this.old.scrollTop
      this.$nextTick(function() {
        this.scrollTop = 0
      })
    },
    // 显示提示蒙版
    showMaskTip() {
      this.showMask = true
    },
  },
}
</script>

<style lang="scss" scoped>
.u-tabs-box {
  margin-bottom: 30rpx;
}
.tab-view {
  height: 100%;
  overflow: auto;
  .load-more-view {
    padding-bottom: 44rpx;
  }
  .loading-view {
    width: 100%;
    background-color: transparent;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 50%;
    left: 0;
    position: fixed;
  }
}

.tools-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-bottom: 18rpx;

  .search-sub {
    height: 72rpx;
    width: 320rpx;
  }

  .search-btn {
    height: 72rpx;
    width: 220rpx;
    background-color: #ffffff;
    border-radius: 36rpx;
    color: #999999;
    display: flex;
    justify-content: center;
    align-items: center;

    .search-image {
      width: 36rpx;
      height: 32rpx;
      flex-shrink: 0;
      margin-right: 24rpx;
    }

    .search-btn-text {
      line-height: 36rpx;
      font-weight: 400;
      font-size: 26rpx;
    }
  }
}
</style>
