<template>
  <view>
    <zj-page-layout
      :hasFooter="false"
      :isScroll="true"
      :refresherTriggered="refresherTriggered"
      @refresherrefresh="refresherrefresh"
      @scrolltolower="scrolltolower"
    >
      <template slot="header">
        <view class="top-container">
          <scroll-view class="tab-scroll-view" scroll-x scroll-with-animation :scroll-left="scrollLeft">
            <view class="left-nav">
              <view
                class="item"
                v-for="(item, index) in mainTabs"
                :key="index"
                :class="[curMainTab === item.value ? 'active' : '', 'tab-item-' + index]"
                @tap="changeMainTab(item.value)"
              >
                <view class="name">{{ item.name }}</view>
                <view class="num">{{ item.num || '' }}</view>
              </view>
            </view>
          </scroll-view>

          <view class="right-search">
            <u-icon name="search" color="#ffffff" size="28" @tap="toSearchPage()"></u-icon>
          </view>
        </view>
      </template>

      <view>
        <view class="status-container">
          <u-tabs
            :list="smallTabs"
            @change="changeSmallTab"
            :current="curSmallTabIndex"
            lineWidth="0"
            lineHeight="0"
            activeStyle="height: 68rpx; display: flex; align-items: center; justify-content: center; padding: 0 24rpx; border-radius: 24rpx; background: #E7EFFF; color: #3D8FFD; border: 1px solid #3D8FFD; box-sizing: border-box;"
            inactiveStyle="height: 68rpx; display: flex; align-items: center; justify-content: center; padding: 0 24rpx; border-radius: 24rpx; border: 1px solid #eaeaea; box-sizing: border-box;"
            itemStyle="padding: 0; border-radius: 24rpx; color: #999999; margin-right: 16rpx; font-size: 28rpx;"
          >
          </u-tabs>

          <view class="date" :class="startDate ? 'active' : ''" @tap="isShowDatePicker = true">
            <view class="text">按日期</view>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>

        <view class="order-list-container">
          <view class="item" v-for="(item, index) in dataList" :key="index" @tap="toDetail(item.id)">
            <view class="item-top">
              <view class="left">
                <view class="title" v-if="item.orderSmallTypeText">
                  {{ item.orderSmallTypeText.slice(0, 2) }}
                </view>
                <view class="tags">
                  <view class="tag red_solid" v-for="(it, idx) in item.orderFlags" :key="idx">{{ it.tagName }}</view>
                </view>
              </view>
              <view class="status">{{ item.orderStatusText }}</view>
            </view>
            <view class="item-main">
              <view class="row">
                <view class="label">服务单号</view>
                <view class="value">
                  <view class="val">{{ item.id }}</view>
                </view>
              </view>
              <view class="row" v-if="item.appointmentTime">
                <view class="label">预约时间</view>
                <view class="value">
                  <view class="val">{{ item.appointmentTime.slice(0, 10) }}</view>
                </view>
              </view>
              <view class="row">
                <view class="label">服务项目</view>
                <view class="value">
                  <view class="val">{{
                    item.pgOrderProducts.map(o => `${o.mainName || ''}${item.orderSmallTypeText}x${o.num}`).join(',')
                  }}</view>
                </view>
              </view>
              <view class="row">
                <view class="label">客户姓名</view>
                <view class="value">
                  <view class="val">{{ item.userName }} {{ item.userMobile }}</view>
                  <view class="num" v-if="item.customerTotalNum > 0">
                    (共<text>{{ item.customerSortNum || 0 }}</text
                    >/{{ item.customerTotalNum || 0 }}单)</view
                  >
                  <view
                    class="fun"
                    v-if="orderStatus_v(item.orderStatus) !== 'DQD'"
                    @tap.stop="$callPhone(item.userMobile)"
                  >
                    <text class="iconfont icon-call"></text>
                    <view class="text">联系Ta</view>
                  </view>
                </view>
              </view>
              <view class="row address-row">
                <!-- // name: item.userName, -->
                <view class="label">服务地址</view>
                <view class="value">
                  <view class="val address ellipsis-3">{{ item.address || item.gpsAddress }}</view>
                  <view
                    class="fun"
                    v-if="orderStatus_v(item.orderStatus) !== 'DQD'"
                    @tap.stop="
                      $openLocation({
                        lat: item.lat,
                        lng: item.lng,
                        address: item.address || item.gpsAddress
                      })
                    "
                  >
                    <text class="iconfont icon-daohang"></text>
                    <view class="text">导航</view>
                  </view>
                </view>
              </view>
            </view>
            <view class="item-btn" @tap.stop>
              <!-- 待接单 -->
              <block v-if="orderStatus_v(item.orderStatus) == 'DJD' && !item.isImportExcel">
                <u-button
                  plain
                  type="primary"
                  text="配件申请"
                  v-if="item.orderType != 'INSTALL' && !item.isImportExcel"
                  @tap="toPartsApply(item.id)"
                ></u-button>
                <u-button
                  plain
                  type="primary"
                  text="取消加急"
                  @tap="actionUrgent(item.id, false)"
                  v-if="item.orderFlags && item.orderFlags.some(o => o.tag == 'JIA_JI') && !item.isImportExcel"
                ></u-button>
                <u-button
                  plain
                  type="primary"
                  text="加急"
                  @tap="actionUrgent(item.id, true)"
                  v-else-if="!item.isImportExcel"
                ></u-button>
                <u-button
                  v-if="!item.isImportExcel"
                  type="primary"
                  text="接单"
                  @tap="actionReceive(item.id)"
                ></u-button>
              </block>
              <!-- 服务中 -->
              <block v-if="orderStatus_v(item.orderStatus) == 'FWZ' || orderStatus_v(item.orderStatus) == 'YCD'">
                <u-button
                  plain
                  type="primary"
                  text="配件申请"
                  v-if="item.orderType != 'INSTALL' && !item.isImportExcel"
                  @tap="toPartsApply(item.id)"
                ></u-button>
                <u-button
                  plain
                  type="primary"
                  text="辅材收费"
                  @tap="toCharge(item.id, 'M')"
                  v-if="item.orderType == 'INSTALL'"
                ></u-button>
                <u-button plain type="primary" text="配件收费" @tap="toCharge(item.id, 'P')" v-else></u-button>
                <u-button
                  v-if="!item.isImportExcel"
                  type="primary"
                  text="过程反馈"
                  @tap="toFeedback(item.id)"
                ></u-button>
              </block>
              <!-- 待抢单 -->
              <block v-if="orderStatus_v(item.orderStatus) == 'DQD' && !item.isImportExcel">
                <u-button type="primary" text="抢单" @tap="qdOrder(item)"></u-button>
              </block>
            </view>
          </view>
        </view>

        <Loading :loadStatus="loadStatus" :dataList="dataList" />
      </view>
    </zj-page-layout>

    <zj-dialog-dateRangePicker v-model="isShowDatePicker" @confirm="confirmDate"></zj-dialog-dateRangePicker>
  </view>
</template>

<script>
import zjDialogDateRangePicker from '@/components/zj-dialog/zj-dialog-dateRangePicker.vue'

export default {
  components: {
    zjDialogDateRangePicker
  },

  data() {
    return {
      mainTabs: [
        { name: '全部', value: '', num: 0 },
        { name: '待抢单', value: 'DQD', num: 0 },
        { name: '待接单', value: 'DJD', num: 0 },
        { name: '服务中', value: 'FWZ', num: 0 },
        { name: '已完工', value: 'YWG', num: 0 },
        { name: '异常待处理', value: 'YCD', num: 0 }
      ],
      curMainTab: '',
      curSmallTab: 0,
      curSmallTabIndex: 0,
      smallTabs: [
        { id: 0, name: '全部' },
        { id: 1, name: '今天' },
        { id: 2, name: '明天' },
        { id: 3, name: '其他' }
      ],
      curOrderType: '',

      isShowDatePicker: false,
      startDate: '',
      endDate: '',

      dataList: [],
      pageNum: 1,
      loadStatus: 0,
      refresherTriggered: false, // 下拉刷新状态

      scrollLeft: 0,
      scrollViewWidth: 0,
      tabsRect: {
        left: 0
      },

      isYb: false, // 是否延保单
      isWb: false // 是否维保单
    }
  },

  async onReady({ tab, isYb, isWb }) {
    this.crossPage.$on('refreshWorkorderList', data => {
      if (data && data.tab) {
        this.curMainTab = data.tab
      }
      this.refreshList()
    })

    if (isYb) {
      this.isYb = true
    }
    if (isWb) {
      this.isWb = true
    }

    this.getCount()

    this.curMainTab = tab || ''
    this.refreshList()

    this.resize()
  },

  onUnload() {
    this.crossPage.$off('refreshWorkorderList')
  },

  methods: {
    orderStatus_v(orderStatus) {
      if (['DYY'].includes(orderStatus)) {
        // 待预约
        return 'DYY'
      } else if (['DQD'].includes(orderStatus)) {
        // 待抢单
        return 'DQD'
      } else if (
        [
          'DSHPG',
          'CJ',
          'YPD',
          'DXSPD',
          'DZBPG',
          'DWDSPGP',
          'DXSSPGP',
          'DTJXSSPGP',
          'DZBSPGP',
          'DFZXPD',
          'DFZXSPGP',
          'XSBH',
          'TJXSBH',
          'ZBBH',
          'FZXBH',
          'FL'
        ].includes(orderStatus)
      ) {
        // 待商户派工
        return 'DSHPG'
      } else if (['DWDPG', 'DWDPD', 'WDBH'].includes(orderStatus)) {
        // 待网点派工
        return 'DWDPG'
      } else if (['DJD', 'DSM', 'YZP'].includes(orderStatus)) {
        // 待接单
        return 'DJD'
      } else if (['FWZ', 'GCSZT', 'BFWG'].includes(orderStatus)) {
        // 服务中
        return 'FWZ'
      } else if (['YCD'].includes(orderStatus)) {
        // 异常单
        return 'YCD'
      } else if (['YWG', 'GCSZX', 'WDWG', 'YWGO'].includes(orderStatus)) {
        // 已完工待结算
        return 'YWG'
      } else if (['YJS', 'LRCD'].includes(orderStatus)) {
        // 已结算
        return 'YJS'
      } else if (['YQX', 'FWZT', 'YCGB', 'FWQX'].includes(orderStatus)) {
        // 已取消
        return 'YQX'
      }
      return ''
    },
    // 触发下拉刷新
    async refresherrefresh(e) {
      this.refresherTriggered = true

      this.refreshList()
    },

    // 滚动到底部
    scrolltolower(e) {
      if (this.loadStatus === 0) {
        this.pageNum++
        this.getList()
      }
    },

    // 获取统计数量
    getCount() {
      this.$api
        .post('/pg/order/base/status/count', {
          isYb: this.isYb,
          isWb: this.isWb
        })
        .then(res => {
          if (!res.data) return false
          const data = res.data
          this.mainTabs[0].num = data.all || 0
          this.mainTabs[1].num = data.dqd || 0
          this.mainTabs[2].num = data.djd || 0
          this.mainTabs[3].num = data.fwz || 0
          this.mainTabs[4].num = data.ywg || 0
          this.mainTabs[5].num = data.ycd || 0
        })
    },

    // 获取列表
    getList() {
      this.loadStatus = 1
      this.$api
        .post('/pg/order/base/list', {
          pageNum: this.pageNum,
          pageSize: 5,
          keyword: '',
          orderBaseStatus: this.curMainTab,
          byDay: this.curSmallTab || '',
          startTime: this.startDate ? this.startDate + ' 00:00:00' : '',
          endTime: this.endDate ? this.endDate + ' 23:59:59' : '',
          isYb: this.isYb,
          isWb: this.isWb
        })
        .then(res => {
          this.loadStatus = 0
          let list = res.data.records
          if (list.length < 5) {
            this.loadStatus = 2
          }

          this.dataList = this.pageNum === 1 ? list : this.dataList.concat(list)
        })
        .catch(() => {
          this.loadStatus = 2
        })
        .finally(res => {
          this.refresherTriggered = false
        })
    },

    findMainTabIndex(val) {
      for (var i = 0; i < this.mainTabs.length; i++) {
        if (this.mainTabs[i]['value'] == val) {
          return i
        }
      }
    },

    setScrollLeft() {
      // 当前活动tab的布局信息，有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
      const tabRect = this.mainTabs[this.findMainTabIndex(this.curMainTab)]
      // 累加得到当前item到左边的距离
      const offsetLeft = this.mainTabs.slice(0, this.findMainTabIndex(this.curMainTab)).reduce((total, curr) => {
        return total + curr.rect.width
      }, 0)
      // 此处为屏幕宽度
      const windowWidth = uni.$u.sys().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.scrollLeft = Math.max(0, scrollLeft)
    },

    // 获取所有标签的尺寸
    resize() {
      if (this.mainTabs.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.mainTabs[index].rect = item
        })
        // 获取了tabs的尺寸之后，设置滑块的位置
        this.setScrollLeft()
      })
    },

    // 获取导航菜单的尺寸
    getTabsRect() {
      return new Promise(resolve => {
        this.queryRect('tab-scroll-view').then(size => resolve(size))
      })
    },

    // 获取所有标签的尺寸
    getAllItemRect() {
      return new Promise(resolve => {
        const promiseAllArr = this.mainTabs.map((item, index) => this.queryRect(`tab-item-${index}`, true))
        Promise.all(promiseAllArr).then(sizes => resolve(sizes))
      })
    },

    // 获取各个标签的尺寸
    queryRect(el, item) {
      return new Promise(resolve => {
        this.$uGetRect(`.${el}`).then(size => {
          resolve(size)
        })
      })
    },

    // 切换大状态
    changeMainTab(val) {
      this.curMainTab = val
      // this.curMainTab = val.value;
      if (this.startDate == '' || this.endDate == '') {
        this.curSmallTab = 0
        this.curSmallTabIndex = 0
      } else {
        this.curSmallTab = ''
        this.curSmallTabIndex = ''
      }

      this.refreshList()
      this.resize()
    },

    // 切换小状态
    changeSmallTab(item) {
      this.curSmallTab = item.id
      this.curSmallTabIndex = item.index
      this.startDate = ''
      this.endDate = ''
      this.refreshList()
    },

    // 选择日期
    confirmDate(item) {
      let [start, end] = item
      if (start == '' || end == '') {
        this.curSmallTab = 0
        this.curSmallTabIndex = 0
        this.startDate = ''
        this.endDate = ''
        return
      }
      this.curSmallTab = ''
      this.curSmallTabIndex = ''
      this.startDate = start
      this.endDate = end

      this.refreshList()
    },

    // 刷新列表
    refreshList() {
      this.dataList = []
      this.pageNum = 1
      this.getList()
      this.getCount()
    },

    // 去搜索页面
    toSearchPage() {
      this.$navToPage({
        url: '/packageWorkorder/pages/search'
      })
    },

    // 加急
    actionUrgent(id, flag) {
      this.$modal({
        title: '加急操作',
        content: '加急操作，会消息通知所有订单相关人员，请谨慎操作。'
      })
        .then(() => {
          this.$api
            .post('/pg/order/base/flag', {
              orderBaseId: id,
              orderFlagEnum: 'JIA_JI',
              flag: flag
            })
            .then(res => {
              this.$successToast()
              this.refreshList()
            })
        })
        .catch(() => {})
    },

    // 接单
    actionReceive(id) {
      this.$modal({
        title: '接单确认',
        content: '确认接单？'
      })
        .then(() => {
          this.$api
            .post('/pg/order/base/rece', {
              orderBaseId: id
            })
            .then(res => {
              this.$successToast()
              this.refreshList()
              this.toDetail(id)
            })
        })
        .catch(() => {})
    },

    // 去收费
    toCharge(id, type) {
      if (type == 'M') {
        this.$navToPage({
          url: `/packageMaterial/pages/sale/index?type=${type}&oid=${id}`
        })
      } else if (type == 'P') {
        this.$navToPage({
          url: `/packageMaterial/pages/newSale/index?type=${type}&oid=${id}`
        })
      }
    },

    // 去配件申请
    toPartsApply(id) {
      this.$navToPage({
        url: `/packageMaterial/pages/partsApply/form?id=${id}`
      })
    },

    // 去过程反馈
    toFeedback(id) {
      this.$navToPage({
        url: `/packageWorkorder/pages/processFeedback?id=${id}`
      })
    },

    toDetail(id) {
      this.$navToPage({
        url: `/packageWorkorder/pages/orderDetail?id=${id}`
      })
    },

    qdOrder(item) {
      this.$modal({
        title: '抢单确认',
        content: '确认抢单？'
      })
        .then(() => {
          this.$api
            .post('/pg/order/base/qd', {
              orderBaseId: item.id
            })
            .then(res => {
              this.$successToast()
              this.refreshList()
              this.toDetail(item.id)
            })
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scopeds>
.all-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .main-container {
    flex: 1;
  }
}

.top-container {
  display: flex;
  background: $theme-color;
  height: 100rpx;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx 10rpx;
  position: relative;

  .left-nav {
    flex: 1;
    display: flex;
    align-items: flex-end;
    // overflow-x: scroll;
    // overflow-y: hidden;
    padding: 20rpx 0;

    .item {
      flex-shrink: 0;
      display: flex;
      margin-right: 32rpx;
      position: relative;

      // &:last-child {
      // 	margin-right: 0;
      // }
      .name {
        font-size: 30rpx;
        color: #ffffff;
      }

      .num {
        color: #ffffff;
        margin-top: -8rpx;
        margin-left: 2rpx;
      }

      &.active {
        &::after {
          content: '';
          width: 44rpx;
          height: 6rpx;
          background: #ffffff;
          border-radius: 6rpx;
          position: absolute;
          bottom: -16rpx;
          left: calc((100% - 44rpx) / 2);
        }

        .name {
          font-size: 40rpx;
          font-weight: bolder;
          position: relative;
        }
      }
    }
  }

  .right-search {
    margin-left: 30rpx;
    margin-top: 10rpx;

    .iconfont {
      font-size: 36rpx;
      color: #ffffff;
    }
  }
}

.status-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;

  .date {
    height: 68rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 24rpx;
    border-radius: 24rpx;
    border: 1px solid #eaeaea;
    box-sizing: border-box;

    .text {
      font-size: 28rpx;
      color: $reg-font;
    }

    .iconfont {
      font-size: 28rpx;
      color: $reg-font;
    }

    &.active {
      background: #e7efff;
      border: 1px solid #3d8ffd;

      .text {
        color: #3d8ffd;
      }

      .iconfont {
        color: #3d8ffd;
      }
    }
  }
}

.order-list-container {
  padding: 0 30rpx;

  .item {
    @include zj-card;
    background: #ffffff;
    border-radius: 20rpx;
    margin-bottom: 30rpx;
    padding: 0 30rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-top {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      border-bottom: 1px solid #d6e0f2;
      padding: 30rpx 0 20rpx;

      .left {
        flex: 1;
        width: 0;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .title {
          font-size: 40rpx;
          font-weight: 600;
          color: $theme-color;
          margin-right: 12rpx;
        }

        .text {
          line-height: 48rpx;
          padding: 0 16rpx;
          background: #f4f5f9;
          border-radius: 8rpx;
          margin-right: 12rpx;

          text {
            color: $assist-color;
          }
        }

        .tags {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;

          .tag {
            margin-top: 10rpx;
            flex-shrink: 0;
            height: 36rpx;
            line-height: 36rpx;
            border-radius: 8rpx;
            border: 1px solid $theme-color;
            color: $theme-color;
            font-size: 24rpx;
            padding: 0 10rpx;
            box-sizing: border-box;
            font-weight: 500;
            margin-right: 10rpx;

            &:last-child {
              margin-right: 0;
            }

            &.red {
              border: 1px solid $minor-color;
              color: $minor-color;
            }

            &.red_solid {
              border: 1px solid $minor-color;
              color: #ffffff;
              background: $minor-color;
            }

            &.orange {
              border: 1px solid $assist-color;
              color: $assist-color;
            }

            &.green {
              border: 1px solid $success-color;
              color: $success-color;
            }
          }
        }
      }

      .right {
        float: right;
        flex-shrink: 0;
        height: 56rpx;
        display: flex;
        align-items: center;

        .iconfont {
          color: $minor-color;
        }

        .time {
          color: $minor-color;
          margin-left: 4rpx;
        }
      }

      .status {
        color: $minor-color;
        line-height: 56rpx;
      }
    }

    .item-main {
      .row {
        display: flex;
        align-items: center;
        margin-top: 20rpx;

        &.address-row {
          align-items: flex-start;

          .value {
            align-items: flex-start;
          }
        }

        .label {
          color: $sec-font;
          flex-shrink: 0;
          margin-right: 20rpx;
          line-height: 36rpx;
          font-size: 28rpx;
        }

        .value {
          flex: 1;
          display: flex;
          align-items: center;

          .val {
            line-height: 32rpx;
            font-size: 28rpx;
          }

          .num {
            margin-left: 4rpx;

            text {
              color: $theme-color;
            }
          }

          .tag {
            height: 36rpx;
            padding: 0 10rpx;
            border-radius: 4rpx;
            background: #ecf5ff;
            color: $theme-color;
            font-size: 20rpx;
            font-weight: 500;
            margin-left: 10rpx;
            line-height: 36rpx;
            box-sizing: border-box;
          }

          .fun {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            padding: 0 20rpx;

            .iconfont {
              color: $theme-color;
              margin-right: 6rpx;
            }

            .text {
              font-size: 28rpx;
              color: $theme-color;
            }
          }
        }
      }
    }

    .item-btn {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 30rpx 0;

      ::v-deep .u-button {
        width: 160rpx;
        margin: 0;
        margin-left: 20rpx;
      }
    }
  }
}
</style>
