<template>
  <view class="page-container">
    <NavBar :title="t('moldLedger.moduleName')" />

    <view class="filter-bar">
      <view class="keyword-box">
        <input
          id="mold-ledger-keyword-input"
          v-model="searchKeyword"
          class="keyword-input"
          type="text"
          :placeholder="t('moldLedger.searchPlaceholder')"
          placeholder-class="placeholder"
          :focus="keywordFocus"
          confirm-type="search"
          @blur="keywordFocus = false"
          @confirm="handleSearch"
        />
      </view>
      <view class="status-box" @click="openStatusPicker">
        <text class="status-box-text">{{ selectedStatusLabel || t('moldLedger.allStatus') }}</text>
        <uni-icons type="bottom" size="14" color="#9ca3af"></uni-icons>
      </view>
      <view class="reset-filter-btn" @click="resetFilters">{{ t('common.reset') }}</view>
    </view>

    <scroll-view
      scroll-y
      class="content-scroll"
      :scroll-top="scrollTop"
      @scroll="handleScroll"
      @scrolltolower="loadMore"
      :lower-threshold="80"
    >
      <view class="list-wrap">
        <view v-for="item in list" :key="item.id" class="ledger-card" @click="openDetail(item)">
          <view class="card-main">
            <view class="card-top">
              <text class="ledger-name">{{ textValue(item.code) }}</text>
              <view :class="['status-chip', statusClass(item.status)]">{{ moldStatusText(item.status) }}</view>
            </view>
            <view class="info-row">
              <text class="info-label">{{ t('moldLedger.name') }}</text>
              <text class="info-value">{{ textValue(item.name) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">{{ t('moldLedger.product') }}</text>
              <text class="info-value">{{ textValue(item.productName) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">{{ t('moldLedger.createTime') }}</text>
              <text class="info-value">{{ formatDateTime(item.createTime) }}</text>
            </view>
          </view>
          <view class="card-actions">
            <view class="card-action delete" @click.stop="confirmDelete(item)">
              <u-icon name="trash" size="22" color="#dc2626"></u-icon>
            </view>
          </view>
        </view>

        <view v-if="loading && pageNo === 1" class="loading-text">{{ t('functionCommon.loading') }}</view>
        <view v-else-if="!list.length" class="empty-text">{{ t('moldLedger.empty') }}</view>
        <view v-else-if="loadingMore" class="loading-text">{{ t('functionCommon.loadingMore') }}</view>
        <view v-else-if="finished" class="finished-text">{{ t('functionCommon.noMoreData') }}</view>
      </view>
    </scroll-view>

    <view v-if="showGoTop" class="go-top-btn" @click="goTop">
      <text class="go-top-icon">↑</text>
    </view>

    <uni-popup ref="statusPickerRef" type="bottom" background-color="#fff">
      <view class="picker-content">
        <view class="picker-header">
          <text class="picker-title">{{ t('moldLedger.selectMoldStatus') }}</text>
          <view class="picker-clear" @click="resetStatus">
            <text class="picker-clear-text">{{ t('moldLedger.clear') }}</text>
          </view>
        </view>
        <scroll-view scroll-y class="picker-list">
          <view
            v-for="option in statusOptions"
            :key="String(option.value)"
            class="picker-item"
            @click="selectStatus(option)"
          >
            <text class="picker-text">{{ option.label }}</text>
            <text v-if="selectedStatus === option.value" class="picker-check">✓</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <sv-focus-no-keyboard ref="focusNoKeyboardRef"></sv-focus-no-keyboard>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import NavBar from '@/components/common/NavBar.vue'
import CopyButton from '@/components/common/CopyButton.vue'
import { deleteMoldBrand, getMoldBrandPage } from '@/api/mes/mold'
import { DICT_TYPE, getDictLabel, initAllDict } from '@/utils/dict'

const { t } = useI18n()
const statusPickerRef = ref(null)
const list = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const finished = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const selectedStatus = ref(undefined)
const scrollTop = ref(0)
const showGoTop = ref(false)
const keywordFocus = ref(false)
const focusNoKeyboardRef = ref(null)
const keywordInputSelector = '#mold-ledger-keyword-input input, input#mold-ledger-keyword-input'

const statusOptions = computed(() => {
  const options = []
  for (let i = 0; i <= 9; i += 1) {
    const label = getDictLabel(DICT_TYPE.ERP_MOLD_STATUS, i, '')
    if (label && label !== String(i)) {
      options.push({ label, value: i })
    }
  }
  return options
})

const selectedStatusLabel = computed(() => {
  const current = statusOptions.value.find((item) => item.value === selectedStatus.value)
  return current ? current.label : ''
})

onLoad(async () => {
  await initAllDict()
  await fetchList(true)
})

onReady(() => {
  focusKeywordNoKeyboard()
})

function activateKeywordFocus() {
  keywordFocus.value = false
  nextTick(() => {
    keywordFocus.value = true
  })
}

function focusKeywordNoKeyboard() {
  nextTick(() => {
    setTimeout(() => {
      focusNoKeyboardRef.value?.focus(keywordInputSelector)
    }, 80)
  })
}

async function handleSearch() {
  await fetchList(true)
}

async function clearSearch() {
  searchKeyword.value = ''
  await fetchList(true)
}

async function resetFilters() {
  searchKeyword.value = ''
  selectedStatus.value = undefined
  activateKeywordFocus()
  await fetchList(true)
}

function openStatusPicker() {
  statusPickerRef.value?.open()
}

async function selectStatus(option) {
  selectedStatus.value = option.value
  statusPickerRef.value?.close()
  await fetchList(true)
}

async function resetStatus() {
  selectedStatus.value = undefined
  statusPickerRef.value?.close()
  await fetchList(true)
}

async function loadMore() {
  if (loading.value || loadingMore.value || finished.value) return
  pageNo.value += 1
  await fetchList(false)
}

async function fetchList(reset) {
  if (reset) {
    pageNo.value = 1
    finished.value = false
  }
  if (pageNo.value === 1) {
    loading.value = true
  } else {
    loadingMore.value = true
  }
  try {
    const keyword = searchKeyword.value.trim()
    const res = await getMoldBrandPage({
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      code: keyword || undefined,
      name: keyword || undefined,
      status: selectedStatus.value
    })
    const page = normalizePageData(res)
    total.value = page.total
    list.value = reset ? page.list : [...list.value, ...page.list]
    finished.value = list.value.length >= total.value || page.list.length < pageSize.value
  } catch (e) {
    if (!reset) pageNo.value = Math.max(1, pageNo.value - 1)
    uni.showToast({ title: t('functionCommon.loadFailed'), icon: 'none' })
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

function normalizePageData(res) {
  const root = res && res.data !== undefined ? res.data : res
  const pageResult = root?.pageResult || root?.data?.pageResult || root?.data || root || {}
  const candidateList = pageResult?.list || pageResult?.rows || pageResult?.records || []
  const candidateTotal = pageResult?.total ?? root?.total ?? root?.data?.total ?? candidateList.length
  return {
    list: Array.isArray(candidateList) ? candidateList : [],
    total: Number(candidateTotal || 0)
  }
}

function handleScroll(e) {
  const top = e?.detail?.scrollTop || 0
  showGoTop.value = top > 600
}

function goTop() {
  scrollTop.value = 0
}

function openDetail(item) {
  const id = item?.id
  if (id === undefined || id === null) {
    uni.showToast({ title: t('moldLedger.noIdView'), icon: 'none' })
    return
  }
  uni.navigateTo({
    url: `/pages_function/pages/moldLedger/detail?id=${encodeURIComponent(String(id))}`
  })
}

function confirmDelete(item) {
  const id = item?.id
  if (id === undefined || id === null) {
    uni.showToast({ title: t('moldLedger.noIdDelete'), icon: 'none' })
    return
  }
  uni.showModal({
    title: t('functionCommon.confirmDelete'),
    content: t('moldLedger.confirmDeleteContent', { name: textValue(item?.name) }),
    success: async (res) => {
      if (!res.confirm) return
      try {
        await deleteMoldBrand(id)
        uni.showToast({ title: t('functionCommon.deleteSuccess'), icon: 'success' })
        await fetchList(true)
      } catch (e) {
        uni.showToast({ title: t('functionCommon.deleteFailed'), icon: 'none' })
      }
    }
  })
}

function moldStatusText(status) {
  return getDictLabel(DICT_TYPE.ERP_MOLD_STATUS, status, textValue(status))
}

function statusClass(status) {
  const label = moldStatusText(status)
  if (label.includes('正常') || label.includes('使用') || label.includes('待用') || label.toUpperCase() === 'OK') {
    return 'status-normal'
  }
  if (label.includes('修') || label.includes('报废') || label.includes('停') || label.toUpperCase() === 'NG') {
    return 'status-danger'
  }
  return 'status-warning'
}

function textValue(value) {
  if (value === 0) return '0'
  if (value === false) return t('functionCommon.no')
  if (value === true) return t('functionCommon.yes')
  if (value === null || value === undefined) return '-'
  const text = String(value).trim()
  return text || '-'
}

function formatDateTime(value) {
  if (!value) return '-'
  if (Array.isArray(value) && value.length >= 3) {
    const [y, m, d, hh = 0, mm = 0, ss = 0] = value
    const pad = (n) => String(n).padStart(2, '0')
    return `${y}-${pad(m)}-${pad(d)} ${pad(hh)}:${pad(mm)}:${pad(ss)}`
  }
  const text = String(value).trim()
  if (!text) return '-'
  const numeric = Number(text)
  if (Number.isFinite(numeric)) {
    const timestamp = text.length === 10 ? numeric * 1000 : numeric
    const date = new Date(timestamp)
    if (!Number.isNaN(date.getTime())) {
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
  }
  const date = new Date(text)
  if (!Number.isNaN(date.getTime())) {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
  }
  return text
}

</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f3f4f6;
}

.filter-bar {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 150rpx 96rpx;
  align-items: center;
  gap: 14rpx;
  padding: 18rpx 28rpx 20rpx;
}

.keyword-box,
.status-box,
.reset-filter-btn {
  height: 66rpx;
  background: #ffffff;
  border: 1rpx solid #d9dde5;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.keyword-box {
  padding: 0 20rpx;
}

.keyword-input {
  width: 100%;
  font-size: 26rpx;
  color: #374151;
}

.status-box {
  justify-content: space-between;
  padding: 0 18rpx;
}

.status-box-text,
.placeholder {
  font-size: 26rpx;
}

.status-box-text {
  color: #374151;
}

.placeholder {
  color: #a8adb7;
}

.reset-filter-btn {
  justify-content: center;
  font-size: 24rpx;
  color: #4b5563;
}

.content-scroll {
  width: 100%;
}

.list-wrap {
  padding: 0 28rpx 140rpx;
}

.ledger-card {
  margin-bottom: 18rpx;
  border-radius: 12rpx;
  background: #ffffff;
  box-shadow: none;
  overflow: hidden;
}

.card-main {
  padding: 24rpx;
}

.card-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.ledger-name {
  max-width: 420rpx;
  font-size: 36rpx;
  line-height: 44rpx;
  color: #24456b;
  font-weight: 700;
}

.status-chip {
  flex-shrink: 0;
  padding: 8rpx 18rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  font-weight: 600;
  line-height: 1.2;
}

.status-normal {
  color: #15803d;
  background: #dcfce7;
}

.status-warning {
  color: #c2410c;
  background: #ffedd5;
}

.status-danger {
  color: #dc2626;
  background: #fee2e2;
}

.code-row {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 14rpx;
}

.ledger-code {
  color: #9ca3af;
  font-size: 26rpx;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  margin-top: 14rpx;
}

.info-label {
  font-size: 28rpx;
  color: #9ca3af;
  font-weight: 600;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  text-align: right;
  font-size: 30rpx;
  color: #9ca3af;
  word-break: break-all;
}

.card-actions {
  padding: 18rpx 24rpx;
  border-top: 1rpx solid #f1f5f9;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 28rpx;
}

.card-action {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56rpx;
  height: 56rpx;
}

.loading-text,
.empty-text,
.finished-text {
  padding: 28rpx 0;
  text-align: center;
  color: #9ca3af;
  font-size: 26rpx;
}

.empty-text {
  padding-top: 160rpx;
}

.go-top-btn {
  position: fixed;
  right: 32rpx;
  bottom: calc(56rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  justify-content: center;
  width: 92rpx;
  height: 92rpx;
  border-radius: 46rpx;
  background: rgba(31, 75, 121, 0.84);
  box-shadow: 0 14rpx 30rpx rgba(24, 63, 108, 0.24);
}

.go-top-icon {
  color: #ffffff;
  font-size: 32rpx;
}

.picker-content {
  padding: 24rpx 24rpx 36rpx;
  border-radius: 28rpx 28rpx 0 0;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.picker-title {
  color: #1f2d3d;
  font-size: 30rpx;
  font-weight: 700;
}

.picker-clear-text {
  color: #1f61ff;
  font-size: 26rpx;
}

.picker-list {
  max-height: 480rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 6rpx;
  border-bottom: 1rpx solid #edf1f6;
}

.picker-text {
  color: #243447;
  font-size: 28rpx;
}

.picker-check {
  color: #1f61ff;
  font-size: 30rpx;
}
</style>
