<script lang="ts" setup>
import {appMerchantMenuMenuListByMerchantPost} from "@/service";
import {useUserStore} from "@/store";

const userStore = useUserStore()
const {t} = useI18n();
const show = ref(false);
/** 与 wd-picker-view 的 value-key 一致，存菜单 id（非列索引） */
const pickerValue = ref<string | number>('')
const emits = defineEmits(['confirm'])

// 默认分页配置（避免一次请求 1000 条）
const DEFAULT_PAGE_SIZE = 10;
const DEFAULT_PAGE_NUM = 1;

type MenuColumnItem = {
  value: string | number
  label: string
}

/** 打开选择器；selectedMenuId 为当前概览选中的菜单 id，用于回显 */
async function onOpen(selectedMenuId?: string | number) {
  await getMenuListByMerchant()
  if (columns.value.length === 0) {
    uni.showToast({
      title: t('pages.menu.pickerNoMenu'),
      icon: 'none',
    })
    return
  }
  const match = selectedMenuId != null && selectedMenuId !== ''
    ? columns.value.find((c) => String(c.value) === String(selectedMenuId))
    : undefined
  pickerValue.value = match ? match.value : columns.value[0].value
  show.value = true
}

const columns = ref<MenuColumnItem[]>([])

async function getMenuListByMerchant() {
  if (!userStore.isLogin) return

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

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

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

    // 按 total 或 “本页不足 pageSize” 判断结束，保证符合分页语义
    if ((typeof res.total === 'number' && allRows.length >= res.total) || rows.length < DEFAULT_PAGE_SIZE) {
      break
    }

    pageNum += 1
    // 安全阈值，避免后端异常导致死循环
    if (pageNum > 200) break
  }

  columns.value = allRows.map((item) => ({
    value: item.id,
    label: item.menuName,
  }))
}


function handleClose() {
  show.value = false;
}

function handleSubmit() {
  if (columns.value.length === 0) {
    uni.showToast({
      title: t('pages.menu.pickerNoMenu'),
      icon: 'none',
    })
    return
  }
  const pv = pickerValue.value
  if (pv === '' || pv === undefined || pv === null) {
    uni.showToast({
      title: t('pages.menu.pickerSelectValidMenu'),
      icon: 'none',
    })
    return
  }
  const isValid = columns.value.some((c) => String(c.value) === String(pv))
  if (!isValid) {
    uni.showToast({
      title: t('pages.menu.pickerSelectValidMenu'),
      icon: 'none',
    })
    return
  }
  emits('confirm', String(pv))
  handleClose()
}

defineExpose({
  onOpen,
});
</script>

<template>
  <view>
    <wd-popup
        v-model="show"
        position="bottom"
        @close="handleClose"
    >
      <view>
        <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
          <view class="text-30rpx text-#999" @click="handleClose">{{ t('common.cancel') }}</view>
          <view class="text-34rpx text-#333">{{ t('common.select') }} {{ t('common.menus') }}</view>
          <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
        </view>
        <view class="bg-#fff px-54rpx py-56rpx">
          <wd-picker-view
              v-if="show"
              v-model="pickerValue"
              :columns="columns"
              label-key="label"
              value-key="value"
          />
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped>
:deep(.uni-picker-view-wrapper) {
  & > uni-picker-view-column:first-of-type .uni-picker-view-group {
    .uni-picker-view-indicator {
      border-radius: 20rpx 0 0 20rpx !important;

      &:after {
        border: none;
      }

      &:before {
        border: none;
      }
    }
  }
}

:deep(.wd-picker-view-column__item) {
  line-height: 94rpx !important;
}

:deep(.uni-picker-view-indicator) {
  height: 94rpx !important;
}
</style>