<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="请购类型">
          <template #value>
            <view
              class="rounded-8rpx px-12rpx py-2rpx text-22rpx"
              :class="getTypeClass(detail.type)"
            >
              {{ getTypeLabel(detail.type) }}
            </view>
          </template>
        </wd-cell>
        <wd-cell title="状态">
          <template #value>
            <view
              class="rounded-8rpx px-12rpx py-2rpx text-22rpx"
              :class="getStatusClass(detail.status)"
            >
              {{ getStatusLabel(detail.status) }}
            </view>
          </template>
        </wd-cell>
        <wd-cell title="优先级">
          <template #value>
            <view
              class="rounded-8rpx px-12rpx py-2rpx text-22rpx"
              :class="getPriorityClass(detail.priority)"
            >
              {{ getPriorityLabel(detail.priority) }}
            </view>
          </template>
        </wd-cell>
        <wd-cell title="紧急程度">
          <template #value>
            <view
              class="rounded-8rpx px-12rpx py-2rpx text-22rpx"
              :class="getEmergencyClass(detail.emergencyDegree)"
            >
              {{ getEmergencyLabel(detail.emergencyDegree) }}
            </view>
          </template>
        </wd-cell>
        <wd-cell title="请购人" :value="detail.requesterNickname || '-'" />
        <wd-cell title="请购部门" :value="detail.requesterDeptName || '-'" />
        <wd-cell title="请购时间" :value="formatDate(detail.requestTime)" />
        <wd-cell title="期望到货" :value="formatDate(detail.expectedTime)" />
        <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.totalProductPrice)" />
        <wd-cell title="合计税额" :value="formatPrice(detail.totalTaxPrice)" />
        <wd-cell title="合计金额（含税）" :value="formatPrice(detail.totalPrice)" />
        <wd-cell title="附加费" :value="formatPrice(detail.additionalFee)" />
      </wd-cell-group>

      <!-- 审核信息 -->
      <wd-cell-group v-if="detail.status !== 1" title="审核信息" border>
        <wd-cell title="审核人" :value="detail.approverName || '-'" />
        <wd-cell title="审核时间" :value="formatDateTime(detail.approveTime)" />
        <wd-cell title="审核意见" :value="detail.approveRemark || '-'" />
      </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.productSpec || '-' }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">单位</text>
              <text class="text-[#666]">{{ item.productUnitName || '-' }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">需求数量</text>
              <text class="text-[#333] font-semibold">{{ formatCount(item.count) }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">参考单价</text>
              <text class="text-[#666]">{{ formatPrice(item.productPrice) }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">产品金额</text>
              <text class="text-[#666]">{{ formatPrice(item.totalProductPrice) }}</text>
            </view>
            <view v-if="item.taxPercent" class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">税率</text>
              <text class="text-[#666]">{{ item.taxPercent }}%</text>
            </view>
            <view v-if="item.taxPrice" class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">税额</text>
              <text class="text-[#666]">{{ formatPrice(item.taxPrice) }}</text>
            </view>
            <view class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">含税金额</text>
              <text class="text-[#1890ff] font-semibold">{{ formatPrice(item.totalPrice) }}</text>
            </view>
            <view v-if="item.supplierName" class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">建议供应商</text>
              <text class="text-[#666]">{{ item.supplierName }}</text>
            </view>
            <view v-if="item.purpose" class="mb-8rpx flex items-center justify-between text-26rpx">
              <text class="text-[#999]">用途</text>
              <text class="text-[#666]">{{ item.purpose }}</text>
            </view>
          </view>
        </view>
      </wd-cell-group>
    </view>

    <!-- 底部操作按钮 -->
    <view class="yd-detail-footer">
      <wd-button
        v-if="hasAccessByCodes(['erp:purchase-requisition:update']) && detail.status === 1"
        type="primary"
        @click="handleEdit"
      >
        编辑
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:purchase-requisition:update-status']) && detail.status === 1"
        type="success"
        @click="handleApprove"
      >
        审核
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:purchase-requisition:approve']) && detail.status === 1"
        type="warning"
        @click="handleReject"
      >
        驳回
      </wd-button>
      <wd-button
        v-if="hasAccessByCodes(['erp:purchase-requisition:delete']) && detail.status === 1"
        type="error"
        @click="handleDelete"
      >
        删除
      </wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import type { PurchaseRequisition } from '@/api/erp/purchase-requisition'
import { onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import {
  deletePurchaseRequisition,
  EMERGENCY_OPTIONS,
  getPurchaseRequisition,
  PRIORITY_OPTIONS,
  REQUISITION_TYPE_OPTIONS,
  STATUS_OPTIONS,
  updatePurchaseRequisitionStatus,
} from '@/api/erp/purchase-requisition'
import { useAccess } from '@/hooks/useAccess'
import { formatDate as formatDateValue } from '@/utils/date'
import { navigateBackPlus } from '@/utils'

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

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

const { hasAccessByCodes } = useAccess()
const toast = useToast()
const detail = ref<PurchaseRequisition>({})

/** 获取类型标签 */
function getTypeLabel(type?: number) {
  return REQUISITION_TYPE_OPTIONS.find(o => o.value === type)?.label || '-'
}

/** 获取类型样式 */
function getTypeClass(type?: number) {
  const map: Record<number, string> = {
    1: 'bg-[#e6f7ff] text-[#1890ff]',
    2: 'bg-[#fff7e6] text-[#fa8c16]',
    3: 'bg-[#f9f0ff] text-[#722ed1]',
  }
  return map[type || 1] || 'bg-[#f5f5f5] text-[#666]'
}

/** 获取状态标签 */
function getStatusLabel(status?: number) {
  return STATUS_OPTIONS.find(o => o.value === status)?.label || '-'
}

/** 获取状态样式 */
function getStatusClass(status?: number) {
  const map: Record<number, string> = {
    1: 'bg-[#fff7e6] text-[#fa8c16]',
    2: 'bg-[#f6ffed] text-[#52c41a]',
    3: 'bg-[#fff1f0] text-[#f5222d]',
    4: 'bg-[#f5f5f5] text-[#999]',
    5: 'bg-[#e6f7ff] text-[#1890ff]',
  }
  return map[status || 1] || 'bg-[#f5f5f5] text-[#666]'
}

/** 获取优先级标签 */
function getPriorityLabel(priority?: number) {
  return PRIORITY_OPTIONS.find(o => o.value === priority)?.label || '-'
}

/** 获取优先级样式 */
function getPriorityClass(priority?: number) {
  const map: Record<number, string> = {
    1: 'bg-[#f5f5f5] text-[#999]',
    2: 'bg-[#e6f7ff] text-[#1890ff]',
    3: 'bg-[#fff7e6] text-[#fa8c16]',
    4: 'bg-[#fff1f0] text-[#f5222d]',
  }
  return map[priority || 1] || 'bg-[#f5f5f5] text-[#666]'
}

/** 获取紧急程度标签 */
function getEmergencyLabel(emergency?: number) {
  return EMERGENCY_OPTIONS.find(o => o.value === emergency)?.label || '-'
}

/** 获取紧急程度样式 */
function getEmergencyClass(emergency?: number) {
  const map: Record<number, string> = {
    1: 'bg-[#f5f5f5] text-[#999]',
    2: 'bg-[#e6f7ff] text-[#1890ff]',
    3: 'bg-[#fff7e6] text-[#fa8c16]',
    4: 'bg-[#fff1f0] text-[#f5222d]',
  }
  return map[emergency || 1] || 'bg-[#f5f5f5] text-[#666]'
}

/** 格式化数量 */
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 | number | Date) {
  return formatDateValue(dateStr) || '-'
}

/** 格式化日期时间 */
function formatDateTime(dateStr?: string | number | Date) {
  return formatDateValue(dateStr, 'YYYY-MM-DD HH:mm') || '-'
}

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

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

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

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

/** 驳回 */
function handleReject() {
  uni.showModal({
    title: '提示',
    content: '确定要驳回该请购单吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await updatePurchaseRequisitionStatus(props.id, 3)
        toast.success('驳回成功')
        getDetail()
      } catch {
        // error handled by http
      }
    },
  })
}

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

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

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