<template>
  <view class="yd-page-container">
    <!-- 顶部导航栏 -->
    <wd-navbar
      title="采摘记录详情"
      left-arrow placeholder safe-area-inset-top fixed
      @click-left="handleBack"
    />

    <!-- 详情内容 -->
    <view v-if="formData">
      <!-- 基本信息 -->
      <wd-cell-group title="基本信息" border>
        <wd-cell title="采摘编号" :value="formData.pickCode" />
        <wd-cell title="状态">
          <view
            class="rounded-8rpx px-16rpx py-4rpx text-24rpx"
            :class="getStatusClass(formData.status)"
          >
            {{ getStatusText(formData.status) }}
          </view>
        </wd-cell>
        <wd-cell title="关联产品" :value="formData.productName || '-'" />
        <wd-cell title="采摘人员" :value="formData.userName || '-'" />
        <wd-cell title="田间编号" :value="formData.fieldCode || '-'" />
        <wd-cell title="采摘时间" :value="formatDate(formData.pickTime)" />
        <wd-cell title="创建时间" :value="formatDate(formData.createTime)" />
      </wd-cell-group>

      <!-- 采摘信息 -->
      <wd-cell-group title="采摘信息" border>
        <wd-cell title="框编号" :value="formData.basketCode || '-'" />
        <wd-cell title="每筐重量" :value="formData.basketWeight ? `${formData.basketWeight} kg` : '-'" />
        <wd-cell title="车牌号" :value="formData.licensePlate || '-'" />
      </wd-cell-group>

      <!-- 装车信息 (status >= 3) -->
      <wd-cell-group v-if="(formData.status ?? 0) >= 3" title="装车信息" border>
        <wd-cell title="装车人员" :value="formData.loaderName || '-'" />
        <wd-cell title="装车时间" :value="formatDate(formData.loadTime)" />
      </wd-cell-group>

      <!-- 卸车入库信息 (status === 4) -->
      <wd-cell-group v-if="formData.status === 4" title="卸车入库信息" border>
        <wd-cell title="卸车人员" :value="formData.unloaderName || '-'" />
        <wd-cell title="卸车时间" :value="formatDate(formData.unloadTime)" />
        <wd-cell title="入库仓库" :value="formData.warehouseName || '-'" />
        <wd-cell title="卸车批次号" :value="formData.unloadBatch || '-'" />
      </wd-cell-group>

      <!-- 备注 -->
      <wd-cell-group v-if="formData.remark" title="备注" border>
        <wd-cell :value="formData.remark" />
      </wd-cell-group>
    </view>

    <!-- 底部操作按钮 -->
    <view class="yd-detail-footer">
      <view class="yd-detail-footer-actions">
        <wd-button
          v-if="hasAccessByCodes(['erp:pick-broccoli:update']) && (formData?.status ?? 0) < 3"
          class="flex-1" type="primary" @click="handleEdit"
        >
          编辑
        </wd-button>
        <wd-button
          v-if="hasAccessByCodes(['erp:pick-broccoli:update']) && formData?.status === 1"
          class="flex-1" type="success" @click="handleStatusUpdate(2, '装框')"
        >
          装框
        </wd-button>
        <wd-button
          v-if="hasAccessByCodes(['erp:pick-broccoli:update']) && formData?.status === 2"
          class="flex-1" type="warning" @click="handleLoadTruck"
        >
          装车
        </wd-button>
        <wd-button
          v-if="hasAccessByCodes(['erp:pick-broccoli:delete']) && (formData?.status ?? 0) < 3"
          class="flex-1" type="error" :loading="deleting" @click="handleDelete"
        >
          删除
        </wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import type { PickBroccoli } from '@/api/erp/pick-broccoli'
import { onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { deletePickBroccoli, getPickBroccoli, loadTruck, updatePickBroccoliStatus } from '@/api/erp/pick-broccoli'
import { useAccess } from '@/hooks/useAccess'
import { navigateBackPlus } from '@/utils'

const props = defineProps<{
  id?: number | any
}>()

definePage({
  style: {
    navigationBarTitleText: '',
    navigationStyle: 'custom',
  },
})

const { hasAccessByCodes } = useAccess()
const toast = useToast()
const formData = ref<PickBroccoli>()
const deleting = ref(false)

/** 格式化日期 */
function formatDate(date?: string) {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

/** 获取状态文本 */
function getStatusText(status?: number) {
  switch (status) {
    case 1: return '已采摘'
    case 2: return '已装框'
    case 3: return '已装车'
    case 4: return '已卸车入库'
    default: return '未知'
  }
}

/** 获取状态样式 */
function getStatusClass(status?: number) {
  switch (status) {
    case 1: return 'bg-[#e6f7ff] text-[#1890ff]'
    case 2: return 'bg-[#fff7e6] text-[#fa8c16]'
    case 3: return 'bg-[#f9f0ff] text-[#722ed1]'
    case 4: return 'bg-[#f6ffed] text-[#52c41a]'
    default: return 'bg-[#f5f5f5] text-[#999]'
  }
}

/** 返回上一页 */
function handleBack() {
  navigateBackPlus('/pages-erp/pick-broccoli/index')
}

/** 加载详情 */
async function getDetail() {
  if (!props.id) {
    return
  }
  try {
    toast.loading('加载中...')
    formData.value = await getPickBroccoli(props.id)
  } finally {
    toast.close()
  }
}

/** 编辑 */
function handleEdit() {
  uni.navigateTo({
    url: `/pages-erp/pick-broccoli/form/index?id=${props.id}`,
  })
}

/** 状态更新（装框） */
function handleStatusUpdate(status: number, text: string) {
  uni.showModal({
    title: '提示',
    content: `确认将该记录状态更新为"${text}完成"吗？`,
    success: async (res) => {
      if (!res.confirm) return
      try {
        await updatePickBroccoliStatus(props.id, status)
        toast.success(`${text}操作成功`)
        getDetail()
      } catch {
        // error handled by http
      }
    },
  })
}

/** 装车操作 */
function handleLoadTruck() {
  uni.showModal({
    title: '装车',
    content: '请输入车牌号',
    editable: true,
    placeholderText: '车牌号',
    success: async (res) => {
      if (!res.confirm || !res.content) return
      try {
        await loadTruck(props.id, res.content, 0, '')
        toast.success('装车操作成功')
        getDetail()
      } catch {
        // error handled by http
      }
    },
  })
}

/** 删除 */
function handleDelete() {
  if (!props.id) {
    return
  }
  uni.showModal({
    title: '提示',
    content: '确定要删除该采摘记录吗？',
    success: async (res) => {
      if (!res.confirm) {
        return
      }
      deleting.value = true
      try {
        await deletePickBroccoli(props.id)
        toast.success('删除成功')
        setTimeout(() => {
          handleBack()
        }, 500)
      } finally {
        deleting.value = false
      }
    },
  })
}

/** 初始化 */
onMounted(() => {
  getDetail()
})
</script>

<style lang="scss" scoped>
</style>
