<template>
  <div class="order-create">
    <a-page-header @back="$router.go(-1)" :content="$t('orderCreate.title')">
      <template #extra>
        <a-button type="primary" @click="handleSubmit" :loading="loading">
          <CheckOutlined />
          {{ $t('orderCreate.createButton') }}
        </a-button>
      </template>
    </a-page-header>

    <a-card class="form-card">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <a-form-item :label="$t('orderCreate.orderTypeLabel')" prop="orderType">
          <a-select v-model:value="form.orderType" :placeholder="$t('orderCreate.orderTypePlaceholder')">
            <a-select-option value="SERVICE">{{ $t('orderCreate.orderTypeService') }}</a-select-option>
            <a-select-option value="SUBSCRIPTION">{{ $t('orderCreate.orderTypeSubscription') }}</a-select-option>
            <a-select-option value="DIGITAL">{{ $t('orders.digitalProduct') }}</a-select-option>
            <a-select-option value="VIRTUAL">{{ $t('orderCreate.orderTypeProduct') }}</a-select-option>
          </a-select>
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.orderTypeHint') }}</span>
          </div>
        </a-form-item>

        <a-form-item :label="$t('orderCreate.currencyLabel')" prop="currency">
          <a-select v-model:value="form.currency" :placeholder="$t('orderCreate.currencyPlaceholder')">
            <a-select-option value="CNY">{{ $t('orderCreate.currencyCNY') }}</a-select-option>
            <a-select-option value="USD">{{ $t('orderCreate.currencyUSD') }}</a-select-option>
            <a-select-option value="EUR">EUR (Euro)</a-select-option>
          </a-select>
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.currencyHint') }}</span>
          </div>
        </a-form-item>

        <a-form-item :label="$t('orderCreate.descriptionLabel')" prop="description">
          <a-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            :placeholder="$t('orderCreate.descriptionPlaceholder')"
          />
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.descriptionHint') }}</span>
          </div>
        </a-form-item>

        <a-form-item :label="$t('orderCreate.contactEmailLabel')" prop="contactEmail">
          <a-input
            v-model="form.contactEmail"
            type="email"
            :placeholder="$t('orderCreate.contactEmailPlaceholder')"
          />
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.contactEmailHint') }}</span>
          </div>
        </a-form-item>

        <a-form-item :label="$t('orderCreate.contactPhoneLabel')" prop="contactPhone">
          <a-input
            v-model="form.contactPhone"
            :placeholder="$t('orderCreate.contactPhonePlaceholder')"
          />
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.contactPhoneHint') }}</span>
          </div>
        </a-form-item>

        <!-- 虚拟商品不需要收货地址 -->
        <template v-if="isPhysicalOrder">
          <a-form-item :label="$t('orderCreate.shippingAddressLabel')" prop="shippingAddress">
            <a-input
              v-model="form.shippingAddress"
              type="textarea"
              :rows="3"
              :placeholder="$t('orderCreate.shippingAddressPlaceholder')"
            />
          </a-form-item>

          <a-form-item :label="$t('orderCreate.billingAddressLabel')" prop="billingAddress">
            <a-input
              v-model="form.billingAddress"
              type="textarea"
              :rows="3"
              :placeholder="$t('orderCreate.billingAddressPlaceholder')"
            />
          </a-form-item>
        </template>

        <!-- 订单项 -->
        <a-form-item :label="$t('orderCreate.virtualProductsLabel')">
          <div class="field-description">
            <InfoFilled />
            <span>{{ $t('orderCreate.virtualProductsHint') }}</span>
          </div>
          <div class="order-items">
            <div
              v-for="(item, index) in form.orderItems"
              :key="index"
              class="order-item"
            >
              <a-row :gutter="20">
                <a-col :span="8">
                  <a-input
                    v-model="item.productName"
                    :placeholder="$t('orderCreate.productNamePlaceholder')"
                    @input="calculateSubtotal(index)"
                  />
                </a-col>
                <a-col :span="4">
                  <a-input-number
                    v-model="item.unitPrice"
                    :precision="2"
                    :min="0"
                    :placeholder="$t('orderCreate.unitPricePlaceholder')"
                    @change="calculateSubtotal(index)"
                  />
                </a-col>
                <a-col :span="4">
                  <a-input-number
                    v-model="item.quantity"
                    :min="1"
                    :placeholder="$t('orderCreate.quantityPlaceholder')"
                    @change="calculateSubtotal(index)"
                  />
                </a-col>
                <a-col :span="4">
                  <a-input
                    v-model="item.subtotal"
                    readonly
                    :placeholder="$t('orderCreate.subtotalPlaceholder')"
                  />
                </a-col>
                <a-col :span="4">
                  <a-button
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeItem(index)"
                    v-if="form.orderItems.length > 1"
                  />
                </a-col>
              </a-row>
            </div>
            
            <a-button
              type="primary"
              :icon="Plus"
              @click="addItem"
              class="add-item-btn"
            >
              添加虚拟商品
            </a-button>
          </div>
        </a-form-item>

        <a-form-item>
          <div class="total-amount">
            <span class="total-label">订单总计：</span>
            <span class="total-value">{{ form.currency }} {{ totalAmount }}</span>
          </div>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useOrderStore } from '@/stores/orders'
import { message } from 'ant-design-vue'
import { PlusOutlined, DeleteOutlined, CheckOutlined, UserOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const { t } = useI18n()
const orderStore = useOrderStore()

const formRef = ref()
const loading = ref(false)

const form = reactive({
  orderType: 'SERVICE',
  currency: 'CNY',
  description: '',
  contactEmail: '',
  contactPhone: '',
  shippingAddress: '',
  billingAddress: '',
  orderItems: [
    {
      productName: '',
      unitPrice: 0,
      quantity: 1,
      subtotal: 0
    }
  ]
})

const rules = {
  orderType: [
    { required: true, message: '请选择订单类型', trigger: 'change' }
  ],
  currency: [
    { required: true, message: '请选择货币', trigger: 'change' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 检查是否为实体商品订单
const isPhysicalOrder = computed(() => {
  return form.orderType === 'PHYSICAL'
})

// 计算总金额
const totalAmount = computed(() => {
  return form.orderItems.reduce((total, item) => {
    return total + parseFloat(item.subtotal || 0)
  }, 0).toFixed(2)
})

// 计算小计
const calculateSubtotal = (index) => {
  const item = form.orderItems[index]
  if (item.unitPrice && item.quantity) {
    item.subtotal = parseFloat((item.unitPrice * item.quantity).toFixed(2))
  } else {
    item.subtotal = 0
  }
}

// 添加商品项
const addItem = () => {
  form.orderItems.push({
    productName: '',
    unitPrice: 0,
    quantity: 1,
    subtotal: 0
  })
}

// 删除商品项
const removeItem = (index) => {
  if (form.orderItems.length > 1) {
    form.orderItems.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    // 验证订单项
    const validItems = form.orderItems.filter(item => 
      item.productName && item.unitPrice > 0 && item.quantity > 0
    )

    if (validItems.length === 0) {
      message.error(t('common.addValidProduct'))
      return
    }

    loading.value = true

    // 准备提交数据
    const orderData = {
      orderType: form.orderType,
      currency: form.currency,
      description: form.description,
      contactEmail: form.contactEmail,
      contactPhone: form.contactPhone,
      shippingAddress: form.shippingAddress,
      billingAddress: form.billingAddress,
      totalAmount: parseFloat(totalAmount.value),
      status: 'PENDING', // 新创建的订单状态为待支付
      orderItems: validItems.map(item => ({
        productName: item.productName,
        unitPrice: parseFloat(item.unitPrice),
        quantity: parseInt(item.quantity),
        subtotal: parseFloat(item.subtotal)
      }))
    }

    const response = await orderStore.createNewOrder(orderData)

    if (response.success) {
      message.success(t('common.orderCreateSuccess'))
      router.push('/admin/orders')
    } else {
      message.error(response.message || t('common.orderCreateFailed'))
    }
  } catch (error) {
    console.error('Create order error:', error)
    message.error(t('common.orderCreateFailed'))
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.order-create {
  max-width: 1200px;
  margin: 0 auto;
}

.form-card {
  margin-top: var(--space-5);
}

.order-items {
  width: 100%;
}

.order-item {
  margin-bottom: var(--space-4);
  padding: var(--space-4);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  background-color: var(--bg-surface);
}

.add-item-btn {
  margin-top: var(--space-4);
}

.total-amount {
  text-align: right;
  padding: var(--space-4);
  background-color: var(--bg-elevated);
  border-radius: var(--radius-md);
}

.total-label {
  font-size: var(--text-base);
  color: var(--text-secondary);
}

.field-description {
  display: flex;
  align-items: flex-start;
  margin-top: var(--space-2);
  padding: var(--space-2) var(--space-3);
  background-color: var(--primary-glow-subtle);
  border: 1px solid var(--primary-glow-medium);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  color: var(--primary-500);
  line-height: var(--leading-snug);
}

.field-description .anticon {
  margin-right: var(--space-1);
  margin-top: 1px;
  flex-shrink: 0;
}

.field-description span {
  flex: 1;
}
</style>


