<script lang="ts" setup>
import Fuse from "fuse.js";
import {
  appMerchantDishListPost,
  appMerchantDishRemovePost,
  appMerchantMenuMenuDetailPost,
  appMerchantMenuMenuListByMerchantPost,
  type MerchantDishVo,
} from "@/service";
import {useMessage} from "wot-design-uni";
import {useUserStore} from "@/store";

const userStore = useUserStore()
const {t} = useI18n()

const message = useMessage();

// 默认分页配置（菜单相关接口仍然依赖）
const DEFAULT_PAGE_SIZE = 10;
const DEFAULT_PAGE_NUM = 1;

const props = defineProps<{
  tabIndex: number | string
  currentIndex: number | string
}>()
const emits = defineEmits(['changeMenu'])

function changeMenu() {
  emits('changeMenu')
}

const tabIndexNum = computed(() => +props.tabIndex)

watch(
    () => props.currentIndex,
    (newVal) => {
      console.log('111', newVal, props.tabIndex)
      if (+newVal === props.tabIndex) {
        // 切换到当前tab，触发分页加载（pageNum会由z-paging自动递增）
        paging.value?.reload()
      }
    },
    {immediate: true},
)

// 分页数据源：tab1=菜单详情内dishList(本地分页)，tab2=菜单列表(后端分页)，tab3=菜品列表(后端分页)
function queryByTab(pageNum: number, pageSize: number) {
  // tab1：菜单概览-菜单下菜品（本地分页）
  if (tabIndexNum.value === 1) {
    return new Promise<IResData<any>>(async (resolve) => {
      await ensureMenuListLoaded()
      await ensureMenuDetailLoaded()
      const all = menuDishListData.value || []
      const start = (pageNum - 1) * pageSize
      resolve({
        rows: all.slice(start, start + pageSize),
        total: all.length,
      } as any)
    })
  }

  // tab2：周菜单管理-菜单列表（后端分页）
  if (tabIndexNum.value === 2) {
    return new Promise<IResData<any>>((resolve) => {
      if (!userStore.isLogin) return resolve({rows: [], total: 0} as any)
      appMerchantMenuMenuListByMerchantPost({
        params: {
          pageNum,
          pageSize,
        },
      }).then((res: any) => {
        resolve({
          ...(res as any),
          rows: (res as any).rows || [],
          total: (res as any).total || 0,
        })
      })
    })
  }

  // tab3：菜品列表（后端分页）
  return new Promise<IResData<any>>((resolve) => {
    if (!userStore.isLogin) return resolve({rows: [], total: 0} as any)
    appMerchantDishListPost({
      params: {
        pageNum,
        pageSize,
      },
      // @ts-ignore 后端 body 暂无筛选条件，这里传空对象
      body: {},
    }).then((res: any) => {
      resolve({
        ...(res as any),
        rows: (res as any).rows || [],
        total: (res as any).total || 0,
      })
    })
  })
}

const {paging, dataList, loading, queryList} = usePage<any>(queryByTab)

function navigateTo(url: string) {
  uni.navigateTo({url})
}


// 获取当前商户的菜单列表
const menuList = ref<any[]>([])
// 当前选中的菜单索引
const currentMenuIndex = ref(0)
// 当前选中的菜单数据
const currentMenu = computed(() => {
  return menuList.value[currentMenuIndex.value] || {}
})

async function ensureMenuListLoaded() {
  // 仅tab1需要完整menuList用于头部展示 & indexChangeMenu定位
  if (tabIndexNum.value !== 1) return
  if (!userStore.isLogin) return
  if (menuList.value.length > 0) return

  const allRows: any[] = []
  let pageNum = DEFAULT_PAGE_NUM

  while (true) {
    const res: any = await appMerchantMenuMenuListByMerchantPost({
      params: {
        pageSize: DEFAULT_PAGE_SIZE,
        pageNum,
      },
    })

    const rows = res.rows || []
    allRows.push(...rows)

    if ((typeof res.total === 'number' && allRows.length >= res.total) || rows.length < DEFAULT_PAGE_SIZE) {
      break
    }

    pageNum += 1
    if (pageNum > 200) break
  }

  menuList.value = allRows
  if (menuList.value.length > 0) {
    currentMenuIndex.value = 0
  }
}

const findIndexById = (array: any[], targetId: string | number) =>
    array.findIndex((item) => String(item.id) === String(targetId));

function indexChangeMenu(id: string) {
  // 最新的菜单ID
  console.log('indexChangeMenu', id)
  const idx = findIndexById(menuList.value, id)
  currentMenuIndex.value = idx >= 0 ? idx : 0
  console.log('当前选中的菜单索引', currentMenuIndex.value)
  getMenuDetail().then(() => {
    paging.value?.reload()
  })
}

// 菜单下面的菜品数据（完整数据，用于tab1本地分页与搜索）
const menuDishListData = ref<MerchantDishVo[]>([])

async function getMenuDetail() {
  const recipeId = currentMenu.value?.id
  if (recipeId === undefined || recipeId === null || String(recipeId).trim() === '') {
    menuDishListData.value = []
    return
  }
  return appMerchantMenuMenuDetailPost({
    params: {
      recipeId
    }
  }).then((res: any) => {
    console.log('获取菜单详情', res)
    if (res.data && (res.data as any).dishList) {
      menuDishListData.value = (res.data as any).dishList || []
    }
  }).catch(err => {
    console.error('获取菜单详情失败', err)
  })
}

async function ensureMenuDetailLoaded() {
  if (tabIndexNum.value !== 1) return
  if (!currentMenu.value?.id) return
  // 没有数据时才请求，避免每次上拉都重复打接口
  if (menuDishListData.value.length > 0) return
  await getMenuDetail()
}

function handleClickMenu(item: any) {
  uni.navigateTo({
    url: `/pages-user/pages/menu/index?id=${item.id}`
  })
}

// 点击菜品
function handleClickDish(item: MerchantDishVo) {
  uni.navigateTo({
    url: `/pages-user/pages/food/add-food?id=${item.id}`
  })
}

// 库存文案相关辅助方法
function hasStock(item: any) {
  return !!(item as any)?.stock
}

function getStock(item: any) {
  const stock = (item as any)?.stock
  if (stock === undefined || stock === null) return ''
  return Number(stock).toFixed(0)
}

/** 已售完：有明确库存且数量 <= 0（未返回 stock 时不视为售完，避免误盖） */
function isSoldOut(item: any) {
  const stock = (item as any)?.stock
  if (stock === undefined || stock === null || stock === '') return false
  const n = Number(stock)
  return !Number.isNaN(n) && n <= 0
}

function initData() {
  console.log('页面回来的时候获取最新的数据', props.currentIndex)
  if (+props.currentIndex === +props.tabIndex) {
    paging.value?.reload()
  }
}

const swipeActionValue = ref<'close' | 'right' | 'left'>('close')

// 打开删除操作
function openDeleteAction() {
  swipeActionValue.value = swipeActionValue.value === 'close' ? 'right' : 'close'
}

// 是否显示关键词输入框
const isShowSearch = ref(false)
// 搜索关键词
const keyword = ref('')

function handleSearch() {
  isShowSearch.value = true
}

type DishSearchResult = {
  item: MerchantDishVo
}
const searchResult = ref<DishSearchResult[]>([]);

function handleConfirmSearch() {
  console.log('handleConfirmSearch', keyword.value)
  const fuse = new Fuse<MerchantDishVo>(menuDishListData.value, {
    threshold: 0.2,
    keys: ["dishName", "dishDescription"],
  });
  searchResult.value = fuse.search(keyword.value)
}

function inputClear() {
  keyword.value = ''
  isShowSearch.value = false
}

// 删除菜品
function deleteRecipe(item: MerchantDishVo) {
  message
      .confirm({
        title: t("common.prompt.system-prompt"),
        msg: `${t("common.prompt.system-prompt-delete")}`,
        confirmButtonText: t("common.yes"),
        cancelButtonText: t("common.no"),
        cancelButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx  !lh-42rpx !font-bold !border-#666666   !rounded-20rpx",
        },
        confirmButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx !lh-42rpx !font-bold  !bg-primary  !rounded-20rpx",
        },
      })
      .then(async () => {
        appMerchantDishRemovePost({
          body: [item.id as number],
        }).then((res) => {
          uni.showToast({
            title: t('toast.deleteSuccess'),
            icon: 'none'
          })
          // 获取菜单详情
          getMenuDetail()
        })
      })
      .catch(() => {
      });
}

function getCurrentMenuId() {
  return currentMenu.value?.id as string | number | undefined
}

defineExpose({
  initData,
  indexChangeMenu,
  getCurrentMenuId
})

// 当前商家是否已经入驻了
const isMerchant = computed(() => {
  return userStore.currentMerchantToken.length > 0
})
</script>

<template>
  <view class="h-full">
    <z-paging ref="paging" v-model="dataList" :auto="false" :fixed="false"
              @onRestore="initData" @query="queryList">
      <template v-if="+currentIndex === 1">
        <view class="px-30rpx pt-36rpx pb-44rpx border-b-#DFDFDF border-b-solid border-b-1rpx">
          <view class="h-280rpx bg-#FFEDD4 rounded-30rpx px-28rpx py-52rpx">
            <view class="text-32rpx lh-32rpx text-#333 font-500 mb-28rpx pr-116rpx">
              {{ t('pages.menu.tipsTitle') }}
            </view>
            <view class="flex items-center">
              <view class="text-28rpx lh-28rpx text-#999 mr-22rpx">
                {{ t('pages.menu.tipsDesc') }}
              </view>
              <image class="w-166rpx h-90rpx shrink-0" src="@img/chef/112.png"></image>
            </view>
          </view>
          <template v-if="menuList.length > 0">
            <view class="flex items-center text-40rpx lh-40rpx text-#333 font-500 mt-76rpx mb-20rpx"
                  @click="changeMenu">
              {{ currentMenu.menuName }}
              <image class="w-28rpx h-28rpx shrink-0 ml-10rpx" src="@img/chef/192.png"></image>
            </view>
            <view class="flex items-start justify-between">
              <view class="">
                <view class="text-32rpx lh-32rpx text-#333">
                  {{ t('pages.menu.menuHours') }}
                </view>
                <view class="text-26rpx lh-26rpx text-#999 my-12rpx">
                  {{ currentMenu.scheduleTimes }}
                </view>
                <!--                <view class="text-26rpx lh-26rpx text-#999">-->
                <!--                  11:00 AM - 7:00 PM-->
                <!--                </view>-->
              </view>
              <view class="h-64rpx w-150rpx center bg-#F2F2F2 rounded-64rpx text-26rpx text-#333"
                    @click="handleClickMenu({ id: currentMenu.id })">
                {{ t('common.edit') }}
              </view>
            </view>
          </template>
        </view>
        <template v-if="menuList.length === 0">
          <view class="py-100rpx center">
            <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
          </view>
        </template>
        <view v-else class="px-30rpx pt-44rpx pb-30rpx animate-in fade-in animate-ease-in animate-duration-300">
          <view v-if="menuDishListData.length > 0" class="flex-center-sb mb-44rpx">
            <view class="flex-1 flex items-center gap-28rpx">
              <image v-if="!isShowSearch"
                     class="w-64rpx h-64rpx shrink-0 animate-in fade-in animate-ease-out animate-duration-300"
                     src="@img/chef/199.png"
                     @click=handleSearch></image>
              <view v-if="isShowSearch"
                    class="h-64rpx flex-1 shrink-0 bg-#F2F2F2 rounded-64rpx flex items-center px-24rpx animate-in fade-in animate-ease-in animate-duration-300">
                <wd-input
                    v-model="keyword"
                    :focus="isShowSearch"
                    :focus-when-clear="true"
                    :placeholder="t('pages-user.recipe.enterPlaceholder')"
                    clearable
                    confirm-type="search"
                    custom-class="!text-30rpx !bg-transparent flex-1"
                    no-border
                    placeholderStyle="font-size: 30rpx;color: #999;"
                    use-prefix-slot
                    @clear="inputClear"
                    @confirm="handleConfirmSearch"
                >
                </wd-input>
              </view>
              <view class="h-64rpx w-142rpx center bg-#F2F2F2 rounded-64rpx text-26rpx text-#333"
                    @click="navigateTo('/pages-user/pages/food/add-food')">
                + {{ t('common.add') }}
              </view>
            </view>
            <image class="w-64rpx h-64rpx shrink-0 ml-30rpx" src="@img/chef/109.png" @click="openDeleteAction"></image>
          </view>
          <!--搜索结果数据-->
          <template v-if="isShowSearch">
            <template v-if="searchResult.length>0">
              <template v-for="(item, index) in searchResult" :key="item.item.id || index">
                <view :class="[index === 0 ? '' : 'mt-46rpx']" @click="handleClickDish(item.item)">
                  <view class="flex-center-sb">
                    <view
                        class="relative w-176rpx h-176rpx mr-28rpx shrink-0 rounded-24rpx overflow-hidden"
                    >
                      <image
                          :src="item.item.dishImage"
                          class="w-full h-full block"
                          mode="aspectFill"
                      ></image>
                      <image
                          v-if="isSoldOut(item.item)"
                          class="sold-out-cover"
                          mode="aspectFill"
                          src="/static/app/images/SoldOut.png"
                      ></image>
                    </view>
                    <view class="flex-1 h-176rpx">
                      <view class="text-33rpx lh-34rpx text-#333 font-500 mb-22rpx line-clamp-1 tracking-[.04em]">
                        {{ item.item.dishName }}
                      </view>
                      <view class="text-22rpx lh-22rpx text-#999 tracking-[.04em] line-clamp-1">
                        {{ t('pages.menu.introduction') }}：{{ item.item.dishDescription }}
                      </view>
                      <view class="mt-63rpx text-#333 text-30rpx font-500">
                        ${{ item.item.originalPrice }}
                      </view>
                    </view>
                  </view>
                </view>
              </template>
            </template>
            <template v-if="searchResult.length === 0">
              <view class="py-100rpx center">
                <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
              </view>
            </template>
          </template>
          <template v-else>
            <!-- tab1 使用本地分页后的 dataList 渲染，menuDishListData 仅用于搜索与总数据缓存 -->
            <template v-for="(item, index) in dataList" :key="item.id || index">
              <view :class="[index === 0 ? '' : 'mt-46rpx']">
                <wd-swipe-action v-model="swipeActionValue">
                  <view class="flex-center-sb" @click="handleClickDish(item)">
                    <view
                        class="relative w-176rpx h-176rpx mr-28rpx shrink-0 rounded-24rpx overflow-hidden"
                    >
                      <image
                          :src="item.dishImage ? item.dishImage.split(',')[0] : ''"
                          class="w-full h-full block"
                          mode="aspectFill"
                      ></image>
                      <image
                          v-if="isSoldOut(item)"
                          class="sold-out-cover"
                          mode="aspectFill"
                          src="/static/app/images/SoldOut.png"
                      ></image>
                    </view>
                    <view class="flex-1 h-176rpx">
                      <view class="text-33rpx lh-34rpx text-#333 font-500 mb-22rpx line-clamp-1 tracking-[.04em]">
                        {{ item.dishName }}
                      </view>
                      <view class="text-22rpx lh-22rpx text-#999 tracking-[.04em] line-clamp-1">
                        {{ t('pages.menu.introduction') }}：{{ item.dishDescription }}
                      </view>
                      <view class="mt-63rpx text-#333 text-30rpx font-500">
                        ${{ item.originalPrice }}
                      </view>
                    </view>
                  </view>
                  <template #right>
                    <view class="flex items-center text-30rpx lh-30rpx text-#fff">
                      <view class="w-152rpx h-200rpx bg-#FF2828 center" @click="deleteRecipe(item)">
                        {{ t('pages-user.recipe.index.delete') }}
                      </view>
                    </view>
                  </template>
                </wd-swipe-action>
              </view>
            </template>
          </template>
          <template v-if="menuDishListData.length === 0">
            <view class="py-100rpx center">
              <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
            </view>
          </template>
        </view>
      </template>
      <template v-else-if="+currentIndex === 2">
        <!-- 周菜单管理 -->
        <view class="px-30rpx pt-76rpx">
          <!-- Monday Menu 标题 -->
          <view class="text-40rpx lh-40rpx text-#333 font-500 mb-52rpx">
            {{ t('pages.menu.menu') }}
          </view>

          <!-- + New Menu 按钮 -->
          <view v-if="isMerchant" class="center mb-24rpx bg-#F2F2F2 rounded-32rpx w-222rpx h-64rpx"
                @click="navigateTo('/pages-user/pages/menu/index')">
            <image class="w-28rpx h-28rpx shrink-0 mr-10rpx" src="@img/chef/107.png"></image>
            <text class="text-26rpx text-#333 font-500">{{ t('pages.menu.addMenu') }}</text>
          </view>

          <!-- 菜单列表 -->
          <view class="">
            <!-- Monday Menu Item -->
            <template v-for="item in dataList" :key="item.id">
              <view class="flex-center-sb border-b-1rpx border-b-solid border-b-#F6F6F6 h-170rpx"
                    @click="handleClickMenu(item)">
                <view class="flex-1">
                  <text class="text-32rpx lh-32rpx text-#333 font-500 block mb-12rpx">{{ item.menuName }}</text>
                  <text class="text-28rpx lh-28rpx text-#999">{{ item.scheduleTimes }}</text>
                </view>
                <image class="w-32rpx h-32rpx shrink-0 rotate-0" src="@img/chef/115.png"></image>
              </view>
            </template>
            <template v-if="dataList.length === 0">
              <view class="py-100rpx center">
                <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
              </view>
            </template>
          </view>
        </view>
      </template>
      <template v-else>
        <view class="px-30rpx pt-76rpx pb-30rpx">
          <view class="text-40rpx lh-40rpx text-#333 mb-52rpx font-bold">{{ t('pages.menu.title') }}</view>
          <view v-if="isMerchant" class="center mb-52rpx bg-#F2F2F2 rounded-32rpx w-218rpx h-64rpx"
                @click="navigateTo('/pages-user/pages/food/add-food')">
            <image class="w-28rpx h-28rpx shrink-0 mr-10rpx" src="@img/chef/107.png"></image>
            <text class="text-26rpx text-#333 font-500">{{ t('pages.menu.add') }}</text>
          </view>
          <template v-for="(item, index) in dataList" :key="item.id || index">
            <view :class="[index === 0 ? '' : 'mt-46rpx']" class="flex-center-sb" @click="handleClickDish(item)">
              <view
                  class="relative w-176rpx h-176rpx mr-28rpx shrink-0 rounded-24rpx overflow-hidden bg-common"
              >
                <image
                    :src="item.dishImage ? item.dishImage.split(',')[0] : ''"
                    class="w-full h-full block"
                    mode="aspectFill"
                ></image>
                <image
                    v-if="isSoldOut(item)"
                    class="sold-out-cover"
                    mode="aspectFill"
                    src="/static/app/images/SoldOut.png"
                ></image>
              </view>
              <view class="flex-1 h-176rpx">
                <view class="text-33rpx lh-34rpx text-#333 font-500 mb-22rpx line-clamp-1 tracking-[.04em]">
                  {{ item.dishName }}
                </view>
                <view class="text-22rpx lh-22rpx text-#999 tracking-[.04em] line-clamp-1">
                  {{ t('pages.menu.introduction') }}：{{ item.dishDescription }}
                </view>
                <view class="flex-center-sb">
                  <view class="mt-63rpx text-#333 text-30rpx font-500">
                    ${{ item.originalPrice }}
                  </view>
                  <view class="mt-63rpx text-#333 text-30rpx font-500">
                    <template v-if="hasStock(item)">
                      {{ t('common.stock') }}: {{ getStock(item) }}
                    </template>
                  </view>
                </view>
              </view>
            </view>
          </template>

          <template v-if="dataList.length === 0">
            <view class="py-100rpx center">
              <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
            </view>
          </template>
        </view>
      </template>
    </z-paging>
  </view>
</template>

<style lang="scss" scoped>
.sold-out-cover {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  pointer-events: none;
}

:deep(.wd-input__clear) {
  background-color: transparent !important;
}
</style>