<template>
  <div class="content">
    <div class="top-wrapper">
      <div class="top-cont">
        <div class="top-title">订单</div>
        <u-input
          v-model="searchValue"
          class="top-ipt"
          placeholder="请输入食堂、档口、菜品/商品名"
          shape="circle"
          suffixIcon="search"
          suffixIconStyle="color: #909399; font-size: 18px;"
          placeholderStyle="font-weight: 400;font-size: 10px;color: rgba(15,39,75,0.4);"
          @blur="handleSearch"
        ></u-input>
        <div class="top-filter" @click="openPopup">
          <span style="font-size: 12px; color: #0f274b">筛选</span>
          <u-icon name="../../static/images/pull.png" />
        </div>
      </div>

      <div style="padding: 0 16px">
        <Tabs :tabList="tabList" @changeTab="changeTab" />
      </div>
    </div>

    <div style="height: 56px"></div>
    <div style="padding: 0 16px">
      <div class="order-list" v-for="(item, index) in tableList" :key="index">
        <div class="flex justify-between">
          <div class="order-source">订单来源：{{ item.sourceType }}</div>
          <div style="color: rgba(15, 39, 75, 0.8)">{{ handleOrderState(item.ordState) }}</div>
        </div>
        <div class="flex justify-between">
          <div>
            <span style="color: #0f274b">{{ item.canteenName }}</span>
            <span class="intervalName">{{ item.intervalName }}</span>
          </div>
          <div style="color: rgba(15, 39, 75, 0.8)">就餐时间：{{ item.orderTime }}</div>
        </div>
        <div class="img-cont" @click="goDetail(item)">
          <div class="img" v-for="(goods, index) in item.detailList" :key="index">
            <u-image :src="goods.goodsDishesImgUrl" width="80px" height="80px" />
            <div>{{ goods.goodsDishesName }}</div>
          </div>
          <div class="price">
            <div>
              <span>￥</span>
              <span style="font-size: 18px">{{ item.realAmount }}</span>
            </div>
            <div style="color: rgba(15, 39, 75, 0.6)">共{{ item.detailList.length }}件</div>
          </div>
        </div>
        <div class="btn-cont">
          <div v-if="item.ordState != 10">
            <u-button size="small">评价</u-button>
          </div>
          <div v-if="item.ordState == 10">
            <u-button size="small">删除订单</u-button>
          </div>
        </div>
      </div>
    </div>

    <div style="margin: 20px 0" v-if="tableList.length > 0">
      <u-loadmore :status="status" nomoreText="没有更多数据了" />
    </div>
    <div v-else class="flex justify-center align-center" style="height: 50vh">
      <u-empty icon="../../static/images/not_order.png" text="暂无相关订单" textColor="#000" />
    </div>

    <!--  筛选部分-->
    <u-popup :show="localShow" @close="closePopup" mode="bottom" round="20">
      <view class="filter-popup">
        <!-- 订单日期 -->
        <view class="section">
          <view class="section-title">订单日期</view>
          <view class="date-quick-select">
            <view
              v-for="(item, index) in dateOptions"
              :key="index"
              class="date-option"
              :class="{ active: currentDateOption === index }"
              @click="selectDateOption(index)"
            >
              {{ item.label }}
            </view>
          </view>

          <view class="date-range">
            <view class="date-input" @click="showStartCalendar = true">
              <text class="date-placeholder" v-if="!startDate">开始时间</text>
              <text v-else class="selected-date">{{ startDate }}</text>
            </view>
            <text class="date-separator">-</text>
            <view class="date-input" @click="showEndCalendar = true">
              <text class="date-placeholder" v-if="!endDate">结束时间</text>
              <text v-else class="selected-date">{{ endDate }}</text>
            </view>
          </view>
        </view>

        <!-- 订单类型 -->
        <view class="section">
          <view class="section-title">订单类型</view>
          <u-grid :border="false" col="3">
            <u-grid-item v-for="(item, index) in orderTypes" :key="index" @click="selectOrderType(index)">
              <view class="order-type-item" :class="{ active: selectedOrderTypes.includes(index) }">
                {{ item }}
              </view>
            </u-grid-item>
          </u-grid>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-buttons">
          <u-button
            text="清空"
            shape="circle"
            :customStyle="{
              border: '2rpx solid #DDDDDD',
              color: '#666666',
              background: '#ffffff',
              marginRight: '24px'
            }"
            @click="clearAll"
          ></u-button>
          <u-button
            type="warning"
            text="确定"
            shape="circle"
            :customStyle="{
              background: '#ff6633'
            }"
            @click="confirm"
          ></u-button>
        </view>
      </view>

      <!-- 日期选择器 -->
      <u-datetime-picker
        :show="showStartCalendar"
        @cancel="showStartCalendar = false"
        @confirm="selectStartDate"
        mode="date"
      ></u-datetime-picker>

      <u-datetime-picker
        :show="showEndCalendar"
        @cancel="showEndCalendar = false"
        @confirm="selectEndDate"
        mode="date"
      ></u-datetime-picker>
    </u-popup>
  </div>
</template>

<script>
import { getOrderList } from '@/api/dining-hall'
import Tabs from '@/pages/components/Tabs.vue'
import { getDate } from '../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/util'
import { getOrderInfoListAPI } from '../../api/order/index'

export default {
  components: { Tabs },
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tabIndex: 0,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchValue: '',
      status: 'loadmore',
      tabList: ['全部订单', '待评价', '退款'],
      tableList: [
        {
          sourceType: 'hygyy双屏消费机', // 订单来源
          canteenName: '宏源工业园/本周菜谱', // 订单来源
          intervalName: '午餐', // 餐次
          ordState: 11, // 订单状态 1 已下单 9 已取消 10 已退款 11 已完成
          orderTime: '2024-08-12', // 下单时间
          realAmount: 30.2, // 实付金额
          detailList: [
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg' // 商品图片
            },
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
            },
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
            }
          ] // 订单详情
        },
        {
          sourceType: 'hygyy双屏消费机', // 订单来源
          canteenName: '宏源工业园/本周菜谱', // 订单来源
          intervalName: '午餐', // 餐次
          ordState: 10, // 订单状态 1 已下单 9 已取消 10 已退款 11 已完成
          orderTime: '2024-08-12', // 下单时间
          realAmount: 30.2, // 实付金额
          detailList: [
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg' // 商品图片
            },
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
            },
            {
              goodsDishesName: '苹果', // 商品名称
              goodsDishesImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
            }
          ] // 订单详情
        }
      ],
      localShow: this.show,
      monthNum: 12,
      minData: getDate(new Date()),
      dateOptions: [
        { label: '近1个月', value: 1 },
        { label: '近3个月', value: 3 },
        { label: '近6个月', value: 6 }
      ],
      currentDateOption: -1,
      startDate: '',
      endDate: '',
      showStartCalendar: false,
      showEndCalendar: false,
      orderTypes: ['当餐点餐', '预订餐', '报餐', '自助餐', '商城', '设备', '收款码', '美团-到店', '美团-外卖'],
      selectedOrderTypes: []
    }
  },
  watch: {
    show(newVal) {
      this.localShow = newVal // 监听 prop 变化并更新本地数据属性
    }
  },
  methods: {
    handleSearch() {
      console.log('搜索', this.searchValue)
      this.getList()
    },
    async getList() {
      console.log('获取列表')
      const params = {
        custId: 0,
        custThridId: 0,
        custNum: 0,
        endDateTime: '',
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        rechargeState: '',
        startDateTime: '',
        tradeType: '',
        searchValue: this.searchValue
      }

      try {
        const res = await getOrderList(params)
        console.log('🚀 ~ getList ~ res:', res)
        this.tableList = res.data.orderInfoList
        this.total = res.data.count
        this.status = this.total == this.tableList.length ? 'nomore' : 'loadmore'
      } catch (error) {
        console.log(error)
      }
    },
    onReachBottom() {
      console.log('🚀 ~ onReachBottom ~ ')
      if (this.total < 10 || this.total == this.tableList.length) {
        this.status = 'nomore'
        return
      }
      this.status = 'loading'
      setTimeout(() => {
        this.pageSize += 10
        this.getList()
        if (this.tableList.length != this.total) this.status = 'loadmore'
        else this.status = 'nomore'
      }, 500)
      console.log('加载..', this.pageSize)
    },
    changeTab(index) {
      console.log('🚀 ~ changeTab ~ index:', index)
      this.tabIndex = index
    },
    // 处理订单状态展示
    handleOrderState(state) {
      switch (state) {
        case 1:
          return '已下单'
        case 9:
          return '已取消'
        case 10:
          return '已退款'
        case 11:
          return '已完成'
      }
    },

    openPopup() {
      this.localShow = true
    },

    closePopup() {
      this.localShow = false
    },
    selectDateOption(index) {
      this.currentDateOption = index
      const months = this.dateOptions[index].value
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - months)

      this.startDate = this.formatDate(start)
      this.endDate = this.formatDate(end)
    },
    selectStartDate(e) {
      console.log('selectStartDate', e)
      const timeFormat = uni.$u.timeFormat
      this.startDate = timeFormat(e.value, 'yyyy-mm-dd')
      this.currentDateOption = -1 // 清除快速选择的高亮
      this.showStartCalendar = false
    },
    selectEndDate(e) {
      const timeFormat = uni.$u.timeFormat
      this.endDate = timeFormat(e.value, 'yyyy-mm-dd')
      this.currentDateOption = -1
      this.showEndCalendar = false
    },
    selectOrderType(index) {
      const position = this.selectedOrderTypes.indexOf(index)
      if (position > -1) {
        this.selectedOrderTypes.splice(position, 1)
      } else {
        this.selectedOrderTypes.push(index)
      }
    },
    clearAll() {
      this.currentDateOption = -1
      this.startDate = ''
      this.endDate = ''
      this.selectedOrderTypes = []
    },
    confirm() {
      if (!this.startDate || !this.endDate) {
        uni.$u.toast('请选择完整的日期范围')
        return
      }
      this.$emit('confirm', {
        dateRange: {
          start: this.startDate,
          end: this.endDate
        },
        orderTypes: this.selectedOrderTypes.map(index => this.orderTypes[index])
      })
      this.closePopup()
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 跳转订单详情
    goDetail(item) {
      console.log('跳转订单详情', item)
      uni.navigateTo({
        url: `/pages/work/details?params=${JSON.stringify(item)}`
      })
    },

    // 获取订单
    async getOrderInfoListData() {
      const res = await getOrderInfoListAPI()
      console.log(res, '获取订单信息')
    }
  },
  created() {
    this.getOrderInfoListData()
  }
}
</script>

<style lang="scss" scoped>
.content {
  background: #f9fbff;
  height: 100%;
  min-height: 100vh;

  .top-wrapper {
    position: fixed;
    /* top: 44px; */
    top: 0;
    width: 100vw;
    background: #f9fbff;
    z-index: 999;
  }

  .top-cont {
    padding: 0 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .top-title {
      font-weight: 500;
      font-size: 20px;
      color: #0f274b;
    }
    .top-ipt {
      height: 31px;
      background: #fff;
      margin-left: 26px;
      margin-right: 12px;
    }
    .top-filter {
      display: flex;
      align-items: center;
    }
  }

  .order-list {
    padding: 8px;
    background: #fff;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 400;
    margin-bottom: 12px;

    .order-source {
      margin-bottom: 12px;
      font-weight: 500;
      color: #0f274b;
    }

    .intervalName {
      margin-left: 10px;
      color: #ff6816;
      border-radius: 1px 1px 1px 1px;
      border: 1px solid #ff6816;
      padding: 0 4px;
    }

    .img-cont {
      margin: 10px;
      display: flex;
      justify-content: space-between;

      .img {
        display: flex;
        flex-direction: column;
        align-items: center;
        div {
          margin-top: 8px;
          color: #0f274b;
        }
      }
    }

    .price {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #0f274b;
      font-weight: 400;
      font-size: 12px;
    }

    .btn-cont {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}
.filter-popup {
  padding: 30rpx;
  min-height: 60vh;
  max-height: 90vh;
  .section {
    margin-bottom: 40rpx;

    .section-title {
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
      margin-bottom: 20rpx;
    }
  }

  .date-quick-select {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;

    .date-option {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f8f8f8;
      border-radius: 100rpx;
      font-size: 28rpx;
      color: #666666;

      &.active {
        background-color: #fff2ef;
        color: #ff6633;
      }
    }
  }

  .date-range {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .date-input {
      flex: 1;
      height: 80rpx;
      background-color: #f8f8f8;
      border-radius: 100rpx;
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      font-size: 28rpx;

      .date-placeholder {
        color: #999999;
      }

      .selected-date {
        color: #333333;
      }
    }

    .date-separator {
      color: #999999;
      font-size: 28rpx;
    }
  }

  .order-type-item {
    width: 200rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
    border-radius: 25px;
    font-size: 28rpx;
    color: #666666;
    margin: 10rpx auto;

    &.active {
      background-color: #fff2ef;
      color: #ff6633;
    }
  }

  .bottom-buttons {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 28px 16rpx;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
}
</style>
