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

    <view class="filter-bar">
      <view class="keyword-box">
        <input
          v-model="searchKeyword"
          class="keyword-input"
          type="text"
          :placeholder="t('moldRepair.searchPlaceholder')"
          placeholder-class="placeholder"
          :focus="keywordFocus"
          confirm-type="search"
          @blur="keywordFocus = false"
          @input="onSearchInput"
          @confirm="handleSearch"
        />
      </view>
      <picker :range="statusLabels" :value="statusPickerIndex" @change="onStatusFilterChange">
        <view class="status-box">
          <text class="status-box-text">{{ selectedStatusLabel }}</text>
          <uni-icons type="bottom" size="14" color="#9ca3af"></uni-icons>
        </view>
      </picker>
      <view class="reset-filter-btn" @click="resetFilters">{{ t('functionCommon.reset') }}</view>
    </view>

    <scroll-view
      scroll-y
      class="list-scroll"
      :scroll-top="scrollTop"
      @scroll="onScroll"
      @scrolltolower="loadMore"
      :lower-threshold="80"
    >
      <view class="list-wrap">
        <view
          v-for="item in list"
          :key="item.id"
          class="repair-card"
          @click="openCard(item)"
        >
          <view class="card-main">
            <view class="card-top">
              <text class="repair-code">{{ textValue(item.repairCode) }}</text>
              <view :class="['repair-status-tag', getRepairStatusTagClass(item.repairStatus)]">{{ getRepairStatusText(item.repairStatus) }}</view>
            </view>
            <view class="equipment-row">
              <text class="equipment-label">{{ t('moldRepair.moldLabel') }}</text>
              <text class="equipment-value">{{ formatMoldDisplay(item) }}</text>
            </view>
            <view class="equipment-row">
               <text class="equipment-label">{{ t('moldRepair.reportTimeLabel') }}</text>
              <text class="repair-date">{{ formatDateValue(item.requireDate || item.createTime) }}</text>
            </view>
          </view>
          <view class="card-actions">
            <view v-if="canEdit(item)" class="card-action edit" @click.stop="openForm('update', item.id)">
              <u-icon name="edit-pen" size="22" color="#1d4ed8"></u-icon>
            </view>
            <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="state-text">{{ t('functionCommon.loading') }}</view>
        <view v-else-if="!list.length" class="state-text empty">{{ t('moldRepair.empty') }}</view>
        <view v-else-if="loadingMore" class="state-text">{{ t('functionCommon.loadingMore') }}</view>
        <view v-else-if="finished" class="state-text">{{ t('functionCommon.noMore') }}</view>
      </view>
    </scroll-view>

    <view v-if="showGoTop" class="go-top-btn" @click="goTop">
      <uni-icons type="top" size="20" color="#ffffff"></uni-icons>
    </view>

    <view class="add-btn" @click="openForm('create')">
      <text class="add-icon">+</text>
    </view>
  </view>
</template>

<script setup>
import { computed, nextTick, ref } from 'vue'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import NavBar from '@/components/common/NavBar.vue'
import {
  deleteMoldRepair,
  getMoldRepairPage
} from '@/api/mes/moldrepair'

const { t } = useI18n()
const searchKeyword = ref('')
const selectedStatus = ref('')
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 initialized = ref(false)
const scrollTop = ref(0)
const showGoTop = ref(false)
const keywordFocus = ref(false)
const selectedMoldId = ref('')

const statusOptions = computed(() => [
  { label: t('functionCommon.all'), value: '' },
  { label: t('moldRepair.statusPending'), value: '0' },
  { label: t('moldRepair.statusPassed'), value: '1' },
  { label: t('moldRepair.statusRejected'), value: '2' }
])

const statusLabels = computed(() => statusOptions.value.map((item) => item.label))
const statusPickerIndex = computed(() => {
  const index = statusOptions.value.findIndex((item) => item.value === selectedStatus.value)
  return index >= 0 ? index : 0
})
const selectedStatusLabel = computed(() => {
  const current = statusOptions.value.find((item) => item.value === selectedStatus.value)
  return current ? current.label : t('functionCommon.all')
})

onLoad(async () => {
  initialized.value = true
  activateKeywordFocus()
  await fetchList(true)
})

onShow(async () => {
  activateKeywordFocus()
  if (!initialized.value) return
  await fetchList(true)
})

onReachBottom(() => {
  loadMore()
})

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 params = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      repairCode: keyword || undefined,
      moldId: selectedMoldId.value || undefined,
      repairStatus: selectedStatus.value === '' ? undefined : selectedStatus.value
    }
    const res = await getMoldRepairPage(params)
    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 (error) {
    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 candidateList = root?.list || root?.rows || root?.records || root?.data?.list || root?.data?.rows || root?.data?.records || []
  const candidateTotal = root?.total ?? root?.data?.total ?? (Array.isArray(candidateList) ? candidateList.length : 0)
  return {
    list: Array.isArray(candidateList) ? candidateList : [],
    total: Number(candidateTotal || 0)
  }
}

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

function handleSearch() {
  uni.hideKeyboard()
  fetchList(true)
}

let searchTimer = null
function onSearchInput() {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    fetchList(true)
  }, 300)
}

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

function onStatusFilterChange(event) {
  const index = Number(event?.detail?.value || 0)
  selectedStatus.value = statusOptions.value[index]?.value ?? ''
  fetchList(true)
}

function canEdit(item) {
  return !isProcessedRepair(item?.repairStatus)
}

function canRepair(item) {
  return String(item?.status ?? '0') !== '1' && !isProcessedRepair(item?.repairStatus)
}

function isProcessedRepair(value) {
  const normalized = value === '' || value === null || value === undefined ? '0' : String(value)
  return normalized !== '0'
}

function openCard(item) {
  if (item?.id === undefined || item?.id === null) {
    uni.showToast({ title: t('moldRepair.noId'), icon: 'none' })
    return
  }
  if (canRepair(item)) {
    openForm('repair', item.id)
    return
  }
  openForm('detail', item.id)
}

function openForm(mode, id) {
  const query = [`mode=${encodeURIComponent(mode)}`]
  if (id !== undefined && id !== null) {
    query.push(`id=${encodeURIComponent(String(id))}`)
  }
  uni.navigateTo({
    url: `/pages_function/pages/moldRepair/form?${query.join('&')}`
  })
}

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

function onScroll(event) {
  const top = event?.detail?.scrollTop || 0
  showGoTop.value = top > 500
}

function goTop() {
  scrollTop.value = 0
}

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

function getRepairStatusText(value) {
  const normalized = value === '' || value === null || value === undefined ? '0' : String(value)
  if (normalized === '1') return t('moldRepair.statusPassed')
  if (normalized === '2') return t('moldRepair.statusRejected')
  return t('moldRepair.statusPending')
}

function getRepairStatusTagClass(value) {
  const normalized = value === '' || value === null || value === undefined ? '0' : String(value)
  if (normalized === '1') return 'tag-success'
  if (normalized === '2') return 'tag-danger'
  return 'tag-warning'
}

function formatDateValue(value) {
  if (value === null || value === undefined || value === '') return '-'
  const date = normalizeDate(value)
  if (!date) return textValue(value)
  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}`
}

function normalizeDate(value) {
  if (value instanceof Date && !Number.isNaN(value.getTime())) return value
  if (typeof value === 'number' || /^\d+$/.test(String(value || ''))) {
    const numeric = Number(value)
    if (!Number.isNaN(numeric)) {
      const date = new Date(numeric)
      if (!Number.isNaN(date.getTime())) return date
    }
  }
  if (typeof value === 'string') {
    const date = new Date(value.replace(/-/g, '/'))
    if (!Number.isNaN(date.getTime())) return date
  }
  return null
}

function formatMoldDisplay(item) {
  const name = String(item?.moldName ?? '').trim()
  const code = String(item?.moldCode ?? '').trim()
  if (name && code) return `${name}-${code}`
  if (name) return name
  if (code) return code
  return '-'
}

function textValue(value) {
  if (value === 0) return '0'
  if (value === null || value === undefined) return '-'
  const text = String(value).trim()
  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 4rpx 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 {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #4b5563;
}

.list-scroll {
  width: 100%;
}

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

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

.card-main {
  padding: 24rpx;
}

.card-top,
.card-bottom,
.card-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

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

.repair-status-tag {
  padding: 8rpx 18rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  font-weight: 600;
  line-height: 1.2;
}

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

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

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

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

.tag-success {
  color: #15803d;
  background: #dcfce7;
}

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

.repair-date {
  font-size: 26rpx;
  color: #9ca3af;
}

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

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

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

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

.add-btn,
.go-top-btn {
  position: fixed;
  right: 32rpx;
  width: 92rpx;
  height: 92rpx;
  border-radius: 46rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 14rpx 30rpx rgba(24, 63, 108, 0.24);
}

.add-btn {
  right: 28rpx;
  bottom: calc(56rpx + env(safe-area-inset-bottom));
  background: #1f4b79;
}

.go-top-btn {
  bottom: calc(172rpx + env(safe-area-inset-bottom));
  background: rgba(31, 75, 121, 0.84);
}

.add-icon {
  color: #ffffff;
  font-size: 64rpx;
  line-height: 1;
  margin-top: -4rpx;
}
</style>