<template>
  <div class="p-4">
    <PageWrapper title="报销管理" content="全面的报销单管理系统，支持创建、审批、追踪报销流程">
      <!-- 顶部操作栏 -->
      <Card class="mb-4">
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center space-x-4">
            <Input.Search
              v-model:value="searchText"
              placeholder="搜索报销单号、申请人、事由..."
              style="width: 350px"
              @search="onSearch"
            />
            <Select v-model:value="filterStatus" style="width: 140px" placeholder="状态筛选" @change="onFilterChange">
              <Select.Option value="">全部状态</Select.Option>
              <Select.Option value="draft">草稿</Select.Option>
              <Select.Option value="pending">待审批</Select.Option>
              <Select.Option value="approved">已通过</Select.Option>
              <Select.Option value="rejected">已拒绝</Select.Option>
              <Select.Option value="paid">已支付</Select.Option>
              <Select.Option value="cancelled">已取消</Select.Option>
            </Select>
            <Select v-model:value="filterDepartment" style="width: 150px" placeholder="部门筛选" @change="onFilterChange">
              <Select.Option value="">全部部门</Select.Option>
              <Select.Option v-for="dept in departments" :key="dept" :value="dept">{{ dept }}</Select.Option>
            </Select>
            <RangePicker v-model:value="dateFilter" placeholder="['申请日期', '结束日期']" @change="onDateChange" />
          </div>
          <div class="flex items-center space-x-2">
            <Button type="primary" @click="goToCreate">
              <Icon icon="mdi:plus" class="mr-1" />
              创建报销单
            </Button>
            <Dropdown :trigger="['click']">
              <template #overlay>
                <Menu @click="handleExport">
                  <Menu.Item key="excel">导出Excel</Menu.Item>
                  <Menu.Item key="pdf">导出PDF</Menu.Item>
                  <Menu.Item key="selected">导出选中</Menu.Item>
                </Menu>
              </template>
              <Button>
                <Icon icon="mdi:download" class="mr-1" />
                导出
                <Icon icon="mdi:chevron-down" class="ml-1" />
              </Button>
            </Dropdown>
          </div>
        </div>

        <!-- 快捷筛选标签 -->
        <div class="flex items-center space-x-2">
          <span class="text-gray-500 text-sm">快捷筛选:</span>
          <Tag
            :color="quickFilter === '' ? 'blue' : 'default'"
            class="cursor-pointer"
            @click="quickFilter = ''; loadReimbursements()"
          >
            全部 ({{ statistics.total }})
          </Tag>
          <Tag
            :color="quickFilter === 'my' ? 'blue' : 'default'"
            class="cursor-pointer"
            @click="quickFilter = 'my'; loadReimbursements()"
          >
            我的报销 ({{ statistics.myTotal }})
          </Tag>
          <Tag
            :color="quickFilter === 'pending' ? 'orange' : 'default'"
            class="cursor-pointer"
            @click="quickFilter = 'pending'; loadReimbursements()"
          >
            待我审批 ({{ statistics.pendingApproval }})
          </Tag>
          <Tag
            :color="quickFilter === 'approved' ? 'green' : 'default'"
            class="cursor-pointer"
            @click="quickFilter = 'approved'; loadReimbursements()"
          >
            已通过 ({{ statistics.approved }})
          </Tag>
        </div>
      </Card>

      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <Card class="text-center hover:shadow-lg transition-shadow">
          <Statistic
            title="本月报销总额"
            :value="statistics.monthTotal"
            :precision="2"
            prefix="¥"
            value-style="color: #1890ff"
          />
          <div class="text-xs text-gray-400 mt-2">较上月 +15.2%</div>
        </Card>
        <Card class="text-center hover:shadow-lg transition-shadow">
          <Statistic
            title="待审批金额"
            :value="statistics.pendingAmount"
            :precision="2"
            prefix="¥"
            value-style="color: #faad14"
          />
          <div class="text-xs text-gray-400 mt-2">{{ statistics.pendingApproval }} 笔待审</div>
        </Card>
        <Card class="text-center hover:shadow-lg transition-shadow">
          <Statistic
            title="已支付金额"
            :value="statistics.paidAmount"
            :precision="2"
            prefix="¥"
            value-style="color: #52c41a"
          />
          <div class="text-xs text-gray-400 mt-2">{{ statistics.paid }} 笔已支付</div>
        </Card>
        <Card class="text-center hover:shadow-lg transition-shadow">
          <Statistic
            title="平均处理时长"
            :value="statistics.avgProcessTime"
            suffix="天"
            value-style="color: #722ed1"
          />
          <div class="text-xs text-gray-400 mt-2">审批效率良好</div>
        </Card>
      </div>

      <!-- 报销单列表 -->
      <Card title="报销单列表">
        <template #extra>
          <Space>
            <Tooltip title="刷新数据">
              <Button @click="loadReimbursements" :loading="loading">
                <Icon icon="mdi:refresh" />
              </Button>
            </Tooltip>
            <Tooltip title="列设置">
              <Button @click="showColumnSetting = true">
                <Icon icon="mdi:cog" />
              </Button>
            </Tooltip>
          </Space>
        </template>

        <Table
          :columns="columns"
          :dataSource="filteredReimbursements"
          :loading="loading"
          :scroll="{ x: 1500 }"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }"
          :rowSelection="rowSelection"
          @change="handleTableChange"
        >
          <!-- 自定义列模板 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'reimbursementNo'">
              <a @click="viewDetail(record)" class="text-blue-600 hover:text-blue-800">
                {{ record.reimbursementNo }}
              </a>
            </template>

            <template v-else-if="column.dataIndex === 'amount'">
              <span class="font-semibold text-lg" :class="getAmountColor(record.amount)">
                ¥{{ formatNumber(record.amount) }}
              </span>
            </template>

            <template v-else-if="column.dataIndex === 'status'">
              <Tag :color="getStatusColor(record.status)">
                <Icon :icon="getStatusIcon(record.status)" class="mr-1" />
                {{ getStatusText(record.status) }}
              </Tag>
            </template>

            <template v-else-if="column.dataIndex === 'applicant'">
              <div class="flex items-center">
                <Avatar :size="32" :style="{ backgroundColor: getRandomColor(record.applicant) }">
                  {{ record.applicant.substring(0, 1) }}
                </Avatar>
                <div class="ml-2">
                  <div>{{ record.applicant }}</div>
                  <div class="text-xs text-gray-400">{{ record.department }}</div>
                </div>
              </div>
            </template>

            <template v-else-if="column.dataIndex === 'items'">
              <div class="text-xs">
                <div>{{ record.itemsCount }} 项费用</div>
                <div class="text-gray-400">{{ record.categories.join(', ') }}</div>
              </div>
            </template>

            <template v-else-if="column.dataIndex === 'progress'">
              <Tooltip :title="`${record.progress}% 完成`">
                <Progress
                  :percent="record.progress"
                  :status="record.status === 'rejected' ? 'exception' : 'normal'"
                  size="small"
                />
              </Tooltip>
            </template>

            <template v-else-if="column.dataIndex === 'approver'">
              <div class="text-sm">
                <div>{{ record.currentApprover || '-' }}</div>
                <div class="text-xs text-gray-400">{{ record.approvalStep || '-' }}</div>
              </div>
            </template>

            <template v-else-if="column.dataIndex === 'action'">
              <Space>
                <Tooltip title="查看详情">
                  <Button type="link" size="small" @click="viewDetail(record)">
                    <Icon icon="mdi:eye" />
                  </Button>
                </Tooltip>

                <Tooltip v-if="canEdit(record)" title="编辑">
                  <Button type="link" size="small" @click="editReimbursement(record)">
                    <Icon icon="mdi:pencil" />
                  </Button>
                </Tooltip>

                <Tooltip v-if="canApprove(record)" title="审批">
                  <Button type="link" size="small" @click="approveReimbursement(record)">
                    <Icon icon="mdi:check-circle" />
                  </Button>
                </Tooltip>

                <Dropdown :trigger="['click']">
                  <template #overlay>
                    <Menu @click="({ key }) => handleAction(key, record)">
                      <Menu.Item v-if="canSubmit(record)" key="submit">
                        <Icon icon="mdi:send" class="mr-2" />提交审批
                      </Menu.Item>
                      <Menu.Item v-if="canRevoke(record)" key="revoke">
                        <Icon icon="mdi:undo" class="mr-2" />撤回
                      </Menu.Item>
                      <Menu.Item key="export">
                        <Icon icon="mdi:download" class="mr-2" />导出
                      </Menu.Item>
                      <Menu.Item key="copy">
                        <Icon icon="mdi:content-copy" class="mr-2" />复制
                      </Menu.Item>
                      <Menu.Divider v-if="canDelete(record)" />
                      <Menu.Item v-if="canDelete(record)" key="delete" danger>
                        <Icon icon="mdi:delete" class="mr-2" />删除
                      </Menu.Item>
                    </Menu>
                  </template>
                  <Button type="link" size="small">
                    <Icon icon="mdi:dots-vertical" />
                  </Button>
                </Dropdown>
              </Space>
            </template>
          </template>
        </Table>
      </Card>

      <!-- 批量操作浮动按钮 -->
      <div v-if="selectedRowKeys.length > 0" class="fixed bottom-8 right-8 z-50">
        <Card class="shadow-2xl">
          <div class="flex items-center space-x-4">
            <span class="text-sm">已选择 <span class="font-bold text-blue-600">{{ selectedRowKeys.length }}</span> 项</span>
            <Button type="primary" @click="batchApprove" :disabled="!canBatchApprove">
              批量审批
            </Button>
            <Button @click="batchExport">批量导出</Button>
            <Button danger @click="batchDelete" :disabled="!canBatchDelete">批量删除</Button>
            <Button @click="selectedRowKeys = []">取消选择</Button>
          </div>
        </Card>
      </div>
    </PageWrapper>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { PageWrapper } from '@vben/common-ui';
import {
  Card, Table, Button, Input, Select, RangePicker, Space, Tag,
  Tooltip, Dropdown, Menu, Statistic, Progress, Avatar, Modal, message
} from 'ant-design-vue';
import { Icon } from '@iconify/vue';
import dayjs from 'dayjs';

defineOptions({ name: 'ReimbursementManagement' });

const router = useRouter();

// 状态管理
const searchText = ref('');
const filterStatus = ref('');
const filterDepartment = ref('');
const dateFilter = ref();
const quickFilter = ref('');
const loading = ref(false);
const showColumnSetting = ref(false);
const selectedRowKeys = ref<string[]>([]);

// 分页
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 部门列表
const departments = ref(['技术部', '市场部', '财务部', '人事部', '行政部', '销售部']);

// 统计数据
const statistics = ref({
  total: 156,
  myTotal: 23,
  pendingApproval: 8,
  approved: 98,
  monthTotal: 285690.50,
  pendingAmount: 45230.00,
  paidAmount: 240460.50,
  paid: 98,
  avgProcessTime: 2.5
});

// 报销单数据
const reimbursements = ref([
  {
    key: '1',
    reimbursementNo: 'RE202501001',
    applicant: '张三',
    department: '技术部',
    applyDate: '2025-01-08',
    amount: 3850.00,
    itemsCount: 5,
    categories: ['差旅', '餐饮'],
    reason: '客户现场技术支持差旅费',
    status: 'pending',
    progress: 50,
    currentApprover: '李经理',
    approvalStep: '部门经理审批',
    attachments: 3,
    createTime: '2025-01-08 09:30:00',
    updateTime: '2025-01-08 14:20:00'
  },
  {
    key: '2',
    reimbursementNo: 'RE202501002',
    applicant: '李四',
    department: '市场部',
    applyDate: '2025-01-07',
    amount: 12600.00,
    itemsCount: 8,
    categories: ['市场活动', '餐饮', '交通'],
    reason: '产品发布会活动费用',
    status: 'approved',
    progress: 100,
    currentApprover: '-',
    approvalStep: '已完成',
    attachments: 15,
    createTime: '2025-01-07 10:15:00',
    updateTime: '2025-01-08 16:40:00'
  },
  {
    key: '3',
    reimbursementNo: 'RE202501003',
    applicant: '王五',
    department: '技术部',
    applyDate: '2025-01-09',
    amount: 5200.00,
    itemsCount: 3,
    categories: ['办公用品', '设备'],
    reason: '团队办公设备采购',
    status: 'draft',
    progress: 0,
    currentApprover: '-',
    approvalStep: '未提交',
    attachments: 2,
    createTime: '2025-01-09 11:00:00',
    updateTime: '2025-01-09 11:00:00'
  },
  {
    key: '4',
    reimbursementNo: 'RE202501004',
    applicant: '赵六',
    department: '销售部',
    applyDate: '2025-01-06',
    amount: 8900.00,
    itemsCount: 6,
    categories: ['差旅', '住宿', '交通'],
    reason: '客户拜访及商务洽谈',
    status: 'paid',
    progress: 100,
    currentApprover: '-',
    approvalStep: '已支付',
    attachments: 8,
    createTime: '2025-01-06 08:45:00',
    updateTime: '2025-01-07 10:30:00'
  },
  {
    key: '5',
    reimbursementNo: 'RE202501005',
    applicant: '陈七',
    department: '市场部',
    applyDate: '2025-01-05',
    amount: 2800.00,
    itemsCount: 4,
    categories: ['餐饮', '礼品'],
    reason: '客户接待费用',
    status: 'rejected',
    progress: 30,
    currentApprover: '王总监',
    approvalStep: '财务审批已拒绝',
    attachments: 4,
    createTime: '2025-01-05 14:20:00',
    updateTime: '2025-01-05 17:10:00'
  }
]);

// 表格列配置
const columns = [
  {
    title: '报销单号',
    dataIndex: 'reimbursementNo',
    key: 'reimbursementNo',
    width: 140,
    fixed: 'left'
  },
  {
    title: '申请人',
    dataIndex: 'applicant',
    key: 'applicant',
    width: 150
  },
  {
    title: '申请日期',
    dataIndex: 'applyDate',
    key: 'applyDate',
    width: 110,
    sorter: true
  },
  {
    title: '报销金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 130,
    sorter: true
  },
  {
    title: '费用明细',
    dataIndex: 'items',
    key: 'items',
    width: 180
  },
  {
    title: '事由',
    dataIndex: 'reason',
    key: 'reason',
    ellipsis: true,
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 110,
    filters: [
      { text: '草稿', value: 'draft' },
      { text: '待审批', value: 'pending' },
      { text: '已通过', value: 'approved' },
      { text: '已拒绝', value: 'rejected' },
      { text: '已支付', value: 'paid' }
    ]
  },
  {
    title: '进度',
    dataIndex: 'progress',
    key: 'progress',
    width: 120
  },
  {
    title: '当前审批人',
    dataIndex: 'approver',
    key: 'approver',
    width: 130
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 过滤后的数据
const filteredReimbursements = computed(() => {
  let filtered = reimbursements.value;

  // 搜索过滤
  if (searchText.value) {
    const search = searchText.value.toLowerCase();
    filtered = filtered.filter(r =>
      r.reimbursementNo.toLowerCase().includes(search) ||
      r.applicant.toLowerCase().includes(search) ||
      r.reason.toLowerCase().includes(search)
    );
  }

  // 状态过滤
  if (filterStatus.value) {
    filtered = filtered.filter(r => r.status === filterStatus.value);
  }

  // 部门过滤
  if (filterDepartment.value) {
    filtered = filtered.filter(r => r.department === filterDepartment.value);
  }

  // 快捷过滤
  if (quickFilter.value === 'my') {
    // 模拟：只显示当前用户的报销单
    filtered = filtered.filter(r => r.applicant === '张三');
  } else if (quickFilter.value === 'pending') {
    filtered = filtered.filter(r => r.status === 'pending');
  } else if (quickFilter.value === 'approved') {
    filtered = filtered.filter(r => r.status === 'approved');
  }

  return filtered;
});

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys;
  }
};

// 权限判断
const canEdit = (record: any) => {
  return record.status === 'draft' || record.status === 'rejected';
};

const canApprove = (record: any) => {
  return record.status === 'pending';
};

const canSubmit = (record: any) => {
  return record.status === 'draft';
};

const canRevoke = (record: any) => {
  return record.status === 'pending';
};

const canDelete = (record: any) => {
  return record.status === 'draft' || record.status === 'rejected';
};

const canBatchApprove = computed(() => {
  return selectedRowKeys.value.some(key => {
    const record = reimbursements.value.find(r => r.key === key);
    return record && record.status === 'pending';
  });
});

const canBatchDelete = computed(() => {
  return selectedRowKeys.value.every(key => {
    const record = reimbursements.value.find(r => r.key === key);
    return record && (record.status === 'draft' || record.status === 'rejected');
  });
});

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

const getAmountColor = (amount: number) => {
  if (amount > 10000) return 'text-red-600';
  if (amount > 5000) return 'text-orange-600';
  return 'text-green-600';
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'draft': 'default',
    'pending': 'processing',
    'approved': 'success',
    'rejected': 'error',
    'paid': 'success',
    'cancelled': 'default'
  };
  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',
    'cancelled': 'mdi:cancel'
  };
  return iconMap[status] || 'mdi:help-circle';
};

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

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

// 事件处理
const onSearch = () => {
  pagination.value.current = 1;
  loadReimbursements();
};

const onFilterChange = () => {
  pagination.value.current = 1;
  loadReimbursements();
};

const onDateChange = () => {
  pagination.value.current = 1;
  loadReimbursements();
};

const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.value = pag;
  console.log('表格变化:', pag, filters, sorter);
};

const loadReimbursements = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    pagination.value.total = filteredReimbursements.value.length;
  }, 500);
};

const goToCreate = () => {
  router.push('/reimbursement/create');
};

const viewDetail = (record: any) => {
  router.push(`/reimbursement/detail/${record.key}`);
};

const editReimbursement = (record: any) => {
  router.push(`/reimbursement/create?id=${record.key}&mode=edit`);
};

const approveReimbursement = (record: any) => {
  router.push(`/reimbursement/detail/${record.key}?action=approve`);
};

const handleAction = (key: string, record: any) => {
  switch (key) {
    case 'submit':
      Modal.confirm({
        title: '确认提交审批',
        content: `是否确认提交报销单 ${record.reimbursementNo} 进行审批？`,
        onOk: () => {
          message.success('提交成功');
          loadReimbursements();
        }
      });
      break;
    case 'revoke':
      Modal.confirm({
        title: '确认撤回',
        content: `是否确认撤回报销单 ${record.reimbursementNo}？`,
        onOk: () => {
          message.success('撤回成功');
          loadReimbursements();
        }
      });
      break;
    case 'export':
      message.info('正在导出...');
      break;
    case 'copy':
      message.success('复制成功');
      break;
    case 'delete':
      Modal.confirm({
        title: '确认删除',
        content: `是否确认删除报销单 ${record.reimbursementNo}？此操作不可恢复。`,
        okType: 'danger',
        onOk: () => {
          message.success('删除成功');
          loadReimbursements();
        }
      });
      break;
  }
};

const handleExport = ({ key }: { key: string }) => {
  message.info(`正在导出${key}格式...`);
};

const batchApprove = () => {
  Modal.confirm({
    title: '批量审批',
    content: `是否确认批量审批选中的 ${selectedRowKeys.value.length} 个报销单？`,
    onOk: () => {
      message.success('批量审批成功');
      selectedRowKeys.value = [];
      loadReimbursements();
    }
  });
};

const batchExport = () => {
  message.info(`正在导出选中的 ${selectedRowKeys.value.length} 个报销单...`);
};

const batchDelete = () => {
  Modal.confirm({
    title: '批量删除',
    content: `是否确认删除选中的 ${selectedRowKeys.value.length} 个报销单？此操作不可恢复。`,
    okType: 'danger',
    onOk: () => {
      message.success('批量删除成功');
      selectedRowKeys.value = [];
      loadReimbursements();
    }
  });
};

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

<style scoped>
:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-statistic-content-value) {
  font-size: 24px;
  font-weight: 600;
}

.cursor-pointer {
  cursor: pointer;
}
</style>
