<template>
  <div class="p-4">
    <PageWrapper>
      <!-- 头部面包屑和操作 -->
      <div class="mb-4 flex items-center justify-between">
        <Breadcrumb>
          <Breadcrumb.Item>
            <a @click="router.back()">报销管理</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>报销详情</Breadcrumb.Item>
        </Breadcrumb>

        <Space>
          <Button v-if="canEdit" type="primary" @click="handleEdit">
            <Icon icon="mdi:pencil" class="mr-1" />
            编辑
          </Button>
          <Button v-if="canSubmit" type="primary" @click="handleSubmit">
            <Icon icon="mdi:send" class="mr-1" />
            提交审批
          </Button>
          <Button v-if="canRevoke" danger @click="handleRevoke">
            <Icon icon="mdi:undo" class="mr-1" />
            撤回
          </Button>
          <Dropdown :trigger="['click']">
            <template #overlay>
              <Menu @click="handleMenuClick">
                <Menu.Item key="export">
                  <Icon icon="mdi:download" class="mr-2" />
                  导出PDF
                </Menu.Item>
                <Menu.Item key="print">
                  <Icon icon="mdi:printer" class="mr-2" />
                  打印
                </Menu.Item>
                <Menu.Item key="copy">
                  <Icon icon="mdi:content-copy" class="mr-2" />
                  复制
                </Menu.Item>
                <Menu.Divider v-if="canDelete" />
                <Menu.Item v-if="canDelete" key="delete" danger>
                  <Icon icon="mdi:delete" class="mr-2" />
                  删除
                </Menu.Item>
              </Menu>
            </template>
            <Button>
              更多操作
              <Icon icon="mdi:chevron-down" class="ml-1" />
            </Button>
          </Dropdown>
        </Space>
      </div>

      <!-- 报销单基本信息 -->
      <Card class="mb-4">
        <div class="flex items-start justify-between mb-6">
          <div class="flex-1">
            <div class="flex items-center mb-4">
              <h2 class="text-2xl font-bold mr-4">{{ reimbursement.reimbursementNo }}</h2>
              <Tag :color="getStatusColor(reimbursement.status)" class="text-base px-3 py-1">
                <Icon :icon="getStatusIcon(reimbursement.status)" class="mr-1" />
                {{ getStatusText(reimbursement.status) }}
              </Tag>
            </div>

            <Descriptions :column="3" bordered>
              <Descriptions.Item label="申请人">
                <div class="flex items-center">
                  <Avatar :size="32" :style="{ backgroundColor: '#1890ff' }">
                    {{ reimbursement.applicant.substring(0, 1) }}
                  </Avatar>
                  <div class="ml-2">
                    <div class="font-semibold">{{ reimbursement.applicant }}</div>
                    <div class="text-xs text-gray-400">{{ reimbursement.department }}</div>
                  </div>
                </div>
              </Descriptions.Item>
              <Descriptions.Item label="申请日期">{{ reimbursement.applyDate }}</Descriptions.Item>
              <Descriptions.Item label="报销金额">
                <span class="text-2xl font-bold text-red-600">¥{{ formatNumber(reimbursement.amount) }}</span>
              </Descriptions.Item>
              <Descriptions.Item label="费用类型" :span="2">
                <Space>
                  <Tag v-for="cat in reimbursement.categories" :key="cat" color="blue">{{ cat }}</Tag>
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="费用项数">{{ reimbursement.items.length }} 项</Descriptions.Item>
              <Descriptions.Item label="报销事由" :span="3">
                {{ reimbursement.reason }}
              </Descriptions.Item>
              <Descriptions.Item label="备注" :span="3">
                {{ reimbursement.notes || '无' }}
              </Descriptions.Item>
            </Descriptions>
          </div>
        </div>

        <!-- 审批进度 -->
        <div class="mt-6">
          <h3 class="text-lg font-semibold mb-4">审批进度</h3>
          <Steps :current="currentStep" :status="stepsStatus">
            <Steps.Step
              v-for="(step, index) in approvalSteps"
              :key="index"
              :title="step.title"
              :description="step.description"
            >
              <template #icon>
                <Icon v-if="step.status === 'finish'" icon="mdi:check-circle" class="text-green-500" />
                <Icon v-else-if="step.status === 'error'" icon="mdi:close-circle" class="text-red-500" />
                <Icon v-else-if="step.status === 'process'" icon="mdi:clock-outline" class="text-blue-500" />
                <Icon v-else icon="mdi:circle-outline" class="text-gray-400" />
              </template>
            </Steps.Step>
          </Steps>
        </div>
      </Card>

      <!-- 费用明细 -->
      <Card title="费用明细" class="mb-4">
        <Table
          :columns="itemColumns"
          :dataSource="reimbursement.items"
          :pagination="false"
          :scroll="{ x: 1000 }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'index'">
              {{ index + 1 }}
            </template>
            <template v-else-if="column.dataIndex === 'category'">
              <Tag color="blue">{{ record.category }}</Tag>
            </template>
            <template v-else-if="column.dataIndex === 'amount'">
              <span class="font-semibold">¥{{ formatNumber(record.amount) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'receipt'">
              <Tag :color="record.hasReceipt ? 'success' : 'warning'">
                {{ record.hasReceipt ? '已上传' : '未上传' }}
              </Tag>
            </template>
          </template>
          <template #summary>
            <Table.Summary fixed>
              <Table.Summary.Row>
                <Table.Summary.Cell :index="0" :colSpan="5" class="text-right font-bold">
                  合计金额:
                </Table.Summary.Cell>
                <Table.Summary.Cell :index="5" class="font-bold text-lg text-red-600">
                  ¥{{ formatNumber(totalAmount) }}
                </Table.Summary.Cell>
                <Table.Summary.Cell :index="6" />
              </Table.Summary.Row>
            </Table.Summary>
          </template>
        </Table>
      </Card>

      <!-- 附件列表 -->
      <Card title="附件资料" class="mb-4">
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div
            v-for="(attachment, index) in reimbursement.attachments"
            :key="index"
            class="border rounded-lg p-3 hover:shadow-md transition-shadow cursor-pointer"
            @click="previewAttachment(attachment)"
          >
            <div class="flex items-center">
              <Icon
                :icon="getFileIcon(attachment.type)"
                class="text-3xl mr-3"
                :style="{ color: getFileColor(attachment.type) }"
              />
              <div class="flex-1 overflow-hidden">
                <div class="text-sm font-semibold truncate">{{ attachment.name }}</div>
                <div class="text-xs text-gray-400">{{ attachment.size }}</div>
              </div>
            </div>
          </div>
        </div>
        <Empty v-if="reimbursement.attachments.length === 0" description="暂无附件" />
      </Card>

      <!-- 审批记录 -->
      <Card title="审批记录" class="mb-4">
        <Timeline>
          <Timeline.Item
            v-for="(record, index) in approvalRecords"
            :key="index"
            :color="getTimelineColor(record.action)"
          >
            <template #dot>
              <Icon :icon="getActionIcon(record.action)" class="text-lg" />
            </template>
            <div class="pb-4">
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center">
                  <Avatar :size="32" :style="{ backgroundColor: getRandomColor(record.operator) }">
                    {{ record.operator.substring(0, 1) }}
                  </Avatar>
                  <div class="ml-2">
                    <span class="font-semibold">{{ record.operator }}</span>
                    <span class="text-gray-500 ml-2">{{ record.role }}</span>
                  </div>
                </div>
                <span class="text-gray-400 text-sm">{{ record.time }}</span>
              </div>
              <div class="ml-10">
                <Tag :color="getActionColor(record.action)">{{ getActionText(record.action) }}</Tag>
                <div v-if="record.comment" class="mt-2 text-gray-600 bg-gray-50 p-3 rounded">
                  {{ record.comment }}
                </div>
              </div>
            </div>
          </Timeline.Item>
        </Timeline>
      </Card>

      <!-- 审批操作区（仅审批人可见） -->
      <Card v-if="showApprovalActions" title="审批操作" class="mb-4">
        <div class="max-w-2xl">
          <Form :model="approvalForm" layout="vertical">
            <Form.Item label="审批意见">
              <Input.TextArea
                v-model:value="approvalForm.comment"
                :rows="4"
                placeholder="请输入审批意见..."
              />
            </Form.Item>
            <Form.Item>
              <Space size="large">
                <Button
                  type="primary"
                  size="large"
                  @click="handleApprove('approved')"
                  :loading="approving"
                >
                  <Icon icon="mdi:check-circle" class="mr-1" />
                  通过
                </Button>
                <Button
                  danger
                  size="large"
                  @click="handleApprove('rejected')"
                  :loading="approving"
                >
                  <Icon icon="mdi:close-circle" class="mr-1" />
                  拒绝
                </Button>
                <Button size="large" @click="handleApprove('transfer')">
                  <Icon icon="mdi:share" class="mr-1" />
                  转交
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </Card>
    </PageWrapper>

    <!-- 附件预览Modal -->
    <Modal
      v-model:open="previewVisible"
      :title="previewFile?.name"
      width="80%"
      :footer="null"
    >
      <div class="flex items-center justify-center h-96">
        <img v-if="isImage(previewFile?.type)" :src="previewFile?.url" class="max-h-full" />
        <div v-else class="text-center">
          <Icon :icon="getFileIcon(previewFile?.type)" class="text-8xl mb-4" />
          <p>{{ previewFile?.name }}</p>
          <Button type="primary" class="mt-4" @click="downloadFile(previewFile)">
            <Icon icon="mdi:download" class="mr-1" />
            下载文件
          </Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { PageWrapper } from '@vben/common-ui';
import {
  Card, Button, Space, Tag, Descriptions, Steps, Table, Timeline,
  Avatar, Breadcrumb, Dropdown, Menu, Form, Input, Modal, Empty, message
} from 'ant-design-vue';
import { Icon } from '@iconify/vue';

defineOptions({ name: 'ReimbursementDetail' });

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

const previewVisible = ref(false);
const previewFile = ref<any>(null);
const approving = ref(false);

// 审批表单
const approvalForm = ref({
  comment: ''
});

// 模拟报销单数据
const reimbursement = ref({
  id: '1',
  reimbursementNo: 'RE202501001',
  applicant: '张三',
  department: '技术部',
  applyDate: '2025-01-08',
  amount: 3850.00,
  categories: ['差旅', '餐饮', '交通'],
  reason: '客户现场技术支持差旅费用报销',
  notes: '北京客户现场，为期3天的技术支持工作',
  status: 'pending',
  items: [
    {
      key: '1',
      date: '2025-01-05',
      category: '交通',
      description: '北京往返高铁票',
      amount: 1200.00,
      hasReceipt: true
    },
    {
      key: '2',
      date: '2025-01-05',
      category: '住宿',
      description: '北京希尔顿酒店 2晚',
      amount: 1800.00,
      hasReceipt: true
    },
    {
      key: '3',
      date: '2025-01-06',
      category: '餐饮',
      description: '客户商务晚餐',
      amount: 650.00,
      hasReceipt: true
    },
    {
      key: '4',
      date: '2025-01-07',
      category: '交通',
      description: '北京市内打车费用',
      amount: 200.00,
      hasReceipt: true
    }
  ],
  attachments: [
    {
      name: '高铁票.jpg',
      type: 'image',
      size: '2.5MB',
      url: 'https://via.placeholder.com/800x600'
    },
    {
      name: '酒店发票.pdf',
      type: 'pdf',
      size: '1.2MB',
      url: ''
    },
    {
      name: '餐饮发票.jpg',
      type: 'image',
      size: '1.8MB',
      url: 'https://via.placeholder.com/800x600'
    }
  ]
});

// 审批步骤
const approvalSteps = ref([
  {
    title: '提交申请',
    description: '张三 · 2025-01-08 09:30',
    status: 'finish'
  },
  {
    title: '部门经理审批',
    description: '李经理 · 审批中',
    status: 'process'
  },
  {
    title: '财务审核',
    description: '待审核',
    status: 'wait'
  },
  {
    title: '总经理审批',
    description: '待审批',
    status: 'wait'
  },
  {
    title: '财务支付',
    description: '待支付',
    status: 'wait'
  }
]);

// 审批记录
const approvalRecords = ref([
  {
    operator: '张三',
    role: '申请人',
    action: 'submit',
    time: '2025-01-08 09:30:00',
    comment: '提交报销申请'
  },
  {
    operator: '李经理',
    role: '部门经理',
    action: 'review',
    time: '2025-01-08 14:20:00',
    comment: '正在审核中，请补充商务晚餐的详细说明'
  }
]);

// 费用明细表格列
const itemColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 80
  },
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 120
  },
  {
    title: '费用类型',
    dataIndex: 'category',
    key: 'category',
    width: 120
  },
  {
    title: '费用说明',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120
  },
  {
    title: '发票状态',
    dataIndex: 'receipt',
    key: 'receipt',
    width: 100
  }
];

// 计算属性
const totalAmount = computed(() => {
  return reimbursement.value.items.reduce((sum, item) => sum + item.amount, 0);
});

const currentStep = computed(() => {
  const finishIndex = approvalSteps.value.findIndex(step => step.status === 'process');
  return finishIndex >= 0 ? finishIndex : approvalSteps.value.length;
});

const stepsStatus = computed(() => {
  if (reimbursement.value.status === 'rejected') return 'error';
  if (reimbursement.value.status === 'paid') return 'finish';
  return 'process';
});

const canEdit = computed(() => {
  return reimbursement.value.status === 'draft' || reimbursement.value.status === 'rejected';
});

const canSubmit = computed(() => {
  return reimbursement.value.status === 'draft';
});

const canRevoke = computed(() => {
  return reimbursement.value.status === 'pending';
});

const canDelete = computed(() => {
  return reimbursement.value.status === 'draft' || reimbursement.value.status === 'rejected';
});

const showApprovalActions = computed(() => {
  // 检查URL参数或当前用户是否为审批人
  return route.query.action === 'approve' && reimbursement.value.status === 'pending';
});

// 方法
const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(num);
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'draft': 'default',
    'pending': 'processing',
    'approved': 'success',
    'rejected': 'error',
    'paid': 'success'
  };
  return colorMap[status] || 'default';
};

const getStatusIcon = (status: string) => {
  const iconMap: Record<string, string> = {
    'draft': 'mdi:file-document-edit-outline',
    'pending': 'mdi:clock-outline',
    'approved': 'mdi:check-circle',
    'rejected': 'mdi:close-circle',
    'paid': 'mdi:cash-check'
  };
  return iconMap[status] || 'mdi:help-circle';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'draft': '草稿',
    'pending': '待审批',
    'approved': '已通过',
    'rejected': '已拒绝',
    'paid': '已支付'
  };
  return textMap[status] || status;
};

const getFileIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'image': 'mdi:file-image',
    'pdf': 'mdi:file-pdf-box',
    'excel': 'mdi:file-excel',
    'word': 'mdi:file-word'
  };
  return iconMap[type] || 'mdi:file-document';
};

const getFileColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'image': '#52c41a',
    'pdf': '#f5222d',
    'excel': '#13c2c2',
    'word': '#1890ff'
  };
  return colorMap[type] || '#666';
};

const isImage = (type?: string) => {
  return type === 'image';
};

const getTimelineColor = (action: string) => {
  const colorMap: Record<string, string> = {
    'submit': 'blue',
    'review': 'orange',
    'approved': 'green',
    'rejected': 'red',
    'transfer': 'purple'
  };
  return colorMap[action] || 'gray';
};

const getActionIcon = (action: string) => {
  const iconMap: Record<string, string> = {
    'submit': 'mdi:send',
    'review': 'mdi:eye',
    'approved': 'mdi:check-circle',
    'rejected': 'mdi:close-circle',
    'transfer': 'mdi:share'
  };
  return iconMap[action] || 'mdi:circle';
};

const getActionColor = (action: string) => {
  const colorMap: Record<string, string> = {
    'submit': 'blue',
    'review': 'orange',
    'approved': 'success',
    'rejected': 'error',
    'transfer': 'purple'
  };
  return colorMap[action] || 'default';
};

const getActionText = (action: string) => {
  const textMap: Record<string, string> = {
    'submit': '提交申请',
    'review': '审核中',
    'approved': '已通过',
    'rejected': '已拒绝',
    'transfer': '转交'
  };
  return textMap[action] || action;
};

const getRandomColor = (str: string) => {
  const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
  const hash = str.split('').reduce((acc, char) => char.charCodeAt(0) + acc, 0);
  return colors[hash % colors.length];
};

// 事件处理
const handleEdit = () => {
  router.push(`/reimbursement/create?id=${reimbursement.value.id}&mode=edit`);
};

const handleSubmit = () => {
  Modal.confirm({
    title: '确认提交审批',
    content: '提交后将无法修改，是否确认提交审批？',
    onOk: () => {
      message.success('提交成功');
      router.back();
    }
  });
};

const handleRevoke = () => {
  Modal.confirm({
    title: '确认撤回',
    content: '是否确认撤回此报销单？',
    onOk: () => {
      message.success('撤回成功');
      router.back();
    }
  });
};

const handleMenuClick = ({ key }: { key: string }) => {
  switch (key) {
    case 'export':
      message.info('正在导出PDF...');
      break;
    case 'print':
      window.print();
      break;
    case 'copy':
      message.success('复制成功');
      break;
    case 'delete':
      Modal.confirm({
        title: '确认删除',
        content: '删除后无法恢复，是否确认删除？',
        okType: 'danger',
        onOk: () => {
          message.success('删除成功');
          router.back();
        }
      });
      break;
  }
};

const previewAttachment = (attachment: any) => {
  previewFile.value = attachment;
  previewVisible.value = true;
};

const downloadFile = (file: any) => {
  message.info(`正在下载 ${file.name}...`);
};

const handleApprove = async (action: string) => {
  if (!approvalForm.value.comment && action === 'rejected') {
    message.warning('拒绝时必须填写审批意见');
    return;
  }

  Modal.confirm({
    title: action === 'approved' ? '确认通过' : action === 'rejected' ? '确认拒绝' : '确认转交',
    content: `是否确认${action === 'approved' ? '通过' : action === 'rejected' ? '拒绝' : '转交'}此报销申请？`,
    onOk: async () => {
      approving.value = true;
      // 模拟API调用
      setTimeout(() => {
        approving.value = false;
        message.success('操作成功');
        router.back();
      }, 1000);
    }
  });
};

onMounted(() => {
  // 根据路由参数加载报销单详情
  const id = route.params.id;
  console.log('加载报销单详情:', id);
});
</script>

<style scoped>
:deep(.ant-descriptions-item-label) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-steps-item-description) {
  font-size: 12px;
}

@media print {
  .no-print {
    display: none !important;
  }
}
</style>
