<template>
  <ElDialog
    v-model="visible"
    :title="$t('billing.dialog.createTitle')"
    width="900px"
    destroy-on-close
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px" v-loading="loading">
      <ElRow :gutter="16">
        <ElCol :span="12">
          <ElFormItem :label="$t('billing.field.tenantName')" prop="tenantId">
            <ElSelect
              v-model="formData.tenantId"
              :placeholder="$t('billing.placeholder.selectTenant')"
              filterable
              remote
              :remote-method="handleSearchTenant"
              :loading="tenantLoading"
              style="width: 100%"
            >
              <ElOption
                v-for="tenant in tenantOptions"
                :key="tenant.id"
                :label="tenant.name"
                :value="tenant.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('billing.field.billingType')" prop="billingType">
            <ElSelect
              v-model="formData.billingType"
              :placeholder="$t('billing.placeholder.selectBillingType')"
              style="width: 100%"
            >
              <ElOption
                v-for="opt in billingTypeOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('billing.field.dueDate')" prop="dueDate">
            <ElDatePicker
              v-model="formData.dueDate"
              type="date"
              :placeholder="$t('billing.placeholder.selectDueDate')"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('billing.field.amountDue')">
            <ElInputNumber
              v-model="formData.amountDue"
              :min="0"
              :precision="2"
              :controls="false"
              style="width: 100%"
              disabled
            />
            <div class="mt-1 text-xs text-gray-500">{{ $t('billing.hint.amountAutoSum') }}</div>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElDivider class="my-3" />

      <!-- 1. 明细项编辑 -->
      <div class="flex items-center justify-between mb-2">
        <div class="font-semibold">{{ $t('billing.drawer.tabs.lineItems') }}</div>
        <ElButton type="primary" plain size="small" @click="handleAddLineItem" v-ripple>
          <ArtSvgIcon icon="ri:add-line" />
          {{ $t('billing.action.addLineItem') }}
        </ElButton>
      </div>

      <ElTable :data="formData.lineItems" stripe border class="mb-3">
        <ElTableColumn :label="$t('billing.lineItem.itemType')" width="160">
          <template #default="{ row }">
            <ElInput
              v-model="row.itemType"
              :placeholder="$t('billing.placeholder.enterItemType')"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="$t('billing.lineItem.description')" min-width="260">
          <template #default="{ row }">
            <ElInput
              v-model="row.description"
              :placeholder="$t('billing.placeholder.enterDescription')"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="$t('billing.lineItem.quantity')" width="140">
          <template #default="{ row }">
            <ElInputNumber
              v-model="row.quantity"
              :min="0.01"
              :precision="2"
              controls-position="right"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="$t('billing.lineItem.unitPrice')" width="160">
          <template #default="{ row }">
            <ElInputNumber
              v-model="row.unitPrice"
              :min="0"
              :precision="2"
              controls-position="right"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="$t('billing.lineItem.amount')" width="160">
          <template #default="{ row }">
            <span class="font-semibold">¥{{ calcLineAmount(row).toFixed(2) }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="$t('table.column.action')" width="120" fixed="right">
          <template #default="{ $index }">
            <ElButton type="danger" link @click="handleRemoveLineItem($index)">
              {{ $t('common.delete') }}
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <ElFormItem :label="$t('billing.field.notes')" prop="notes">
        <ElInput
          v-model="formData.notes"
          type="textarea"
          :rows="3"
          :placeholder="$t('billing.placeholder.enterNotes')"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="flex justify-end gap-2">
        <ElButton @click="visible = false">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="loading" v-ripple>
          {{ $t('common.confirm') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElDatePicker,
    ElDialog,
    ElDivider,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElMessage,
    ElOption,
    ElRow,
    ElCol,
    ElSelect,
    ElTable,
    ElTableColumn,
    type FormInstance,
    type FormRules
  } from 'element-plus'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { createBilling } from '@/api/billing'
  import { fetchGetTenantList } from '@/api/tenant'
  import { BillingType } from '@/enums/Billing'

  defineOptions({ name: 'CreateBillingDialog' })

  const { t } = useI18n()
  const emit = defineEmits<{
    success: []
  }>()

  interface LineItemForm {
    itemType: string
    description: string
    quantity: number
    unitPrice: number
  }

  // 1. 响应式状态
  const visible = ref(false)
  const loading = ref(false)
  const tenantLoading = ref(false)
  const formRef = ref<FormInstance>()
  const tenantOptions = ref<Api.Tenant.TenantDto[]>([])

  // 2. 表单数据
  const formData = reactive<{
    tenantId: string
    billingType: BillingType | undefined
    amountDue: number
    dueDate: string
    lineItems: LineItemForm[]
    notes: string
  }>({
    tenantId: '',
    billingType: BillingType.Manual,
    amountDue: 0,
    dueDate: '',
    lineItems: [{ itemType: 'Manual', description: '', quantity: 1, unitPrice: 0 }],
    notes: ''
  })

  // 3. 选项
  const billingTypeOptions = computed(() => {
    return [
      { label: t('billing.billingType.subscription'), value: BillingType.Subscription },
      { label: t('billing.billingType.quotaPurchase'), value: BillingType.QuotaPurchase },
      { label: t('billing.billingType.manual'), value: BillingType.Manual },
      { label: t('billing.billingType.renewal'), value: BillingType.Renewal }
    ]
  })

  // 4. 规则校验
  const rules: FormRules = {
    tenantId: [
      { required: true, message: t('billing.validation.tenantRequired'), trigger: 'change' }
    ],
    billingType: [
      { required: true, message: t('billing.validation.billingTypeRequired'), trigger: 'change' }
    ],
    dueDate: [
      { required: true, message: t('billing.validation.dueDateRequired'), trigger: 'change' }
    ]
  }

  // 5. 计算金额（自动汇总）
  const calcLineAmount = (row: LineItemForm) => {
    const qty = Number(row.quantity || 0)
    const price = Number(row.unitPrice || 0)
    return Math.max(0, qty * price)
  }

  watch(
    () => formData.lineItems.map((x) => [x.quantity, x.unitPrice]),
    () => {
      formData.amountDue = formData.lineItems.reduce((sum, x) => sum + calcLineAmount(x), 0)
    },
    { deep: true, immediate: true }
  )

  // 6. 明细项操作
  const handleAddLineItem = () => {
    formData.lineItems.push({ itemType: 'Manual', description: '', quantity: 1, unitPrice: 0 })
  }

  const handleRemoveLineItem = (index: number) => {
    if (formData.lineItems.length <= 1) return
    formData.lineItems.splice(index, 1)
  }

  const validateLineItems = () => {
    if (formData.lineItems.length === 0) {
      ElMessage.warning(t('billing.validation.lineItemsRequired'))
      return false
    }

    for (const [idx, item] of formData.lineItems.entries()) {
      if (!item.description?.trim()) {
        ElMessage.warning(t('billing.validation.lineItemDescriptionRequired', { index: idx + 1 }))
        return false
      }
      if (Number(item.quantity) <= 0) {
        ElMessage.warning(t('billing.validation.lineItemQuantityInvalid', { index: idx + 1 }))
        return false
      }
      if (Number(item.unitPrice) < 0) {
        ElMessage.warning(t('billing.validation.lineItemUnitPriceInvalid', { index: idx + 1 }))
        return false
      }
    }

    if (formData.amountDue <= 0) {
      ElMessage.warning(t('billing.validation.amountMin'))
      return false
    }

    return true
  }

  // 7. 搜索租户
  const handleSearchTenant = async (query: string) => {
    if (!query?.trim()) return

    tenantLoading.value = true
    try {
      const res = await fetchGetTenantList({
        Keyword: query.trim(),
        Page: 1,
        PageSize: 20
      })
      tenantOptions.value = res.items || []
    } catch (error) {
      console.error('Search tenant error:', error)
    } finally {
      tenantLoading.value = false
    }
  }

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

    try {
      // 1. 表单校验
      await formRef.value.validate()
      if (!validateLineItems()) return

      // 2. 组装后端命令参数
      const payload: Api.Billing.CreateBillingCommand = {
        tenantId: formData.tenantId,
        billingType: formData.billingType ?? BillingType.Manual,
        amountDue: Number(formData.amountDue || 0),
        dueDate: formData.dueDate,
        lineItems: formData.lineItems.map((x) => ({
          itemType: x.itemType || 'Manual',
          description: x.description.trim(),
          quantity: Number(x.quantity || 0),
          unitPrice: Number(x.unitPrice || 0),
          amount: calcLineAmount(x)
        })),
        notes: formData.notes?.trim() || undefined
      }

      // 3. 请求创建
      loading.value = true
      await createBilling(payload)

      ElMessage.success(t('billing.message.createSuccess'))
      emit('success')
      visible.value = false
    } catch (error) {
      console.error('Create billing error:', error)
    } finally {
      loading.value = false
    }
  }

  // 9. 关闭后重置
  const handleClosed = () => {
    formRef.value?.resetFields()
    formData.tenantId = ''
    formData.billingType = BillingType.Manual
    formData.dueDate = ''
    formData.notes = ''
    formData.lineItems = [{ itemType: 'Manual', description: '', quantity: 1, unitPrice: 0 }]
  }

  // 10. 打开对话框
  const open = () => {
    visible.value = true
  }

  defineExpose({ open })
</script>
