<script setup lang="ts">
import { Field as VanField, Icon as VanIcon } from 'vant'
import { computed, ref, watch } from 'vue'

interface ChargeItem {
  id: number
  workOrderCode?: string
  workOrderId?: string
  type: string
  item: string
  model?: string
  unitPrice: number
  quantity: number
  total: string
}

const props = defineProps<{
  item: ChargeItem
  index: number
  isWorkOrder?: boolean
  workOrderData?: any
  isUpdatePrice?: boolean
}>()

const emit = defineEmits<{
  (e: 'remove', id: number): void
  (e: 'update', item: ChargeItem): void
}>()

// 本地状态，用于双向绑定
const localUnitPrice = ref(props.item.unitPrice.toString())
const localQuantity = ref(props.item.quantity.toString())
const item = computed(() => props.item)

// 监听 props 变化，同步本地状态
watch(() => props.item.unitPrice, (newVal) => {
  localUnitPrice.value = newVal.toString()
})

watch(() => props.item.quantity, (newVal) => {
  localQuantity.value = newVal.toString()
})

// 计算小计
const total = computed(() => {
  const price = Number.parseFloat(localUnitPrice.value) || 0
  const qty = Number.parseInt(localQuantity.value) || 0
  return (price * qty).toFixed(2)
})

// 处理单价变化 - 限制9位整数2位小数
function handleUnitPriceChange(value: string) {
  // 移除非数字和小数点的字符
  let cleaned = value.replace(/[^\d.]/g, '')

  // 限制小数点后最多2位
  const parts = cleaned.split('.')
  if (parts.length > 2) {
    cleaned = `${parts[0]}.${parts.slice(1).join('')}`
  }
  if (parts[1] && parts[1].length > 2) {
    cleaned = `${parts[0]}.${parts[1].slice(0, 2)}`
  }

  // 限制整数部分最多9位
  if (parts[0] && parts[0].length > 9) {
    cleaned = parts[0].slice(0, 9) + (parts[1] ? `.${parts[1]}` : '')
  }

  // 更新值
  localUnitPrice.value = cleaned
  updateItem()
}

// 处理数量变化 - 限制5位整数
function handleQuantityChange(value: string) {
  // 只允许数字，限制最多5位
  let cleaned = value.replace(/\D/g, '')
  if (cleaned.length > 5) {
    cleaned = cleaned.slice(0, 5)
  }

  // 更新值
  localQuantity.value = cleaned
  updateItem()
}

// 更新费用项
function updateItem() {
  const price = Number.parseFloat(localUnitPrice.value) || 0
  const qty = Number.parseInt(localQuantity.value) || 0

  // 只有当价格和数量都大于0时才更新
  if (price > 0 && qty > 0) {
    const updatedItem: ChargeItem = {
      ...props.item,
      unitPrice: price,
      quantity: qty,
      total: total.value,
    }
    emit('update', updatedItem)
  }
  else if (localUnitPrice.value === '' || localQuantity.value === '') {
    // 如果输入为空，不更新，保持原值

  }
}
</script>

<template>
  <div class="other-charge-item">
    <div class="other-charge-item__header">
      <h5 class="other-charge-item__title">
        费用项 #{{ index + 1 }}
      </h5>
      <VanIcon
        name="cross"
        class="other-charge-item__delete"
        @click="$emit('remove', item.id)"
      />
    </div>

    <div class="other-charge-item__info">
      <div v-if="isWorkOrder" class="other-charge-item__field">
        <p class="other-charge-item__label">
          所属工单
        </p>
        <p class="other-charge-item__value">
          {{ item.workOrderCode }}
        </p>
      </div>
      <div class="other-charge-item__field">
        <p class="other-charge-item__label">
          小计
        </p>
        <p class="other-charge-item__value--info">
          ￥{{ total }}
        </p>
      </div>
      <div class="other-charge-item__field">
        <p class="other-charge-item__label">
          收费类型
        </p>
        <p class="other-charge-item__value">
          {{ item.type }}
        </p>
      </div>
      <div class="other-charge-item__field">
        <p class="other-charge-item__label">
          具体项目
        </p>
        <p class="other-charge-item__value">
          {{ item.item }}
        </p>
      </div>
    </div>

    <div class="other-charge-item__details">
      <div class="other-charge-item__field">
        <p class="other-charge-item__label">
          单价
        </p>
        <VanField
          :model-value="localUnitPrice"
          type="number"
          :disabled="!isUpdatePrice"
          placeholder="限制9位整数2位小数"
          @update:model-value="handleUnitPriceChange"
        >
          <template #prefix>
            <span class="other-charge-item__prefix">¥</span>
          </template>
        </VanField>
      </div>
      <div class="other-charge-item__field">
        <p class="other-charge-item__label">
          数量
        </p>
        <VanField
          :model-value="localQuantity"
          type="number"
          placeholder="限制5位整数"
          @update:model-value="handleQuantityChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.other-charge-item {
  background-color: #f9fafb;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  margin-bottom: 12px;

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    gap: 8px;
  }

  &__title {
    font-size: 12px;
    font-weight: 500;
    color: #374151;
    margin: 0;
    flex-shrink: 0;
  }
  &__value--info {
    font-size: 14px;
    font-weight: 500;
    color: #2563eb;
  }
  &__delete {
    color: #ef4444;
    font-size: 16px;
    flex-shrink: 0;
    cursor: pointer;

    &:active {
      color: #b91c1c;
    }
  }

  :deep(.van-field) {
    background-color: #ffffff;
    border-radius: 4px;
    padding: 8px 12px;
  }

  :deep(.van-field__control) {
    background-color: #ffffff;
    color: #1f2937;
    font-size: 14px;
  }

  :deep(.van-field__label) {
    display: none;
  }

  &__info {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 8px;
  }

  &__details {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
  }

  &__label {
    font-size: 12px;
    color: #6b7280;
    margin: 0 0 4px 0;
  }

  &__value {
    font-size: 14px;
    font-weight: 500;
    color: #1f2937;
    margin: 0;
  }

  &__prefix {
    color: #6b7280;
    font-size: 14px;
    margin-right: 4px;
  }
}
</style>
