<script setup lang="ts">
/**
 * 文件职责：成本明细编辑抽屉（新增/编辑）。
 */
import type {
  FinanceCostCategoryCode,
  FinanceCostEntryDetailDto,
} from '#/api/finance/cost';

import { computed, reactive, watch } from 'vue';

import { Button, Drawer, Form, Input, InputNumber } from 'ant-design-vue';

import { roundAmount } from '../composables/cost-page/helpers';

interface Props {
  category: FinanceCostCategoryCode;
  categoryText: string;
  mode: 'create' | 'edit';
  open: boolean;
  sourceItem?: FinanceCostEntryDetailDto;
  submitting: boolean;
}

interface EditorFormState {
  amount: number;
  itemId?: string;
  itemName: string;
  quantity?: number;
  sortOrder: number;
  unitPrice?: number;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'submit', payload: FinanceCostEntryDetailDto): void;
}>();

const formState = reactive<EditorFormState>({
  itemId: undefined,
  itemName: '',
  amount: 0,
  quantity: 0,
  unitPrice: 0,
  sortOrder: 1,
});

const isLaborCategory = computed(() => props.category === 'labor');
const drawerTitle = computed(() =>
  props.mode === 'create'
    ? `新增${props.categoryText}明细`
    : `编辑${props.categoryText}明细`,
);

const laborComputedAmount = computed(() => {
  if (!isLaborCategory.value) return formState.amount;
  return roundAmount((formState.quantity ?? 0) * (formState.unitPrice ?? 0));
});

watch(
  () => [props.open, props.sourceItem, props.mode] as const,
  () => {
    if (!props.open) return;

    formState.itemId = props.sourceItem?.itemId;
    formState.itemName = props.sourceItem?.itemName ?? '';
    formState.amount = props.sourceItem?.amount ?? 0;
    formState.quantity = props.sourceItem?.quantity ?? 0;
    formState.unitPrice = props.sourceItem?.unitPrice ?? 0;
    formState.sortOrder = props.sourceItem?.sortOrder ?? 1;
  },
  { immediate: true },
);

function handleSubmit() {
  if (!formState.itemName.trim()) {
    return;
  }

  formState.amount = isLaborCategory.value
    ? laborComputedAmount.value
    : roundAmount(formState.amount);

  emit('submit', {
    itemId: formState.itemId,
    itemName: formState.itemName.trim(),
    amount: Math.max(0, formState.amount),
    quantity: isLaborCategory.value
      ? roundAmount(formState.quantity ?? 0)
      : undefined,
    unitPrice: isLaborCategory.value
      ? roundAmount(formState.unitPrice ?? 0)
      : undefined,
    sortOrder: Math.max(1, Number(formState.sortOrder || 1)),
  });
}
</script>

<template>
  <Drawer
    :open="props.open"
    :title="drawerTitle"
    width="460"
    @close="emit('close')"
  >
    <Form layout="vertical">
      <Form.Item label="明细名称" required>
        <Input
          :value="formState.itemName"
          :maxlength="64"
          placeholder="请输入明细名称"
          @update:value="(value) => (formState.itemName = String(value ?? ''))"
        />
      </Form.Item>

      <template v-if="isLaborCategory">
        <Form.Item label="人数" required>
          <InputNumber
            class="fc-full-input"
            :min="0"
            :precision="2"
            :controls="false"
            :value="formState.quantity"
            @update:value="(value) => (formState.quantity = Number(value ?? 0))"
          />
        </Form.Item>

        <Form.Item label="月薪" required>
          <InputNumber
            class="fc-full-input"
            :min="0"
            :precision="2"
            :controls="false"
            :value="formState.unitPrice"
            @update:value="
              (value) => (formState.unitPrice = Number(value ?? 0))
            "
          />
        </Form.Item>

        <Form.Item label="小计">
          <InputNumber
            class="fc-full-input"
            :value="laborComputedAmount"
            :precision="2"
            :controls="false"
            disabled
          />
        </Form.Item>
      </template>

      <Form.Item v-else label="金额" required>
        <InputNumber
          class="fc-full-input"
          :min="0"
          :precision="2"
          :controls="false"
          :value="formState.amount"
          @update:value="(value) => (formState.amount = Number(value ?? 0))"
        />
      </Form.Item>

      <Form.Item label="排序">
        <InputNumber
          class="fc-full-input"
          :min="1"
          :precision="0"
          :controls="false"
          :value="formState.sortOrder"
          @update:value="(value) => (formState.sortOrder = Number(value ?? 1))"
        />
      </Form.Item>
    </Form>

    <template #footer>
      <div class="fc-drawer-footer">
        <Button @click="emit('close')">取消</Button>
        <Button
          type="primary"
          :loading="props.submitting"
          :disabled="!formState.itemName.trim()"
          @click="handleSubmit"
        >
          确认
        </Button>
      </div>
    </template>
  </Drawer>
</template>
