<script setup lang="ts">
import dayjs from 'dayjs';
import {
  Button,
  Card,
  Descriptions,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Select,
  Space,
  Tag,
  message,
} from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import type { FinanceApi } from '#/api/core/finance';
import { useFinanceStore } from '#/store/finance';

import { STATUS_OPTIONS, formatStatus } from './status';

defineOptions({ name: 'FinanceReimbursementDetail' });

const route = useRoute();
const router = useRouter();
const financeStore = useFinanceStore();

const reimbursementId = Number(route.params.id);
const loading = ref(false);
const saving = ref(false);
const formRef = ref<FormInstance>();

const reimbursement = computed(() =>
  financeStore.reimbursements.find((item) => item.id === reimbursementId),
);

const formState = reactive({
  description: '',
  amount: 0,
  currency: 'CNY',
  project: '',
  memo: '',
  submittedBy: '',
  approvedBy: '',
  reimbursementBatch: '',
  reviewNotes: '',
  status: 'pending' as FinanceApi.TransactionStatus,
});

const rules = {
  description: [{ required: true, message: '请填写报销内容' }],
  amount: [
    { required: true, message: '请输入金额' },
    {
      validator(_: unknown, value: number) {
        if (value && value > 0) return Promise.resolve();
        return Promise.reject(new Error('金额需大于 0'));
      },
    },
  ],
};

const canEdit = computed(() => !reimbursement.value?.isDeleted);

watch(
  reimbursement,
  (value) => {
    if (!value) return;
    formState.description = value.description;
    formState.amount = value.amount;
    formState.currency = value.currency;
    formState.project = value.project ?? '';
    formState.memo = value.memo ?? '';
    formState.submittedBy = value.submittedBy ?? '';
    formState.approvedBy = value.approvedBy ?? '';
    formState.reimbursementBatch = value.reimbursementBatch ?? '';
    formState.reviewNotes = value.reviewNotes ?? '';
    formState.status = value.status;
  },
  { immediate: true },
);

async function ensureData() {
  if (
    financeStore.reimbursements.length === 0 ||
    !reimbursement.value
  ) {
    loading.value = true;
    try {
      await financeStore.fetchReimbursements({ includeDeleted: true });
    } finally {
      loading.value = false;
    }
  }
}

async function handleSave() {
  if (!reimbursement.value) return;
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  saving.value = true;
  try {
    await financeStore.updateReimbursement(reimbursement.value.id, {
      description: formState.description,
      amount: formState.amount,
      currency: formState.currency,
      project: formState.project || null,
      memo: formState.memo || null,
      submittedBy: formState.submittedBy || null,
      approvedBy: formState.approvedBy || null,
      reimbursementBatch: formState.reimbursementBatch || null,
      reviewNotes: formState.reviewNotes || null,
      status: formState.status,
    });
    message.success('信息已更新');
  } catch (error) {
    console.error(error);
    message.error('更新失败，请稍后重试');
  } finally {
    saving.value = false;
  }
}

async function handleApprove() {
  if (!reimbursement.value) return;
  try {
    await financeStore.updateReimbursement(reimbursement.value.id, {
      status: 'approved',
    });
    message.success('已审批通过');
  } catch (error) {
    console.error(error);
    message.error('审批失败，请稍后重试');
  }
}

async function handleReject() {
  if (!reimbursement.value) return;
  try {
    await financeStore.updateReimbursement(reimbursement.value.id, {
      status: 'rejected',
      reviewNotes: formState.reviewNotes || reimbursement.value.reviewNotes,
    });
    message.success('已驳回');
  } catch (error) {
    console.error(error);
    message.error('驳回失败，请稍后重试');
  }
}

async function handleMarkPaid() {
  if (!reimbursement.value) return;
  try {
    await financeStore.updateReimbursement(reimbursement.value.id, {
      status: 'paid',
    });
    message.success('已标记为报销完成');
  } catch (error) {
    console.error(error);
    message.error('操作失败，请稍后重试');
  }
}

async function handleRestore() {
  if (!reimbursement.value) return;
  try {
    await financeStore.restoreReimbursement(reimbursement.value.id);
    message.success('已恢复报销单');
  } catch (error) {
    console.error(error);
    message.error('恢复失败，请稍后重试');
  }
}

async function handleDelete() {
  if (!reimbursement.value) return;
  try {
    await financeStore.deleteReimbursement(reimbursement.value.id);
    message.success('已移入回收站');
  } catch (error) {
    console.error(error);
    message.error('操作失败，请稍后重试');
  }
}

function goBack() {
  router.back();
}

onMounted(() => {
  ensureData();
});
</script>

<template>
  <div class="p-6 space-y-4">
    <Button @click="goBack">返回</Button>

    <Card v-if="loading">
      <span>加载中...</span>
    </Card>

    <Card v-else-if="!reimbursement">
      <Space direction="vertical">
        <span>未找到报销单记录，可能已被删除或编号错误。</span>
        <Button type="primary" @click="goBack">返回列表</Button>
      </Space>
    </Card>

    <template v-else>
      <Card>
        <template #title>报销概览</template>
        <Space direction="vertical" class="w-full">
          <Space align="center">
            <Tag :color="formatStatus(reimbursement.status).color">
              {{ formatStatus(reimbursement.status).label }}
            </Tag>
            <span class="text-gray-500 text-sm">
              创建于 {{ dayjs(reimbursement.createdAt).format('YYYY-MM-DD HH:mm') }}
            </span>
          </Space>
          <Descriptions :column="1" size="small" bordered>
            <Descriptions.Item label="报销内容">
              {{ reimbursement.description || '未填写' }}
            </Descriptions.Item>
            <Descriptions.Item label="报销日期">
              {{ dayjs(reimbursement.transactionDate).format('YYYY-MM-DD') }}
            </Descriptions.Item>
            <Descriptions.Item label="金额">
              {{ reimbursement.amount.toFixed(2) }} {{ reimbursement.currency }}
              （折合 {{ reimbursement.amountInBase.toFixed(2) }} CNY）
            </Descriptions.Item>
            <Descriptions.Item label="所属项目">
              {{ reimbursement.project || '未指定' }}
            </Descriptions.Item>
            <Descriptions.Item label="提交人">
              {{ reimbursement.submittedBy || '未填写' }}
            </Descriptions.Item>
            <Descriptions.Item label="审批人">
              {{ reimbursement.approvedBy || '未指定' }}
            </Descriptions.Item>
            <Descriptions.Item label="审批备注">
              {{ reimbursement.reviewNotes || '暂无' }}
            </Descriptions.Item>
            <Descriptions.Item label="批次号">
              {{ reimbursement.reimbursementBatch || '未设置' }}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {{ dayjs(reimbursement.createdAt).format('YYYY-MM-DD HH:mm') }}
            </Descriptions.Item>
          </Descriptions>
        </Space>
      </Card>

      <Card>
        <template #title>更新报销信息</template>
        <template #extra>
          <Space>
            <Button type="primary" :loading="saving" :disabled="!canEdit" @click="handleSave">
              保存变更
            </Button>
            <Button :disabled="!canEdit" @click="handleApprove">
              审批通过
            </Button>
            <Button danger :disabled="!canEdit" @click="handleReject">
              驳回
            </Button>
            <Button :disabled="!canEdit" @click="handleMarkPaid">
              标记已报销
            </Button>
            <Popconfirm
              v-if="!reimbursement.isDeleted"
              title="确定要删除该报销单？"
              ok-text="删除"
              cancel-text="取消"
              @confirm="handleDelete"
            >
              <Button danger type="link">移入回收站</Button>
            </Popconfirm>
            <Button
              v-else
              type="link"
              @click="handleRestore"
            >
              恢复
            </Button>
          </Space>
        </template>

        <Form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
          class="grid grid-cols-1 gap-4 md:grid-cols-2"
        >
          <Form.Item label="报销内容" name="description">
            <Input
              v-model:value="formState.description"
              :disabled="!canEdit"
              placeholder="描述报销事项"
            />
          </Form.Item>
          <Form.Item label="金额" name="amount">
            <InputNumber
              v-model:value="formState.amount"
              :disabled="!canEdit"
              :precision="2"
              :min="0"
              class="w-full"
            />
          </Form.Item>
          <Form.Item label="币种" name="currency">
            <Input
              v-model:value="formState.currency"
              :disabled="!canEdit"
              placeholder="例如 CNY"
            />
          </Form.Item>
          <Form.Item label="所属项目" name="project">
            <Input
              v-model:value="formState.project"
              :disabled="!canEdit"
              placeholder="可填写项目或成本中心"
            />
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input.TextArea
              v-model:value="formState.memo"
              :disabled="!canEdit"
              :rows="3"
              placeholder="补充说明"
            />
          </Form.Item>
          <Form.Item label="提交人" name="submittedBy">
            <Input
              v-model:value="formState.submittedBy"
              :disabled="!canEdit"
              placeholder="报销申请人"
            />
          </Form.Item>
          <Form.Item label="审批人" name="approvedBy">
            <Input
              v-model:value="formState.approvedBy"
              :disabled="!canEdit"
              placeholder="审批负责人"
            />
          </Form.Item>
          <Form.Item label="审批备注" name="reviewNotes">
            <Input.TextArea
              v-model:value="formState.reviewNotes"
              :rows="3"
              :disabled="!canEdit"
              placeholder="审批意见、驳回原因等"
            />
          </Form.Item>
          <Form.Item label="批次号" name="reimbursementBatch">
            <Input
              v-model:value="formState.reimbursementBatch"
              :disabled="!canEdit"
              placeholder="报销批次或审批编号"
            />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              v-model:value="formState.status"
              :options="STATUS_OPTIONS"
              :disabled="!canEdit"
            />
          </Form.Item>
        </Form>
      </Card>
    </template>
  </div>
</template>
