<script setup lang="ts">
import {
  Button as VanButton,
  Field as VanField,
  Icon as VanIcon,
  Picker as VanPicker,
  Popup as VanPopup,
  Stepper as VanStepper,
} from 'vant'
import { computed, reactive, ref, watch } from 'vue'

// 型号接口
interface ModelItem {
  name: string
  price?: number
}

// 物品接口
interface ItemType {
  name: string
  children?: ModelItem[]
}

// 分类接口
interface CategoryItem {
  name: string
  children: ItemType[]
}

// 配置接口
interface ChargeTypeConfig {
  value: CategoryItem[]
}

interface FormData {
  workOrderCode?: string
  workOrderId?: string
  type: string
  item: string
  model: string // 新增型号字段
  unitPrice: string
  quantity: number
}

const props = defineProps<{
  isWorkOrder?: boolean
  workOrderData?: any
  show: boolean
  chargeTypes: ChargeTypeConfig
}>()

const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'add', item: {
    workOrderCode?: string
    workOrderId?: string
    id: number
    type: string
    item: string
    model: string // 新增型号字段
    unitPrice: number
    quantity: number
    total: string
  }): void
}>()

const showModal = computed({
  get: () => props.show,
  set: value => emit('update:show', value),
})

// 工单选项
const workOrderOptions = computed(() => {
  return props.workOrderData || []
})

const formData = reactive<FormData>({
  workOrderCode: workOrderOptions.value.length === 1 ? workOrderOptions.value[0].text : '',
  workOrderId: workOrderOptions.value.length === 1 ? workOrderOptions.value[0].value : '',
  type: '',
  item: '',
  model: '', // 新增型号字段
  unitPrice: '',
  quantity: 1,
})

const showWorkOrderSelector = ref(false)
const showTypeSelector = ref(false)
const showItemSelector = ref(false)
const showModelSelector = ref(false) // 新增型号选择器状态
const workOrderError = ref(false)
const typeError = ref(false)
const itemError = ref(false)
const priceError = ref(false)
const isWorkOrder = computed(() => props.isWorkOrder)

// 分类选项
const typeOptions = computed(() => {
  return props.chargeTypes.value.map(category => ({ text: category.name, value: category.name }))
})

// 物品选项
const itemOptions = computed(() => {
  if (!formData.type)
    return []

  const category = props.chargeTypes.value.find(c => c.name === formData.type)
  if (!category)
    return []

  return category.children.map(item => ({ text: item.name, value: item.name }))
})

// 型号选项
const modelOptions = computed(() => {
  if (!formData.type || !formData.item)
    return []

  const category = props.chargeTypes.value.find(c => c.name === formData.type)
  if (!category)
    return []

  const item = category.children.find(i => i.name === formData.item)
  if (!item || !item.children)
    return []

  return item.children.map(model => ({ text: model.name, value: model.name }))
})

// 是否有型号选项
const hasModelOptions = computed(() => {
  if (!formData.type || !formData.item)
    return false

  const category = props.chargeTypes.value.find(c => c.name === formData.type)
  if (!category)
    return false
  console.log('category', category)
  const item = category.children.find(i => i.name === formData.item)
  console.log('item', item)
  return !!(item && item.children && item.children.length > 0)
})

// 选择处理函数
function onWorkOrderSelected({ selectedValues, selectedOptions }) {
  formData.workOrderId = selectedValues[0]
  formData.workOrderCode = selectedOptions[0].text
  showWorkOrderSelector.value = false
  workOrderError.value = false
}
function onTypeSelected({ selectedValues }) {
  console.log('onTypeSelected', selectedValues)
  formData.type = selectedValues[0]
  formData.item = ''
  formData.model = '' // 重置型号
  formData.unitPrice = '' // 重置单价
  showTypeSelector.value = false
  typeError.value = false
}

function onItemSelected({ selectedValues }) {
  formData.item = selectedValues[0]
  formData.model = '' // 重置型号
  formData.unitPrice = '' // 重置单价
  showItemSelector.value = false
  itemError.value = false
}

// 型号选择处理函数
function onModelSelected({ selectedValues }) {
  formData.model = selectedValues[0]

  // 设置对应型号的单价
  if (formData.type && formData.item && formData.model) {
    const category = props.chargeTypes.value.find(c => c.name === formData.type)
    if (category) {
      const item = category.children.find(i => i.name === formData.item)
      if (item && item.children) {
        const model = item.children.find(m => m.name === formData.model)
        if (model && model.price !== undefined) {
          formData.unitPrice = model.price.toString()
        }
      }
    }
  }

  showModelSelector.value = false
}

function handleSubmit() {
  // 验证表单
  let isValid = true
  // 验证工单
  if (isWorkOrder.value && !formData.workOrderId) {
    workOrderError.value = true
    isValid = false
  }

  if (!formData.type) {
    typeError.value = true
    isValid = false
  }

  if (!formData.item) {
    itemError.value = true
    isValid = false
  }

  if (!formData.unitPrice || Number.parseFloat(formData.unitPrice) <= 0) {
    priceError.value = true
    isValid = false
  }

  if (!isValid)
    return

  const unitPrice = Number.parseFloat(formData.unitPrice)
  const quantity = formData.quantity
  const total = (unitPrice * quantity).toFixed(2)

  // 提交新费用项
  emit('add', {
    id: Date.now(),
    workOrderId: formData.workOrderId || '',
    workOrderCode: formData.workOrderCode || '',
    type: formData.type,
    item: formData.item,
    model: formData.model, // 添加型号
    unitPrice,
    quantity,
    total,
  })

  // 重置表单
  resetForm()

  // 关闭弹窗
  closeModal()
}

function resetForm() {
  if (isWorkOrder.value && workOrderOptions.value.length === 1) {
    formData.workOrderId = workOrderOptions.value[0].value || ''
    formData.workOrderCode = workOrderOptions.value[0].text || ''
  }
  else {
    formData.workOrderId = ''
    formData.workOrderCode = ''
  }
  formData.type = ''
  formData.item = ''
  formData.model = '' // 重置型号
  formData.unitPrice = ''
  formData.quantity = 1
  workOrderError.value = false
  typeError.value = false
  itemError.value = false
  priceError.value = false
}

function closeModal() {
  showModal.value = false
  resetForm()
}

// 监听输入，清除错误状态
// eslint-disable-next-line style/max-statements-per-line
watch(() => formData.workOrderId, () => { workOrderError.value = false })
// eslint-disable-next-line style/max-statements-per-line
watch(() => formData.type, () => { typeError.value = false })
// eslint-disable-next-line style/max-statements-per-line
watch(() => formData.item, () => { itemError.value = false })
// eslint-disable-next-line style/max-statements-per-line
watch(() => formData.unitPrice, () => { priceError.value = false })
</script>

<template>
  <VanPopup
    v-model:show="showModal"
    round
    position="center"
    :style="{ width: '90%', maxWidth: '420px' }"
    close-icon-position="top-right"
    class="other-charge-item-modal"
  >
    <div class="other-charge-item-modal__container">
      <div class="other-charge-item-modal__header">
        <h3 class="other-charge-item-modal__title">
          添加费用项
        </h3>
        <VanIcon name="cross" @click="closeModal" />
      </div>

      <form class="other-charge-item-modal__form" @submit.prevent="handleSubmit">
        <div v-if="isWorkOrder" class="other-charge-item-modal__field">
          <label class="other-charge-item-modal__label">所属工单</label>
          <VanField
            v-model="formData.workOrderCode"
            placeholder="请选择工单"
            readonly
            right-icon="arrow-down"
            :error="workOrderError"
            @click="showWorkOrderSelector = true"
          />
        </div>

        <div class="other-charge-item-modal__field">
          <label class="other-charge-item-modal__label">收费类型</label>
          <VanField
            v-model="formData.type"
            placeholder="请选择收费类型"
            readonly
            right-icon="arrow-down"
            :error="typeError"
            @click="showTypeSelector = true"
          />
        </div>

        <div class="other-charge-item-modal__field">
          <label class="other-charge-item-modal__label">具体项目</label>
          <VanField
            v-model="formData.item"
            placeholder="请选择具体项目"
            readonly
            right-icon="arrow-down"
            :disabled="!formData.type"
            :error="itemError"
            @click="showItemSelector = true"
          />
        </div>

        <!-- 新增型号选择字段 -->
        <div v-if="hasModelOptions" class="other-charge-item-modal__field">
          <label class="other-charge-item-modal__label">型号</label>
          <VanField
            v-model="formData.model"
            placeholder="请选择型号"
            readonly
            right-icon="arrow-down"
            :disabled="!formData.item"
            @click="showModelSelector = true"
          />
        </div>

        <div class="other-charge-item-modal__price-quantity">
          <div class="other-charge-item-modal__field">
            <label class="other-charge-item-modal__label">单价 (元)</label>
            <div class="other-charge-item-modal__price-input">
              <VanField
                v-model="formData.unitPrice"
                type="digit"
                placeholder="0.00"
                :error="priceError"
              >
                <template #prefix>
                  <span class="other-charge-item-modal__prefix">¥</span>
                </template>
              </VanField>
            </div>
          </div>

          <div class="other-charge-item-modal__field">
            <label class="other-charge-item-modal__label">数量</label>
            <VanStepper
              v-model="formData.quantity"
              min="1"
              step="1"
              input-width="60px"
              button-size="28px"
              theme="round"
            />
          </div>
        </div>

        <div class="other-charge-item-modal__buttons">
          <VanButton
            plain
            type="default"
            size="normal"
            class="other-charge-item-modal__cancel-btn"
            @click="closeModal"
          >
            取消
          </VanButton>
          <VanButton
            type="primary"
            size="normal"
            native-type="submit"
            class="other-charge-item-modal__confirm-btn"
          >
            添加
          </VanButton>
        </div>
      </form>
    </div>

    <!-- 工单 -->
    <VanPopup
      v-model:show="showWorkOrderSelector"
      position="bottom"

      teleport="#other-charge-form"
      round destroy-on-close
    >
      <VanPicker
        :columns="workOrderOptions"
        show-toolbar
        title="选择工单"
        @confirm="onWorkOrderSelected"
        @cancel="showWorkOrderSelector = false"
      />
    </VanPopup>

    <!-- 收费类型选择器 -->
    <VanPopup
      v-model:show="showTypeSelector"
      position="bottom"
      destroy-on-close
      teleport="#other-charge-form"
      round
    >
      <VanPicker
        :columns="typeOptions"
        show-toolbar
        title="选择收费类型"
        @confirm="onTypeSelected"
        @cancel="showTypeSelector = false"
      />
    </VanPopup>

    <!-- 具体项目选择器 -->
    <VanPopup
      v-model:show="showItemSelector"
      destroy-on-close
      position="bottom"
      round
      teleport="#other-charge-form"
    >
      <VanPicker
        :columns="itemOptions"
        show-toolbar
        title="选择具体项目"
        @confirm="onItemSelected"
        @cancel="showItemSelector = false"
      />
    </VanPopup>

    <!-- 型号选择器 -->
    <VanPopup
      v-model:show="showModelSelector"
      destroy-on-close
      position="bottom"
      round
      teleport="#other-charge-form"
    >
      <VanPicker
        :columns="modelOptions"
        show-toolbar
        title="选择型号"
        @confirm="onModelSelected"
        @cancel="showModelSelector = false"
      />
    </VanPopup>
  </VanPopup>
</template>

<style scoped lang="less">
.other-charge-item-modal {
  &__container {
    padding: 16px;
  }

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

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

  &__form {
    .van-field {
      background-color: #f9fafb;
      border-radius: 6px;
    }
  }

  &__field {
    margin-bottom: 16px;
  }

  &__label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 4px;
  }

  &__price-quantity {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }

  &__price-input {
    position: relative;
  }

  &__prefix {
    color: #6b7280;
    font-size: 14px;
  }

  &__buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 24px;
    gap: 12px;
  }

  &__cancel-btn {
    border-color: #d1d5db;
    color: #374151;
  }

  &__confirm-btn {
    background-color: #2563eb;
  }

  :deep(.van-stepper__input) {
    background-color: #f9fafb;
  }

  :deep(.van-stepper__minus),
  :deep(.van-stepper__plus) {
    background-color: #f3f4f6;
    border: 1px solid #d1d5db;
  }
}
</style>
