<template>
  <div class="home-content-container">
    <el-tabs v-model="activeTab">
      <!-- Banner管理 -->
      <el-tab-pane label="Banner管理" name="banners">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>Banner列表</span>
              <el-button type="primary" size="small" @click="handleCreateBanner">
                <el-icon><Plus /></el-icon>
                新增Banner
              </el-button>
            </div>
          </template>
          <el-table :data="banners" v-loading="loading.banners" stripe>
            <el-table-column label="图片" width="150">
              <template #default="{ row }">
                <el-image :src="getImageUrl(row.image_url)" style="width: 120px; height: 60px" fit="cover">
                  <template #error>
                    <div class="image-error">图片丢失</div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="link_url" label="链接" show-overflow-tooltip />
            <el-table-column prop="sort_order" label="排序" width="80" align="center" />
            <el-table-column prop="is_active" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
                  {{ row.is_active ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handleEditBanner(row)">编辑</el-button>
                <el-button type="danger" link size="small" @click="handleDeleteBanner(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 热门服务管理 -->
      <el-tab-pane label="热门服务" name="hotServices">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门服务列表</span>
              <el-button type="primary" size="small" @click="handleCreateHotService">
                <el-icon><Plus /></el-icon>
                新增热门服务
              </el-button>
            </div>
          </template>
          <el-table :data="hotServices" v-loading="loading.hotServices" stripe>
            <el-table-column label="列表图" width="100">
              <template #default="{ row }">
                <el-image v-if="row.image_url" :src="getImageUrl(row.image_url)" style="width: 60px; height: 60px" fit="cover">
                  <template #error>
                    <div class="image-error-small">丢失</div>
                  </template>
                </el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="详情图" width="100">
              <template #default="{ row }">
                <el-image v-if="row.detail_image" :src="getImageUrl(row.detail_image)" style="width: 60px; height: 60px" fit="cover">
                  <template #error>
                    <div class="image-error-small">丢失</div>
                  </template>
                </el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="name_zh" label="中文名称" min-width="120" />
            <el-table-column prop="name_en" label="英文名称" min-width="120" />
            <el-table-column prop="name_pt" label="西语名称" min-width="120" />
            <el-table-column label="服务类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getServiceTypeTag(row.service_type)" size="small">
                  {{ getServiceTypeLabel(row.service_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sort_order" label="排序" width="80" align="center" />
            <el-table-column prop="is_active" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
                  {{ row.is_active ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handleEditHotService(row)">编辑</el-button>
                <el-button type="danger" link size="small" @click="handleDeleteHotService(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- Banner编辑弹窗 -->
    <el-dialog v-model="bannerDialog.visible" :title="bannerDialog.isEdit ? '编辑Banner' : '新增Banner'" width="500px">
      <el-form :model="bannerForm" label-width="100px">
        <el-form-item label="图片" required>
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, 'banner')"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            name="file"
            accept="image/*">
            <el-image v-if="bannerForm.image_url" :src="getImageUrl(bannerForm.image_url)" style="width: 200px; height: 100px" fit="cover" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="bannerForm.link_url" placeholder="点击跳转链接" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="bannerForm.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="bannerForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bannerDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveBanner" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 热门服务编辑弹窗 -->
    <el-dialog v-model="hotServiceDialog.visible" :title="hotServiceDialog.isEdit ? '编辑热门服务' : '新增热门服务'" width="600px">
      <el-form :model="hotServiceForm" label-width="100px">
        <el-form-item label="中文名称" required>
          <el-input v-model="hotServiceForm.name_zh" placeholder="请输入中文名称" />
        </el-form-item>
        <el-form-item label="英文名称" required>
          <el-input v-model="hotServiceForm.name_en" placeholder="Please enter English name" />
        </el-form-item>
        <el-form-item label="西语名称" required>
          <el-input v-model="hotServiceForm.name_pt" placeholder="Por favor, ingrese el nombre" />
        </el-form-item>
        <el-form-item label="服务类型" required>
          <el-select v-model="hotServiceForm.service_type" placeholder="请选择服务类型" filterable style="width: 100%">
            <el-option v-for="item in serviceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <div class="form-tip">用于跳转对应的预约表单页面</div>
        </el-form-item>
        <el-form-item label="列表图">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, 'hotService')"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            name="file"
            accept="image/*">
            <el-image v-if="hotServiceForm.image_url" :src="getImageUrl(hotServiceForm.image_url)" style="width: 100px; height: 100px" fit="cover" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">首页列表显示的图片</div>
        </el-form-item>
        <el-form-item label="详情图">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, 'hotServiceDetail')"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            name="file"
            accept="image/*">
            <el-image v-if="hotServiceForm.detail_image" :src="getImageUrl(hotServiceForm.detail_image)" style="width: 100px; height: 100px" fit="cover" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">详情页显示的图片</div>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="hotServiceForm.link_url" placeholder="点击跳转链接" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="hotServiceForm.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="hotServiceForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="hotServiceDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveHotService" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

const activeTab = ref('hotServices')
const saving = ref(false)
const loading = reactive({ banners: false, hotServices: false })

const banners = ref([])
const hotServices = ref([])

const bannerDialog = reactive({ visible: false, isEdit: false })
const bannerForm = reactive({ id: null, image_url: '', link_url: '', sort_order: 0, is_active: true })

const hotServiceDialog = reactive({ visible: false, isEdit: false })
const hotServiceForm = reactive({
  id: null, name_zh: '', name_en: '', name_pt: '', service_type: 'flight',
  image_url: '', detail_image: '', link_url: '', sort_order: 0, is_active: true
})

const serviceTypeOptions = [
  { value: 'flight', label: '全球机票代理' },
  { value: 'hotel', label: '全球酒店预定' },
  { value: 'lounge', label: '全球机场贵宾室服务' },
  { value: 'airport_transfer', label: '机场接/送机服务' },
  { value: 'unaccompanied_minor', label: '无成人陪伴儿童代办' },
  { value: 'train', label: '高铁票代订' },
  { value: 'telemedicine', label: '远程医疗问诊代理服务' },
  { value: 'special_passenger', label: '特殊（特护）旅客定制服务代办' },
  { value: 'pet_transport', label: '宠物托运代理' },
  { value: 'guide_translation', label: '西班牙语专业导游/翻译服务' },
  { value: 'visa', label: '签证咨询' },
  { value: 'exhibition', label: '墨西哥展会咨询与协办服务' },
  { value: 'air_logistics', label: '跨境航空物流/快递一站式服务' },
  { value: 'sea_freight', label: '海运/清关一站式服务' },
  { value: 'travel_planning', label: '旅游线路规划/咨询' },
  { value: 'insurance', label: '跨境出行意外保险/国际财产保险咨询' }
]

function getServiceTypeLabel(type) {
  const item = serviceTypeOptions.find(t => t.value === type)
  return item ? item.label : '未知'
}

function getServiceTypeTag(type) {
  const tagMap = { 
    flight: 'primary', hotel: 'success', lounge: 'warning', airport_transfer: 'info',
    unaccompanied_minor: 'danger', train: 'primary', telemedicine: 'success',
    special_passenger: 'warning', pet_transport: 'info', guide_translation: 'danger',
    visa: 'primary', exhibition: 'success', air_logistics: 'warning',
    sea_freight: 'info', travel_planning: 'danger', insurance: 'primary'
  }
  return tagMap[type] || ''
}

const uploadUrl = computed(() => '/api/v1/admin/upload/image')
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('admin_token')
  return token ? { Authorization: `Bearer ${token}` } : {}
})

function getImageUrl(path) {
  if (!path) return ''
  if (path.startsWith('http')) return path
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  return `${baseUrl}${path}`
}

function beforeUpload(file) {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isImage) { ElMessage.error('只能上传图片文件!'); return false }
  if (!isLt5M) { ElMessage.error('图片大小不能超过5MB!'); return false }
  return true
}

function handleUploadSuccess(response, type) {
  if (response.code === 0 || response.success) {
    if (type === 'banner') bannerForm.image_url = response.data.url
    else if (type === 'hotService') hotServiceForm.image_url = response.data.url
    else if (type === 'hotServiceDetail') hotServiceForm.detail_image = response.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

function handleUploadError(error) {
  console.error('Upload error:', error)
  ElMessage.error('图片上传失败，请重试')
}

async function fetchBanners() {
  loading.banners = true
  try {
    const res = await api.get('/api/v1/admin/home/banners')
    if (res.data.code === 0) banners.value = res.data.data
  } catch (e) { ElMessage.error('获取Banner失败') }
  finally { loading.banners = false }
}

async function fetchHotServices() {
  loading.hotServices = true
  try {
    const res = await api.get('/api/v1/admin/home/hot-services')
    if (res.data.code === 0) hotServices.value = res.data.data
  } catch (e) { ElMessage.error('获取热门服务失败') }
  finally { loading.hotServices = false }
}

function handleCreateBanner() {
  Object.assign(bannerForm, { id: null, image_url: '', link_url: '', sort_order: 0, is_active: true })
  bannerDialog.isEdit = false
  bannerDialog.visible = true
}

function handleEditBanner(row) {
  Object.assign(bannerForm, row)
  bannerDialog.isEdit = true
  bannerDialog.visible = true
}

async function saveBanner() {
  if (!bannerForm.image_url) { ElMessage.error('请上传图片'); return }
  saving.value = true
  try {
    if (bannerDialog.isEdit) {
      await api.put(`/api/v1/admin/home/banners/${bannerForm.id}`, bannerForm)
    } else {
      await api.post('/api/v1/admin/home/banners', bannerForm)
    }
    ElMessage.success('保存成功')
    bannerDialog.visible = false
    fetchBanners()
  } catch (e) { ElMessage.error('保存失败') }
  finally { saving.value = false }
}

async function handleDeleteBanner(row) {
  await ElMessageBox.confirm('确定删除此Banner?', '提示', { type: 'warning' })
  try {
    await api.delete(`/api/v1/admin/home/banners/${row.id}`)
    ElMessage.success('删除成功')
    fetchBanners()
  } catch (e) { ElMessage.error('删除失败') }
}

function handleCreateHotService() {
  Object.assign(hotServiceForm, {
    id: null, name_zh: '', name_en: '', name_pt: '', service_type: 'flight',
    image_url: '', detail_image: '', link_url: '', sort_order: 0, is_active: true
  })
  hotServiceDialog.isEdit = false
  hotServiceDialog.visible = true
}

function handleEditHotService(row) {
  Object.assign(hotServiceForm, row)
  hotServiceDialog.isEdit = true
  hotServiceDialog.visible = true
}

async function saveHotService() {
  if (!hotServiceForm.name_zh || !hotServiceForm.name_en || !hotServiceForm.name_pt) {
    ElMessage.error('请填写所有语言的名称')
    return
  }
  saving.value = true
  try {
    if (hotServiceDialog.isEdit) {
      await api.put(`/api/v1/admin/home/hot-services/${hotServiceForm.id}`, hotServiceForm)
    } else {
      await api.post('/api/v1/admin/home/hot-services', hotServiceForm)
    }
    ElMessage.success('保存成功')
    hotServiceDialog.visible = false
    fetchHotServices()
  } catch (e) { ElMessage.error('保存失败') }
  finally { saving.value = false }
}

async function handleDeleteHotService(row) {
  await ElMessageBox.confirm('确定删除此热门服务?', '提示', { type: 'warning' })
  try {
    await api.delete(`/api/v1/admin/home/hot-services/${row.id}`)
    ElMessage.success('删除成功')
    fetchHotServices()
  } catch (e) { ElMessage.error('删除失败') }
}

onMounted(() => {
  fetchBanners()
  fetchHotServices()
})
</script>

<style lang="scss" scoped>
.home-content-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .image-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      &:hover { border-color: #409eff; }
    }
    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .upload-tip, .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
  .image-error {
    width: 120px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    color: #909399;
    font-size: 12px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
  }
  .image-error-small {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    color: #909399;
    font-size: 12px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
  }
}
</style>
