<template>
  <pb-layout
    title="订单"
    navbar="normal"
    tabbar="/pages/index/order"
    :bgStyle="bgStyle"
    opacityBgUi="bg-white"
    color="black"
    :leftIcon="''"
  >
    <pb-sticky bgColor="#fff">
      <pb-tabs :list="tabMaps" :scrollable="false" @change="onTabsChange" :current="state.currentTab">
        <template #right>
          <uni-icons
            type="search"
            size="20"
            :color="state.searchStatus ? '#ff3000' : '#000'"
            :style="{
              position: 'relative',
              top: '2px',
              'margin-right': '20rpx',
            }"
            @click="onSearch"
          ></uni-icons>
        </template>
      </pb-tabs>
    </pb-sticky>
    <p-empty v-if="state.pagination.total === 0" icon="/static/order-empty.png" text="暂无订单" bgColor="transparent" />
    <view v-if="state.pagination.total > 0">
      <view
        class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
        v-for="order in state.pagination.list"
        :key="order.id"
      >
        <view @tap="onOrderDetail(order.id, state.currentTab)">
          <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
            <view class="order-no">订单号：{{ order.no }}</view>
            <view class="order-state ss-font-26" :class="formatOrderColor(order)">
              {{ formatOrderStatus(order) }}
            </view>
          </view>
          <view class="ss-p-x-20">
            <view class="order-no">收货人：{{ order?.user.nickname }}</view>
            <view class="order-no">联系电话：{{ order?.user.mobile }}</view>
            <view class="order-no">下单时间：{{ formatDate(order.createTime) }}</view>
          </view>
          <view class="border-bottom" v-for="item in order.items" :key="item.id">
            <p-goods-item
              :img="item.picUrl"
              :title="item.spuName"
              :skuText="item.properties.map((property) => property.valueName).join(' ')"
              :price="item.price"
              :num="item.count"
            />
          </view>

          <view
            class="order-card-footer ss-flex ss-col-center ss-p-x-20"
            :class="order.buttons.length > 3 ? 'ss-row-between' : 'ss-row-right'"
          >
            <view class="ss-flex ss-col-center">
              <button
                v-if="order.buttons.length === 0"
                class="tool-btn ss-reset-button"
                @tap.stop="onOrderDetail(order.id)"
              >
                查看详情
              </button>
              <button
                v-if="order.buttons.includes('confirm')"
                class="tool-btn ss-reset-button"
                @tap.stop="onConfirm(order)"
              >
                确认收货
              </button>
              <button
                v-if="order.buttons.includes('express')"
                class="tool-btn ss-reset-button"
                @tap.stop="onExpress(order.id)"
              >
                查看物流
              </button>
              <button
                v-if="order.buttons.includes('cancel')"
                class="tool-btn ss-reset-button"
                @tap.stop="onCancel(order.id, sindex)"
              >
                取消订单
              </button>
              <button
                v-if="order.buttons.includes('comment')"
                class="tool-btn ss-reset-button"
                @tap.stop="onComment(order.id)"
              >
                评价
              </button>
              <button
                v-if="order.buttons.includes('delete')"
                class="delete-btn ss-reset-button"
                @tap.stop="onDelete(order.id)"
              >
                删除订单
              </button>
              <button
                v-if="order.buttons.includes('verification')"
                class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                @tap.stop="onVerification(order.id)"
              >
                核销订单
              </button>
              <button
                v-if="order.buttons.includes('delivery')"
                class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                @tap.stop="onDelivery(order.id)"
              >
                配送完成
              </button>
            </view>
          </view>
          <view class="pay-box ss-m-t-30 ss-flex ss-gap-40 ss-p-b-40 ss-row-right ss-p-r-20">
            <view class="ss-flex ss-col-center">
              <view class="discounts-title pay-color">共 {{ totalNumsPerOrder(order) }} 件商品,总金额:</view>
              <view class="discounts-money pay-color"> ￥{{ fen2yuan(totalPricePerOrder(order)) }} </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{ contentdown: '上拉加载更多' }"
    />
    <uni-popup type="right" ref="filterPopupRef" background-color="#fff">
      <view class="query-form">
        <uni-forms v-model="state.queryForm">
          <uni-forms-item name="userNickname" label="昵称">
            <uni-easyinput type="text" v-model="state.queryForm.userNickname" placeholder="请输入昵称" clearable />
          </uni-forms-item>
          <uni-forms-item label="联系电话" name="userMobile">
            <uni-easyinput type="number" v-model="state.queryForm.userMobile" placeholder="请输入联系电话" />
          </uni-forms-item>
          <uni-forms-item name="no" label="订单号">
            <uni-easyinput type="text" v-model="state.queryForm.no" placeholder="请输入订单号" clearable />
          </uni-forms-item>
          <uni-forms-item name="createTime" label="创建时间">
            <uni-datetime-picker v-model="state.queryForm.createTime" type="daterange" />
          </uni-forms-item>
        </uni-forms>

        <view class="btns">
          <button class="ss-reset-button query-btn shadow" @tap="onSubmit">查询</button>
          <button class="ss-reset-button reset-btn shadow" @tap="reset">重置</button>
        </view>
      </view>
    </uni-popup>
  </pb-layout>
</template>

<script setup>
import { ref } from 'vue'
import OrderApi from '@/peach/api/trade/order'
import { onLoad, onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { fen2yuan, formatOrderColor, formatOrderStatus, handleOrderButtons } from '@/peach/hooks/useGoods'
import peach from '@/peach'
import _, { isEmpty } from 'lodash'
import { resetPagination, formatDate } from '@/peach/utils'

const bgStyle = {
  backgroundColor: 'var(--ui-BG-1)',
  description: '',
}

const state = ref({
  currentTab: 0,
  pagination: {
    list: [],
    total: 0,
    pageNo: 1,
    pageSize: 6,
  },
  loadStatus: '',
  queryForm: {
    userNickname: '',
    userMobile: '',
    no: '',
    createTime: [],
  },
  searchStatus: false,
})

const filterPopupRef = ref(null)

const tabMaps = [
  {
    name: '全部',
  },
  {
    name: '已付款',
    value: '50,60',
    commentStatus: 2,
  },
  {
    name: '已评价',
    value: '30',
    commentStatus: 1,
  },
  {
    name: '已退款',
    value: '10,20',
  },
]

function onDelivery(id) {
  OrderApi.orderComplete({ orderId: id }).then(() => {
    uni.showToast({
      title: '配送成功',
      icon: 'success',
    })
    setTimeout(() => {
      peach.$router.go('/pages/order/detail', {
        id: id,
      })
    }, 500)
  })
}

// 单个订单总商品数
function totalNumsPerOrder(order) {
  if (order.items.length) {
    return order.items.reduce((per, cur) => {
      return per + cur.count
    }, 0)
  }
}

// 单个订单总金额
function totalPricePerOrder(order) {
  if (order.items.length) {
    return order.items.reduce((per, cur) => {
      return per + cur.payPrice
    }, 0)
  }
}

function onSearch() {
  filterPopupRef.value.open()
}

function onSubmit() {
  state.value.pagination.list = []
  filterPopupRef.value.close()
  state.value.searchStatus = true
  getOrderList()
}

function resetFields() {
  state.value.queryForm = {
    userNickname: '',
    userMobile: '',
    no: '',
    createTime: [],
  }
}

function reset() {
  state.value.pagination.list = []
  state.value.searchStatus = false
  filterPopupRef.value.close()
  resetFields()
  getOrderList()
}

// 切换选项卡
function onTabsChange(e) {
  if (state.value.currentTab === e.index) {
    return
  }
  // 重头加载代码
  resetPagination(state.value.pagination)
  state.value.currentTab = e.index
  getOrderList()
}

// 订单详情
function onOrderDetail(id) {
  peach.$router.go('/pages/order/detail', {
    id,
    currentTabIndex: state.value.currentTab,
  })
}

// 获取订单列表
async function getOrderList() {
  state.value.loadStatus = 'loading'
  let { data } = await OrderApi.getOrderPage({
    pageNo: state.value.pagination.pageNo,
    pageSize: state.value.pagination.pageSize,
    status: state.value.currentTab !== 3 ? tabMaps[state.value.currentTab].value : undefined,
    refundStatus: state.value.currentTab === 3 ? tabMaps[state.value.currentTab].value : undefined,
    commentStatus: tabMaps[state.value.currentTab].commentStatus
      ? state.value.currentTab === 1
        ? false
        : true
      : undefined,
    ...state.value.queryForm,
  })

  data.list.forEach((item) => {
    handleOrderButtons(item)
  })
  state.value.pagination.list = _.concat(state.value.pagination.list, data.list)
  state.value.pagination.total = data.total
  let currentPageTotal = state.value.pagination.length
  state.value.loadStatus = currentPageTotal < state.value.pagination.total ? 'more' : 'noMore'
}

onLoad(async (options) => {
  if (options.type) {
    state.value.currentTab = options.type
  }
})

onShow(async () => {
  resetPagination(state.value.pagination)
  await getOrderList()
})

// 加载更多
function loadMore() {
  if (state.value.loadStatus === 'noMore') {
    return
  }
  state.value.pagination.pageNo++
  getOrderList()
}

// 上拉加载更多
onReachBottom(() => {
  loadMore()
})

// 下拉刷新
onPullDownRefresh(() => {
  resetPagination(state.value.pagination)
  state.value.searchStatus = false
  resetFields()
  getOrderList()
  setTimeout(function () {
    uni.stopPullDownRefresh()
  }, 800)
})
</script>

<style lang="scss" scoped>
.tool-btn {
  width: 160rpx;
  height: 60rpx;
  background: #f6f6f6;
  font-size: 26rpx;
  border-radius: 30rpx;
  margin-right: 10rpx;

  &:last-of-type {
    margin-right: 0;
  }
}

.delete-btn {
  width: 160rpx;
  height: 56rpx;
  color: #ff3000;
  background: #fee;
  border-radius: 28rpx;
  font-size: 26rpx;
  margin-right: 10rpx;
  line-height: normal;

  &:last-of-type {
    margin-right: 0;
  }
}

.apply-btn {
  width: 140rpx;
  height: 50rpx;
  border-radius: 25rpx;
  font-size: 24rpx;
  border: 2rpx solid #dcdcdc;
  line-height: normal;
  margin-left: 16rpx;
}

.order-list-card-box {
  .order-card-header {
    padding-top: 20rpx;
    .order-no {
      font-size: 26rpx;
      font-weight: 500;
    }

    .order-state {
    }
  }

  .pay-box {
    .discounts-title {
      font-size: 24rpx;
      line-height: normal;
      color: #999999;
    }

    .discounts-money {
      font-size: 24rpx;
      line-height: normal;
      color: #999;
      font-family: OPPOSANS;
    }

    .pay-color {
      color: #333;
    }
  }

  .order-card-footer {
    height: 100rpx;

    .more-item-box {
      padding: 20rpx;

      .more-item {
        height: 60rpx;

        .title {
          font-size: 26rpx;
        }
      }
    }

    .more-btn {
      color: $dark-9;
      font-size: 24rpx;
    }

    .content {
      width: 154rpx;
      color: #333333;
      font-size: 26rpx;
      font-weight: 500;
    }
  }
}

.query-form {
  width: 600rpx;
  margin-top: 230rpx;
  padding: 0 20rpx;
  .btns {
    display: flex;
    gap: 20px;
    .query-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: $white;
    }
    .reset-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      border: 1px solid #000;
    }
  }
}

:deep(.uni-tooltip-popup) {
  background: var(--ui-BG);
}

.warning-color {
  color: #faad14;
}

.danger-color {
  color: #ff3000;
}

.success-color {
  color: #52c41a;
}

.info-color {
  color: #999999;
}
</style>
