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

    <!-- 详情内容 -->
    <view class="pb-180rpx">
      <!-- 基本信息 -->
      <wd-cell-group title="基本信息" border>
        <wd-cell title="报损单号" :value="detail.no || '-'" />
        <wd-cell title="报损时间" :value="formatDate(detail.lossTime)" />
        <wd-cell title="报损原因" :value="detail.reason || '-'" />
        <wd-cell title="审核状态">
          <template #value>
            <view
              class="rounded-8rpx px-16rpx py-4rpx text-24rpx"
              :class="detail.status === 20 ? 'bg-[#f6ffed] text-[#52c41a]' : 'bg-[#fff7e6] text-[#fa8c16]'"
            >
              {{ detail.status === 20 ? '已审核' : '未审核' }}
            </view>
          </template>
        </wd-cell>
        <wd-cell title="备注" :value="detail.remark || '-'" />
      </wd-cell-group>

      <!-- 金额信息 -->
      <wd-cell-group title="金额信息" border>
        <wd-cell title="合计数量" :value="formatCount(detail.totalCount)" />
        <wd-cell title="合计金额" :value="formatPrice(detail.totalPrice)" />
      </wd-cell-group>

      <!-- 报损产品清单 -->
      <wd-cell-group title="报损产品清单" border>
        <view v-if="!detail.items || detail.items.length === 0" class="py-40rpx text-center text-[#999]">
          暂无产品数据
        </view>
        <view v-else>
          <view
            v-for="(item, index) in detail.items"
            :key="index"
            class="mx-24rpx mb-20rpx rounded-12rpx bg-[#f9f9f9] p-24rpx"
          >
            <view class="mb-12rpx text-28rpx text-[#333] font-semibold">
              {{ item.productName || '-' }}
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">仓库</text>
              <text class="text-[#666]">{{ item.warehouseName || '-' }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">数量</text>
              <text class="text-[#f5222d] font-semibold">-{{ formatCount(item.count) }}</text>
            </view>
            <view class="flex items-center justify-between text-26rpx">
              <text class="text-[#999]">金额</text>
              <text class="text-[#f5222d] font-semibold">{{ formatPrice(item.totalPrice) }}</text>
            </view>
          </view>
        </view>
      </wd-cell-group>
    </view>

    <!-- 底部操作按钮 -->
    <view class="yd-detail-footer">
      <wd-button
        v-if="hasAccessByCodes(['erp:stock-loss:update']) && detail.status === 10"
        type="primary"
        @click="handleEdit"
      >
        编辑
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:stock-loss:update-status']) && detail.status === 10"
        type="success"
        @click="handleApprove"
      >
        审批
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:stock-loss:update-status']) && detail.status === 20"
        type="warning"
        @click="handleReverseApprove"
      >
        反审批
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:stock-loss:delete']) && detail.status === 10"
        type="error"
        @click="handleDelete"
      >
        删除
      </wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import type { StockLoss } from '@/api/erp/stock-loss'
import { onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { deleteStockLoss, getStockLoss, updateStockLossStatus } from '@/api/erp/stock-loss'
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 detail = ref<StockLoss>({})

/** 格式化数量 */
function formatCount(count?: number) {
  if (count === undefined || count === null) return '-'
  return count.toFixed(2)
}

/** 格式化金额 */
function formatPrice(price?: number) {
  if (price === undefined || price === null) return '-'
  return `¥${price.toFixed(2)}`
}

/** 格式化日期 */
function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return dateStr.substring(0, 10)
}

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

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

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

/** 审批 */
function handleApprove() {
  uni.showModal({
    title: '提示',
    content: '确定要审批该报损单吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await updateStockLossStatus(props.id, 20)
        toast.success('审批成功')
        getDetail()
      } catch {
        // error handled by http
      }
    },
  })
}

/** 反审批 */
function handleReverseApprove() {
  uni.showModal({
    title: '提示',
    content: '确定要反审批该报损单吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await updateStockLossStatus(props.id, 10)
        toast.success('反审批成功')
        getDetail()
      } catch {
        // error handled by http
      }
    },
  })
}

/** 删除 */
function handleDelete() {
  uni.showModal({
    title: '提示',
    content: '确定要删除该报损单吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await deleteStockLoss([props.id])
        toast.success('删除成功')
        setTimeout(() => {
          handleBack()
        }, 500)
      } catch {
        // error handled by http
      }
    },
  })
}

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

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