<script lang="ts" setup>
import {useConfigStore, useUserStore} from "@/store";
import HomeSkeleton from "./components/home-skeleton.vue";
import {appMerchantIndexDataGet, appMerchantOrderDishListPost, appMerchantOrderOrderListPost} from "@/service";
import {OrderStatus} from "@/constant/enums";
import dayjs from "dayjs";
import Config from "@/config";

const configStore = useConfigStore()
const userStore = useUserStore()
const emits = defineEmits(['changeStore'])

const {t} = useI18n()

function navigateTo(url: string) {
  if (userStore.checkLogin()) {
    if (url === '/pages-user/pages/scan-code/index' && !userStore.currentMerchantToken) {
      uni.showToast({
        title: t('toast.pleaseSelectStore'),
        icon: 'none',
      })
      return
    }
    uni.navigateTo({
      url,
    })
  }
}

const orderTabsList = ref([
  {
    title: t('pages.home.todayOrder'),
    value: 0,
  },
  {
    title: t('pages.home.bookDishesToday'),
    value: 1,
  },
  {
    title: t('pages.home.futureOrders'),
    value: 2,
  }
])
const currentTabs = ref(0)

function viewAll() {
  if (userStore.checkLogin()) {
    switch (currentTabs.value) {
      case 0:
        navigateTo('/pages-user/pages/home-order/today')
        break
      case 1:
        navigateTo('/pages-user/pages/home-order/reservation')
        break
      case 2:
        navigateTo('/pages-user/pages/home-order/future')
        break
    }
  }
}

// 生成未来四天的日期,不包含今天
const recentDays = computed(() => {
  const days = []
  for (let i = 1; i < 6; i++) {
    const date = new Date()
    date.setDate(date.getDate() + i)
    // 格式化日期，不显示年份，只显示月/日
    const month = date.getMonth() + 1
    const day = date.getDate()
    days.push(`${month}/${day}`)
  }
  return days
})
// 选中的日期
const selectedDate = ref(0)

function clickSelectedDate(index: number) {
  selectedDate.value = index
  // 如果当前在订单标签页，更新时间范围并刷新订单列表
  if (currentTabs.value === 2) {
    const selectedDay = index + 1 // 因为 recentDays 从明天开始，所以要加1
    const targetDate = dayjs().add(selectedDay, 'day')
    timeData.value = {
      createBeginTime: targetDate.startOf('day').valueOf(),
      createEndTime: targetDate.endOf('day').valueOf(),
    }
    getOrderList()
  }
}

// 加载状态
const loading = ref(true)

// 店铺数据
const storeInfo = ref()

async function initData() {
  await userStore.getUserInfo();
  if (!storeInfo.value) {
    loading.value = true
  }
  try {
    if (!userStore.isLogin) {
      loading.value = false
      // 清空首页查询的数据
      storeInfo.value = {}
      return
    }
    // 查询商户首页数据
    appMerchantIndexDataGet({
      body: {
        timeZoneId: dayjs.tz?.guess() || Config.timezone
      }
    }).then(res => {
      console.log('商户首页数据', res)
      storeInfo.value = res.data
    }).finally(() => {
      loading.value = false
    })
    // 获取当前商户的订单信息
    getOrderList()
  } catch (e) {
  }
}

function tabsChange(index: any) {
  console.log('切换了标签', index)
  currentTabs.value = index.index
  if (!userStore.isLogin) return
  if (index.index === 1) {
    getReservationList()
  } else if (index.index === 2) {
    // 设置日期
    console.log('recentDays.value[selectedDate.value]', recentDays.value[selectedDate.value])
    // 根据选中的日期设置时间范围
    const selectedDay = selectedDate.value + 1 // 因为 recentDays 从明天开始，所以要加1
    const targetDate = dayjs().add(selectedDay, 'day')
    timeData.value = {
      createBeginTime: targetDate.startOf('day').valueOf(),
      createEndTime: targetDate.endOf('day').valueOf(),
    }
    getOrderList()
  } else if (index.index === 0) {
    timeData.value = {
      createBeginTime: dayjs().startOf('day').valueOf(),
      createEndTime: dayjs().endOf('day').valueOf(),
    }
    getOrderList()
  }
}

// 今日订单列表
const todayOrderList = ref([])
const timeData = ref({
  createBeginTime: dayjs().startOf('day').valueOf(),
  createEndTime: dayjs().endOf('day').valueOf(),
})

function getOrderList() {
  appMerchantOrderOrderListPost({
    params: {
      pageNum: 1,
      pageSize: 2,
    },
    body: {
      userPort: 2,
      orderStatusList: [OrderStatus.HAS_PENDING_PAYMENT, OrderStatus.MERCHANT_ACCEPTED, OrderStatus.DELIVERING, OrderStatus.COMPLETED,],
      ...timeData.value
    }
  }).then((res: any) => {
    todayOrderList.value = res.rows
    console.log('订单列表', res)
  })
}

// 预定菜品列表
const reservationList = ref([])

function getReservationList() {
  appMerchantOrderDishListPost({
    body: {
      pageNum: 1,
      pageSize: 10,
      createBeginTime: dayjs().startOf('day').valueOf(),
      createEndTime: dayjs().endOf('day').valueOf(),
    }
  }).then(res => {
    reservationList.value = res.rows
  })
}

async function getPlatformDefaultStoreInfo() {
}

defineExpose({
  initData,
  init: getPlatformDefaultStoreInfo,
})
</script>

<template>
  <view :style="[{
                height: configStore.windowHeight+'px',
  }]"
        class="bg-#F6F6F6"
  >
    <z-paging ref="paging">
      <template #top>
        <view>
          <status-bar/>
          <view class="flex-center-sb px-30rpx pt-20rpx pb-10rpx relative">
            <view class="flex items-center" @click="navigateTo('/pages-user/pages/scan-code/index')">
              <image class="w-46rpx h-46rpx" src="@img/chef/110.png"></image>
              <view class="text-30rpx text-#333 lh-30rpx ml-12rpx">{{ t('pages.home.scanCode') }}</view>
            </view>
            <view class="absolute top-50% -translate-y-50% left-50% -translate-x-1/2 z-10 pt-16rpx">
              <title-store @changeStore="emits('changeStore')"/>
            </view>
            <view class="w-46rpx h-46rpx relative" @click="navigateTo('/pages-user/pages/message/index')">
              <view v-if="userStore.unreadMessageCount > 0"
                    class="w-10rpx h-10rpx bg-red-5 rounded-50% absolute top-0 right-0"></view>
              <image class="w-46rpx h-46rpx" src="@img/chef/114.png"></image>
            </view>
          </view>
        </view>
      </template>
      <view
          v-show="loading"
          class="animate-in fade-in animate-ease-out animate-duration-300"
      >
        <home-skeleton/>
      </view>
      <view
          v-if="!loading"
          class="animate-in fade-in animate-ease-in animate-duration-300"
      >
        <view class="pt-55rpx">
          <!-- 营业数据 -->
          <view class="mx-30rpx rounded-30rpx bg-white px-20rpx pt-30rpx pb-28rpx">
            <view class="flex items-center mb-48rpx">
              <image class="w-40rpx h-40rpx" src="@img/chef/111.png"></image>
              <view class="text-30rpx text-#333 lh-30rpx ml-10rpx font-bold tracking-[.04em]">
                {{ t('pages.home.dataStatistics') }}
              </view>
            </view>
            <view class="grid grid-cols-3 gap-y-47rpx">
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/home-order/today')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{ storeInfo?.todayOrderNum || 0 }}</view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.todayOrder') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/home-order/yesterday')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{
                    storeInfo?.yesterdayOrderNum || 0
                  }}
                </view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.yesterdayOrder') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/home-order/month-order')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{ storeInfo?.monthOrderNum || 0 }}</view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.monthOrder') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/sales-record/index')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{ storeInfo?.todayIncome || 0 }}</view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.todayAmount') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/income/index')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{ storeInfo?.monthIncome || 0 }}</view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.monthAmount') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/income/index')">
                <view class="text-34rpx text-#333 lh-34rpx mb-20rpx font-500">{{ storeInfo?.totalIncome || 0 }}</view>
                <view class="text-22rpx text-#7D7D7D lh-22rpx">{{ t('pages.home.totalAmount') }}</view>
              </view>
            </view>
          </view>

          <view class="mx-30rpx my-26rpx h-218rpx relative"
                @click="navigateTo('/pages-user/pages/cooking-machine/index')">
            <image class="w-full h-full" src="@img/chef/113.png"></image>
            <view class="absolute top-0 left-0 pr-145rpx px-30rpx py-20rpx">
              <view class="text-36rpx text-#333 font-bold">{{ t('pages.home.card-title') }}</view>
              <view class="text-24rpx text-#935D04 lh-24rpx my-12rpx">{{ t('pages.home.card-desc') }}</view>
              <text
                  class=" inline-block h-52rpx lh-52rpx text-center bg-#935D04 rounded-full px-20rpx text-24rpx text-#FBE3C3">
                {{ t('pages.home.view') }}
              </text>
            </view>
          </view>

          <!-- 营销工具 -->
          <view class="px-30rpx py-36rpx bg-white">
            <view class="text-36rpx text-#333 font-bold lh-36rpx mb-48rpx tracking-[.04em]">
              {{ t('pages.home.commonTools') }}
            </view>
            <view class="grid grid-cols-4">
              <view class="flex flex-col items-center relative"
                    @click="navigateTo('/pages-user/pages/home-order/refund-order')">
                <view
                    v-if="storeInfo?.refundOrderNum && +storeInfo?.refundOrderNum > 0"
                    class="absolute top--10rpx right-40rpx z-2 min-w-36rpx h-36rpx rounded-full bg-#FF1212 text-28rpx text-#fff center">
                  {{ +storeInfo?.refundOrderNum > 99 ? '99+' : storeInfo?.refundOrderNum }}
                </view>
                <image class="w-52rpx h-52rpx mb-24rpx" src="@img/chef/101.png"></image>
                <view class="text-24rpx text-#333 lh-20rpx">{{ t('pages.home.refundOrders') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/income/index')">
                <image class="w-52rpx h-52rpx mb-24rpx" src="@img/chef/102.png"></image>
                <view class="text-24rpx text-#333 lh-20rpx">{{ t('pages.home.myIncome') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/recipe/index')">
                <image class="w-52rpx h-52rpx mb-24rpx" src="@img/chef/103.png"></image>
                <view class="text-24rpx text-#333 lh-20rpx">{{ t('pages.home.recipes') }}</view>
              </view>
              <view class="flex flex-col items-center" @click="navigateTo('/pages-user/pages/coupons/index')">
                <image class="w-52rpx h-52rpx mb-24rpx" src="@img/chef/104.png"></image>
                <view class="text-24rpx text-#333 lh-20rpx">{{ t('pages.home.coupons') }}</view>
              </view>
            </view>
          </view>

          <!-- 订单列表 -->
          <view class="pt-10rpx pb-36rpx bg-white mt-26rpx mb-37rpx">
            <wd-tabs v-model="currentTabs" :lineWidth="67" animated color="#14181B" inactiveColor="#666666"
                     sticky @change="tabsChange">
              <template v-for="(item, index) in orderTabsList" :key="item">
                <wd-tab :title="item.title"></wd-tab>
              </template>
            </wd-tabs>

            <view v-if="userStore.isLogin" class="px-30rpx pt-34rpx">
              <view v-show="currentTabs === 0" class="bg-#F6F6F6 px-20rpx py-28rpx rounded-16rpx">
                <template v-for="item in todayOrderList">
                  <view class="w-full p-20rpx rounded-16rpx bg-white mb-10rpx last:mb-0">
                    <order-item :item="item"/>
                  </view>
                </template>
                <view v-if="todayOrderList.length === 0" class="py-100rpx center">
                  <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
                </view>
                <view
                    class="mx-auto mt-24rpx text-24rpx text-#333 w-128rpx h-40rpx rounded-40rpx center border-#666666 border-solid border-1px"
                    @click="viewAll">
                  View all
                </view>
              </view>
              <view v-show="currentTabs === 1" class="bg-#F6F6F6 px-20rpx py-28rpx rounded-16rpx">
                <template v-for="item in reservationList">
                  <reservation-item :item="item" class="mb-10rpx last:mb-0rpx"></reservation-item>
                </template>
                <view v-if="reservationList.length === 0" class="py-100rpx center">
                  <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
                </view>
                <view
                    class="mx-auto mt-24rpx text-24rpx text-#333 w-128rpx h-40rpx rounded-40rpx center border-#666666 border-solid border-1px"
                    @click="viewAll">
                  View all
                </view>
              </view>
              <scroll-view v-if="currentTabs === 2" scroll-x="true">
                <view class="flex items-center gap-28rpx">
                  <template v-for="(item, index) in recentDays">
                    <view
                        :class="[selectedDate === index ? 'border-#333333 border-solid border-1px text-#333 font-500' : 'text-#999']"
                        class="w-140rpx h-56rpx rounded-56rpx bg-#F6F6F6 center text-28rpx"
                        @click="clickSelectedDate(index)"
                    >{{ item }}
                    </view>
                  </template>
                </view>
              </scroll-view>
              <view v-show="currentTabs === 2" class="bg-#F6F6F6 px-20rpx py-28rpx rounded-16rpx mt-28rpx">
                <template v-for="item in todayOrderList">
                  <view class="w-full p-20rpx rounded-16rpx bg-white mb-10rpx last:mb-0">
                    <order-item :item="item"/>
                  </view>
                </template>
                <view v-if="todayOrderList.length === 0" class="py-100rpx center">
                  <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
                </view>
                <view
                    class="mx-auto mt-24rpx text-24rpx text-#333 w-128rpx h-40rpx rounded-40rpx center border-#666666 border-solid border-1px"
                    @click="viewAll">
                  View all
                </view>
              </view>
            </view>
            <view v-else class="py-100rpx center">
              <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
            </view>
          </view>

          <!-- end -->
          <view class="px-104rpx flex-center-sb pb-37rpx">
            <image class="w-150rpx h-16rpx" src="@img/chef/105.png"></image>
            <view class="text-24rpx text-#999 lh-24rpx mx-20rpx">It's already the end~</view>
            <image class="w-150rpx h-16rpx rotate-180" src="@img/chef/105.png"></image>
          </view>
        </view>
      </view>
      <template #bottom>
        <view class="h-50px"></view>
        <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
      </template>
    </z-paging>
  </view>
</template>

<style lang="scss" scoped>
:deep(.wd-tabs__nav-item) {
  font-size: 30rpx !important;

  &.is-active {
    font-size: 34rpx !important;
  }
}

:deep(.wd-tabs__line) {
  border-radius: 0 !important;
  height: 10rpx !important;
  bottom: 0 !important;
}
</style>
