<template>
  <div class="app-list-container">
    <div class="header">
      <h2>客户端分发</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索分发名称"
          style="width: 250px; margin-right: 10px;"
          clearable
          @clear="fetchList"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <el-button type="primary" @click="openCreateDialog">创建分发</el-button>
      </div>
    </div>

    <el-table :data="items" v-loading="loading" style="width: 100%" stripe border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分发名称" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" link @click="goDetail(scope.row)">进入</el-button>
            <el-divider direction="vertical" />
            <el-button type="primary" link @click="copyShareUrl(scope.row.share_id)">分享</el-button>
            <el-divider direction="vertical" />
            <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchList"
        @current-change="fetchList"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑分发' : '创建分发'" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="分发名称" required>
          <el-input v-model="form.name" placeholder="如：iOS App / Android App" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="选填" />
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            :auto-upload="false"
            :limit="1"
            :on-change="onIconChange"
            :on-remove="onIconRemove"
            :file-list="iconFileList"
            accept="image/png,image/jpeg,image/gif,image/webp"
          >
            <el-button type="primary">选择图标</el-button>
            <template #tip>
              <span class="tip">支持 PNG、JPG、GIF、WebP，最大 2MB</span>
            </template>
          </el-upload>
          <img v-if="form.iconPreview" :src="form.iconPreview" class="icon-preview" alt="" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listDistributions,
  createDistribution,
  updateDistribution,
  deleteDistribution,
  uploadDistributionIcon,
  ClientDistribution
} from '../../api/clientDistributions'

const router = useRouter()
const items = ref<ClientDistribution[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const editId = ref<number | null>(null)

const form = ref({
  name: '',
  description: '',
  icon_url: '',
  iconPreview: '' as string
})
const iconFileList = ref<any[]>([])
const iconUploading = ref(false)

const shareUrl = (shareId: string) => `${window.location.origin}/d/${encodeURIComponent(shareId)}`

const copyShareUrl = async (shareId: string) => {
  const url = shareUrl(shareId)
  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('已复制下载页面链接')
  } catch {
    ElMessage.error('复制失败')
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await listDistributions({
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      search: searchQuery.value || undefined
    })
    items.value = res.data.items
    total.value = res.data.total
  } catch {
    items.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => fetchList()

const openCreateDialog = () => {
  isEdit.value = false
  editId.value = null
  form.value = { name: '', description: '', icon_url: '', iconPreview: '' }
  iconFileList.value = []
  dialogVisible.value = true
}

const openEditDialog = (row: ClientDistribution) => {
  isEdit.value = true
  editId.value = row.id
  form.value = {
    name: row.name,
    description: row.description || '',
    icon_url: row.icon_object_key || '',
    iconPreview: row.icon_url || ''
  }
  iconFileList.value = row.icon_url ? [{ name: '当前图标', uid: 'current' }] : []
  dialogVisible.value = true
}

const onIconChange = async (file: any) => {
  const raw = file.raw
  if (!raw) return
  if (raw.size > 2 * 1024 * 1024) {
    ElMessage.warning('图标大小不能超过 2MB')
    return
  }
  iconUploading.value = true
  try {
    const res = await uploadDistributionIcon(raw, editId.value || 0)
    form.value.icon_url = res.data.object_key
    form.value.iconPreview = URL.createObjectURL(raw)
    iconFileList.value = [{ name: raw.name, uid: file.uid }]
  } catch {
    iconFileList.value = []
  } finally {
    iconUploading.value = false
  }
}

const onIconRemove = () => {
  form.value.icon_url = ''
  form.value.iconPreview = ''
  iconFileList.value = []
}

const handleSubmit = async () => {
  if (!form.value.name.trim()) {
    ElMessage.warning('请输入分发名称')
    return
  }
  submitting.value = true
  try {
    const payload: Record<string, unknown> = {
      name: form.value.name,
      description: form.value.description || undefined
    }
    if (form.value.icon_url !== undefined) {
      payload.icon_url = form.value.icon_url
    }
    if (isEdit.value && editId.value) {
      await updateDistribution(editId.value, payload)
      ElMessage.success('更新成功')
    } else {
      await createDistribution(payload)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row: ClientDistribution) => {
  await ElMessageBox.confirm(`确定删除「${row.name}」？删除后分享链接将失效。`, '确认删除', {
    type: 'warning'
  })
  try {
    await deleteDistribution(row.id)
    ElMessage.success('已删除')
    fetchList()
  } catch {}
}

const goDetail = (row: ClientDistribution) => {
  router.push(`/dashboard/client-distributions/${row.id}`)
}

onMounted(fetchList)
</script>

<style scoped>
.app-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.header h2 {
  margin: 0;
}
.header-actions {
  display: flex;
  align-items: center;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.tip {
  font-size: 12px;
  color: #999;
}
.icon-preview {
  margin-top: 8px;
  width: 64px;
  height: 64px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}
</style>
