<template>
  <div class="travel-management">
    <a-page-header
      title="旅行管理"
      sub-title="管理用户发布的旅行信息"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('travel:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            发布旅行
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关键词">
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="目的地/用户昵称"
              allow-clear
            />
          </a-form-item>
          
          <a-form-item label="状态">
            <a-select
              v-model:value="searchForm.status"
              placeholder="全部状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="draft">草稿</a-select-option>
              <a-select-option value="published">已发布</a-select-option>
              <a-select-option value="archived">已归档</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="出行时间">
            <a-range-picker
              v-model:value="searchForm.travelTime"
              :placeholder="['开始时间', '结束时间']"
            />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 旅行表格 -->
      <a-table
        :columns="columns"
        :data-source="travelList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'actions'">
            <a-space :size="8">
              <a-button size="small" @click="handleView(record)">
                <EyeOutlined />
                查看
              </a-button>
              
              <a-button 
                v-if="hasPermission('travel:write')" 
                size="small" 
                @click="handleEdit(record)"
              >
                <EditOutlined />
                编辑
              </a-button>
              
              <template v-if="record.status === 'published' && hasPermission('travel:write')">
                <a-button size="small" danger @click="handleArchive(record)">
                  <FolderOpenOutlined />
                  归档
                </a-button>
              </template>
              
              <a-button 
                v-if="record.status !== 'published' && hasPermission('travel:write')" 
                size="small" 
                type="primary" 
                @click="handlePublish(record)"
              >
                <SendOutlined />
                发布
              </a-button>
              
              <a-button 
                v-if="hasPermission('travel:write')" 
                size="small" 
                danger 
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑旅行模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="travelFormRef"
        :model="currentTravel"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="目的地" name="destination">
          <a-input v-model:value="currentTravel.destination" placeholder="请输入目的地" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始日期" name="startDate">
              <a-date-picker
                v-model:value="currentTravel.startDate"
                format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束日期" name="endDate">
              <a-date-picker
                v-model:value="currentTravel.endDate"
                format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="预算(元)" name="budget">
          <a-input-number
            v-model:value="currentTravel.budget"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="人数" name="peopleCount">
          <a-input-number
            v-model:value="currentTravel.peopleCount"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-select v-model:value="currentTravel.status" placeholder="请选择状态">
            <a-select-option value="draft">草稿</a-select-option>
            <a-select-option value="published">已发布</a-select-option>
            <a-select-option value="archived">已归档</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="currentTravel.description"
            placeholder="请输入旅行描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  SendOutlined,
  FolderOpenOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { 
  getTravels, 
  getTravel, 
  createTravel, 
  updateTravel, 
  publishTravel, 
  archiveTravel, 
  deleteTravel 
} from '@/api/travel'
import type { Travel, TravelQueryParams } from '@/api/travel'

interface SearchForm {
  keyword: string
  status: string
  travelTime: any[]
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const loading = ref(false)
const searchForm = reactive<SearchForm>({
  keyword: '',
  status: '',
  travelTime: []
})

const travelList = ref<Travel[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '目的地',
    dataIndex: 'destination',
    key: 'destination',
    width: 150
  },
  {
    title: '用户',
    dataIndex: 'userName',
    key: 'userName',
    width: 100
  },
  {
    title: '出行时间',
    key: 'travelTime',
    width: 200,
    customRender: ({ record }: { record: Travel }) => 
      `${record.startDate} 至 ${record.endDate}`
  },
  {
    title: '预算',
    dataIndex: 'budget',
    key: 'budget',
    width: 100,
    align: 'right',
    customRender: ({ text }: { text: number }) => `¥${text}`
  },
  {
    title: '人数',
    dataIndex: 'peopleCount',
    key: 'peopleCount',
    width: 80,
    align: 'center'
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '发布时间',
    dataIndex: 'publishedAt',
    key: 'publishedAt',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 250,
    align: 'center'
  }
]

// 状态映射
const getStatusColor = (status: string) => {
  const colors = {
    draft: 'orange',
    published: 'green',
    archived: 'blue'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return texts[status as keyof typeof texts] || '未知'
}

// 添加模态框相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('发布旅行')
const isEditing = ref(false)
const travelFormRef = ref<FormInstance>()

// 当前旅行数据
const currentTravel = ref<Partial<Travel>>({})

// 表单验证规则
const formRules = {
  destination: [
    { required: true, message: '请输入目的地' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期' }
  ],
  budget: [
    { required: true, message: '请输入预算' }
  ],
  peopleCount: [
    { required: true, message: '请输入人数' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
}

// 生命周期
onMounted(() => {
  loadTravels()
})

// 方法
const loadTravels = async () => {
  loading.value = true
  try {
    const params: TravelQueryParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    const response = await getTravels(params)
    travelList.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    message.error('加载旅行列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadTravels()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    travelTime: []
  })
  pagination.current = 1
  loadTravels()
}

const handleRefresh = () => {
  loadTravels()
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadTravels()
}

const handleView = async (record: Travel) => {
  try {
    const response = await getTravel(record.id)
    Modal.info({
      title: '旅行详情',
      width: 600,
      content: h('div', { class: 'travel-detail-modal' }, [
        h('a-descriptions', {
          column: 1,
          bordered: true
        }, [
          h('a-descriptions-item', { label: '目的地' }, response.data.destination),
          h('a-descriptions-item', { label: '用户' }, response.data.userName),
          h('a-descriptions-item', { label: '出行时间' }, 
            `${response.data.startDate} 至 ${response.data.endDate}`),
          h('a-descriptions-item', { label: '预算' }, `¥${response.data.budget}`),
          h('a-descriptions-item', { label: '人数' }, response.data.peopleCount),
          h('a-descriptions-item', { label: '状态' }, [
            h('a-tag', { color: getStatusColor(response.data.status) }, getStatusText(response.data.status))
          ]),
          h('a-descriptions-item', { label: '发布时间' }, response.data.publishedAt || '-'),
          h('a-descriptions-item', { label: '描述' }, response.data.description || '-')
        ])
      ]),
      okText: '关闭'
    })
  } catch (error) {
    message.error('获取旅行详情失败')
  }
}

const handleEdit = async (record: Travel) => {
  try {
    modalLoading.value = true
    const response = await getTravel(record.id)
    modalTitle.value = '编辑旅行'
    isEditing.value = true
    currentTravel.value = response.data
    modalVisible.value = true
  } catch (error) {
    message.error('获取旅行详情失败')
  } finally {
    modalLoading.value = false
  }
}

const showCreateModal = () => {
  modalTitle.value = '发布旅行'
  isEditing.value = false
  currentTravel.value = {
    budget: 0,
    peopleCount: 1,
    status: 'draft'
  }
  modalVisible.value = true
}

const handleModalOk = () => {
  travelFormRef.value
    ?.validate()
    .then(() => {
      if (isEditing.value) {
        handleUpdateTravel()
      } else {
        handleCreateTravel()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

const handleModalCancel = () => {
  modalVisible.value = false
  travelFormRef.value?.resetFields()
}

const handleCreateTravel = async () => {
  try {
    modalLoading.value = true
    await createTravel(currentTravel.value as any)
    message.success('创建旅行成功')
    modalVisible.value = false
    loadTravels()
  } catch (error) {
    message.error('创建旅行失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdateTravel = async () => {
  try {
    modalLoading.value = true
    await updateTravel(currentTravel.value.id!, currentTravel.value as any)
    message.success('更新旅行成功')
    modalVisible.value = false
    loadTravels()
  } catch (error) {
    message.error('更新旅行失败')
  } finally {
    modalLoading.value = false
  }
}

const handlePublish = async (record: Travel) => {
  Modal.confirm({
    title: '确认发布',
    content: `确定要发布旅行 "${record.destination}" 吗？`,
    onOk: async () => {
      try {
        await publishTravel(record.id)
        message.success('旅行已发布')
        loadTravels()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleArchive = async (record: Travel) => {
  Modal.confirm({
    title: '确认归档',
    content: `确定要归档旅行 "${record.destination}" 吗？`,
    onOk: async () => {
      try {
        await archiveTravel(record.id)
        message.success('旅行已归档')
        loadTravels()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleDelete = async (record: Travel) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除旅行 "${record.destination}" 吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        await deleteTravel(record.id)
        message.success('旅行已删除')
        loadTravels()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}
</script>

<style scoped lang="less">
.travel-management {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}

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