<template>
  <a-modal
    v-model:visible="visible"
    :title="orderData ? '编辑采购订单' : '新建采购订单'"
    :width="800"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      :label-col-style="{ fontWeight: 'bold' }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="订单编号"
            field="orderNo"
            :required="true"
          >
            <a-input
              v-model="formData.orderNo"
              placeholder="请输入订单编号"
              :disabled="!!orderData"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="采购类型"
            field="purchaseType"
            :required="true"
          >
            <a-select
              v-model="formData.purchaseType"
              placeholder="请选择采购类型"
              allow-clear
            >
              <a-option value="equipment">设备采购</a-option>
              <a-option value="material">材料采购</a-option>
              <a-option value="service">服务采购</a-option>
              <a-option value="office">办公用品</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="供应商"
            field="supplierName"
            :required="true"
          >
            <a-input
              v-model="formData.supplierName"
              placeholder="请输入供应商名称"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="紧急程度"
            field="urgency"
            :required="true"
          >
            <a-select
              v-model="formData.urgency"
              placeholder="请选择紧急程度"
              allow-clear
            >
              <a-option value="high">紧急</a-option>
              <a-option value="medium">一般</a-option>
              <a-option value="low">普通</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="申请人"
            field="applicant"
            :required="true"
          >
            <a-input
              v-model="formData.applicant"
              placeholder="请输入申请人"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="申请日期"
            field="applyDate"
            :required="true"
          >
            <a-date-picker
              v-model="formData.applyDate"
              style="width: 100%"
              placeholder="请选择申请日期"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        label="采购明细"
        field="items"
        :required="true"
      >
        <div class="items-section">
          <div class="items-header">
            <span>采购项目</span>
            <a-button type="primary" size="small" @click="addItem">
              <template #icon>
                <GiSvgIcon name="plus" />
              </template>
              添加项目
            </a-button>
          </div>

          <div class="items-list">
            <div
              v-for="(item, index) in formData.items"
              :key="index"
              class="item-row"
            >
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-input
                    v-model="item.name"
                    placeholder="项目名称"
                    allow-clear
                  />
                </a-col>
                <a-col :span="4">
                  <a-input-number
                    v-model="item.quantity"
                    placeholder="数量"
                    :min="1"
                    :precision="0"
                    style="width: 100%"
                  />
                </a-col>
                <a-col :span="4">
                  <a-input
                    v-model="item.unit"
                    placeholder="单位"
                    allow-clear
                  />
                </a-col>
                <a-col :span="4">
                  <a-input-number
                    v-model="item.unitPrice"
                    placeholder="单价"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </a-col>
                <a-col :span="4">
                  <a-input
                    :value="(item.quantity * item.unitPrice).toFixed(2)"
                    disabled
                    placeholder="小计"
                  />
                </a-col>
                <a-col :span="2">
                  <a-button
                    type="text"
                    size="small"
                    danger
                    @click="removeItem(index)"
                  >
                    <template #icon>
                      <GiSvgIcon name="delete" />
                    </template>
                  </a-button>
                </a-col>
              </a-row>
            </div>
          </div>
        </div>
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="预计交货日期"
            field="expectedDeliveryDate"
          >
            <a-date-picker
              v-model="formData.expectedDeliveryDate"
              style="width: 100%"
              placeholder="请选择预计交货日期"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="订单总金额"
            field="totalAmount"
          >
            <a-input
              :value="`¥${totalAmount.toFixed(2)}`"
              disabled
              placeholder="订单总金额"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        label="采购说明"
        field="description"
      >
        <a-textarea
          v-model="formData.description"
          placeholder="请输入采购说明"
          :max-length="1000"
          show-word-limit
          :rows="4"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'

interface Props {
  visible: boolean
  orderData?: any | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  orderData: null,
})

const emit = defineEmits<Emits>()

// Form ref
const formRef = ref<FormInstance>()
const loading = ref(false)

// Form data
const formData = reactive({
  orderNo: '',
  purchaseType: '',
  supplierName: '',
  urgency: '',
  applicant: '',
  applyDate: '',
  expectedDeliveryDate: '',
  description: '',
  items: [
    {
      name: '',
      quantity: 1,
      unit: '个',
      unitPrice: 0,
    },
  ],
})

// Form rules
const rules = {
  orderNo: [
    { required: true, message: '请输入订单编号' },
  ],
  purchaseType: [
    { required: true, message: '请选择采购类型' },
  ],
  supplierName: [
    { required: true, message: '请输入供应商名称' },
  ],
  urgency: [
    { required: true, message: '请选择紧急程度' },
  ],
  applicant: [
    { required: true, message: '请输入申请人' },
  ],
  applyDate: [
    { required: true, message: '请选择申请日期' },
  ],
}

// Computed total amount
const totalAmount = computed(() => {
  return formData.items.reduce((total, item) => {
    return total + (item.quantity * item.unitPrice)
  }, 0)
})

// Watch visible prop
const visible = ref(props.visible)
watch(() => props.visible, (newVal) => {
  visible.value = newVal
  if (newVal && props.orderData) {
    initFormData()
  }
})

watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// Initialize form data
const initFormData = () => {
  if (props.orderData) {
    Object.assign(formData, {
      orderNo: props.orderData.orderNo || '',
      purchaseType: props.orderData.purchaseType || '',
      supplierName: props.orderData.supplierName || '',
      urgency: props.orderData.urgency || '',
      applicant: props.orderData.applicant || '',
      applyDate: props.orderData.applyDate || '',
      expectedDeliveryDate: props.orderData.expectedDeliveryDate || '',
      description: props.orderData.description || '',
      items: props.orderData.items || [
        {
          name: '',
          quantity: 1,
          unit: '个',
          unitPrice: 0,
        },
      ],
    })
  }
}

// Add item
const addItem = () => {
  formData.items.push({
    name: '',
    quantity: 1,
    unit: '个',
    unitPrice: 0,
  })
}

// Remove item
const removeItem = (index: number) => {
  if (formData.items.length > 1) {
    formData.items.splice(index, 1)
  }
}

// Handle OK
const handleOk = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) {
      loading.value = true
      // 这里调用保存API
      await new Promise((resolve) => setTimeout(resolve, 1000))
      Message.success(props.orderData ? '更新成功' : '创建成功')
      emit('success')
      handleCancel()
    }
  } catch (error) {
    console.error('保存失败:', error)
    Message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// Handle Cancel
const handleCancel = () => {
  visible.value = false
  resetForm()
}

// Reset form
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    orderNo: '',
    purchaseType: '',
    supplierName: '',
    urgency: '',
    applicant: '',
    applyDate: '',
    expectedDeliveryDate: '',
    description: '',
    items: [
      {
        name: '',
        quantity: 1,
        unit: '个',
        unitPrice: 0,
      },
    ],
  })
}
</script>

<style scoped>
.items-section {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 16px;

  .items-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    font-weight: 500;
  }

  .items-list {
    .item-row {
      margin-bottom: 12px;
      padding: 12px;
      background: #fafafa;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

:deep(.arco-form-item-label) {
  font-weight: 500;
}
</style>
