<template>
  <div class="big-screen-page">
    <a-row :gutter="16" class="summary-row">
      <a-col :xs="24" :sm="12" :lg="6" v-for="item in summaryItems" :key="item.label">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">{{ item.label }}</div>
          <div class="summary-value">{{ item.value }}</div>
        </a-card>
      </a-col>
    </a-row>

    <a-card :bordered="false" class="panel-card">
      <template #title>大屏管理</template>
      <template #extra>
        <a-space>
          <a-input-search v-model="keyword" allow-clear placeholder="搜索名称或说明" @search="loadScreens" />
          <a-button type="primary" :disabled="!canOperate" @click="openCreateScreen">
            <template #icon><icon-plus /></template>
            新建大屏
          </a-button>
          <a-button :loading="loading" :disabled="pageUnauthorized" @click="loadAll">
            <template #icon><icon-refresh /></template>
          </a-button>
        </a-space>
      </template>

      <PageState :status="pageStatus" :error-text="errorMessage" :partial-text="partialMessage" @retry="loadAll">
      <a-table
        v-if="pageStatus !== 'empty' && pageStatus !== 'error' && pageStatus !== 'unauthorized'"
        row-key="id"
        :loading="loading"
        :data="screens"
        :pagination="pagination"
        :scroll="{ x: 'max-content' }"
        @page-change="handlePageChange"
      >
        <template #columns>
          <a-table-column title="名称" data-index="name" :width="220">
            <template #cell="{ record }">
              <a-space direction="vertical" :size="2">
                <strong>{{ record.name }}</strong>
                <span class="muted">{{ record.goview_project_id || '未绑定 GoView' }}</span>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="分组" data-index="group_id" :width="140">
            <template #cell="{ record }">{{ groupName(record.group_id) }}</template>
          </a-table-column>
          <a-table-column title="画布" :width="120">
            <template #cell="{ record }">{{ record.width }} x {{ record.height }}</template>
          </a-table-column>
          <a-table-column title="发布状态" data-index="publish_status" :width="130">
            <template #cell="{ record }">
              <a-tag :color="publishStatusColor(record.publish_status)">
                {{ publishStatusText(record.publish_status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="公开" data-index="is_public" :width="90">
            <template #cell="{ record }">
              <a-tag :color="record.is_public ? 'green' : 'gray'">
                {{ record.is_public ? '公开' : '受限' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建人" data-index="creator_name" :width="120" />
          <a-table-column title="操作" :width="220" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" :disabled="!canOperate" @click="openEditScreen(record)">编辑</a-button>
                <a-button type="text" size="small" :disabled="!canOperate" @click="handlePublish(record)">发布</a-button>
                <a-button type="text" size="small" :disabled="pageUnauthorized" @click="selectScreen(record)">快照</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      </PageState>
    </a-card>

    <a-row :gutter="16" class="ops-row">
      <a-col :xs="24" :lg="8">
        <a-card :bordered="false" class="panel-card">
          <template #title>分组</template>
          <template #extra>
            <a-button size="small" :disabled="!canOperate" @click="createDefaultGroup">新增</a-button>
          </template>
          <a-list :data="groups" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta :title="item.name" :description="item.description || '无描述'" />
                <a-tag>{{ item.sort_order }}</a-tag>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8">
        <a-card :bordered="false" class="panel-card">
          <template #title>轮播</template>
          <template #extra>
            <a-button size="small" :disabled="!canOperate" @click="createDefaultCarousel">新增</a-button>
          </template>
          <a-list :data="carousels" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta :title="item.name" :description="`${item.interval_seconds || 30}s`" />
                <a-switch :model-value="item.enabled" disabled />
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8">
        <a-card :bordered="false" class="panel-card">
          <template #title>快照导出</template>
          <template #extra>
            <a-button size="small" :disabled="!currentScreen || !canOperate" @click="createSnapshotRecord">记录</a-button>
          </template>
          <a-empty v-if="snapshots.length === 0" />
          <a-list v-else :data="snapshots" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta :title="item.file_name" :description="item.file_path" />
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>

    <a-modal
      v-model:visible="screenModalVisible"
      :title="editingScreen ? '编辑大屏' : '新建大屏'"
      :ok-loading="saving"
      @ok="saveScreen"
    >
      <a-form :model="screenForm" layout="vertical">
        <a-form-item label="名称" field="name" required>
          <a-input v-model="screenForm.name" />
        </a-form-item>
        <a-form-item label="GoView 项目 ID" field="goview_project_id" required>
          <a-input v-model="screenForm.goview_project_id" />
        </a-form-item>
        <a-row :gutter="12">
          <a-col :span="12">
            <a-form-item label="分组">
              <a-select v-model="screenForm.group_id" allow-clear>
                <a-option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="公开读取">
              <a-switch v-model="screenForm.is_public" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="12">
          <a-col :span="12">
            <a-form-item label="宽度">
              <a-input-number v-model="screenForm.width" :min="100" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="高度">
              <a-input-number v-model="screenForm.height" :min="100" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="说明">
          <a-textarea v-model="screenForm.description" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  createBigScreen,
  createBigScreenCarousel,
  createBigScreenGroup,
  createBigScreenSnapshot,
  fetchBigScreenCarousels,
  fetchBigScreenGroups,
  fetchBigScreenSnapshots,
  fetchBigScreens,
  publishBigScreen,
  updateBigScreen,
  type BigScreen,
  type BigScreenCarousel,
  type BigScreenGroup,
  type BigScreenSnapshot,
} from '@/api/ops/bigScreen'

const loading = ref(false)
const saving = ref(false)
const errorMessage = ref('')
const partialMessage = ref('')
const pageUnauthorized = ref(false)
const keyword = ref('')
const screens = ref<BigScreen[]>([])
const groups = ref<BigScreenGroup[]>([])
const carousels = ref<BigScreenCarousel[]>([])
const snapshots = ref<BigScreenSnapshot[]>([])
const currentScreen = ref<BigScreen | null>(null)
const editingScreen = ref<BigScreen | null>(null)
const screenModalVisible = ref(false)

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
})

const screenForm = reactive<Partial<BigScreen>>({
  name: '',
  description: '',
  group_id: undefined,
  goview_project_id: '',
  width: 1920,
  height: 1080,
  status: 1,
  is_public: false,
})

const summaryItems = computed(() => [
  { label: '大屏总数', value: pagination.total },
  { label: '已发布', value: screens.value.filter((item) => item.publish_status === 'published').length },
  { label: '分组', value: groups.value.length },
  { label: '轮播', value: carousels.value.length },
])

const canOperate = computed(() => !pageUnauthorized.value && !loading.value)

const pageStatus = computed(() => {
  if (pageUnauthorized.value) return 'unauthorized'
  if (loading.value) return 'loading'
  if (errorMessage.value && !screens.value.length) return 'error'
  if (partialMessage.value) return 'partial'
  if (!screens.value.length) return 'empty'
  return 'success'
})

const isForbidden = (error: any) => error?.response?.status === 403 || error?.code === 403 || error?.code === 401

const setLoadError = (error: any, fallback: string) => {
  if (isForbidden(error)) {
    pageUnauthorized.value = true
    errorMessage.value = '当前账号没有访问大屏管理的权限。'
    return
  }
  errorMessage.value = error?.message || fallback
}

const responseData = <T,>(res: { data?: T; details?: T }): T | undefined => res.data ?? res.details

const loadScreens = async () => {
  loading.value = true
  errorMessage.value = ''
  pageUnauthorized.value = false
  try {
    const res = await fetchBigScreens({
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: keyword.value || undefined,
    })
    const page = responseData(res)
    screens.value = page?.data || []
    pagination.total = page?.total || 0
  } catch (error: any) {
    setLoadError(error, '加载大屏失败')
    Message.error(error.message || '加载大屏失败')
  } finally {
    loading.value = false
  }
}

const loadGroups = async () => {
  const res = await fetchBigScreenGroups()
  groups.value = responseData(res) || []
}

const loadCarousels = async () => {
  const res = await fetchBigScreenCarousels()
  carousels.value = responseData(res) || []
}

const loadSnapshots = async () => {
  const res = await fetchBigScreenSnapshots(currentScreen.value ? { screen_id: currentScreen.value.id } : undefined)
  snapshots.value = responseData(res) || []
}

const loadAll = async () => {
  partialMessage.value = ''
  const results = await Promise.allSettled([loadScreens(), loadGroups(), loadCarousels(), loadSnapshots()])
  if (results.some((item) => item.status === 'rejected')) {
    partialMessage.value = '分组、轮播或快照数据部分加载失败，主列表仍可使用。'
  }
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadScreens()
}

const groupName = (id?: number) => groups.value.find((group) => group.id === id)?.name || '未分组'

const publishStatusText = (status?: string) => {
  const map: Record<string, string> = { draft: '草稿', published: '已发布', offline: '已下线' }
  return map[status || 'draft'] || status || '草稿'
}

const publishStatusColor = (status?: string) => {
  const map: Record<string, string> = { draft: 'gray', published: 'green', offline: 'orange' }
  return map[status || 'draft'] || 'blue'
}

const resetScreenForm = () => {
  screenForm.name = ''
  screenForm.description = ''
  screenForm.group_id = undefined
  screenForm.goview_project_id = ''
  screenForm.width = 1920
  screenForm.height = 1080
  screenForm.status = 1
  screenForm.is_public = false
}

const openCreateScreen = () => {
  editingScreen.value = null
  resetScreenForm()
  screenModalVisible.value = true
}

const openEditScreen = (screen: BigScreen) => {
  editingScreen.value = screen
  Object.assign(screenForm, screen)
  screenModalVisible.value = true
}

const saveScreen = async () => {
  if (!screenForm.name || !screenForm.goview_project_id) {
    Message.warning('请填写名称和 GoView 项目 ID')
    return
  }
  saving.value = true
  try {
    if (editingScreen.value) {
      await updateBigScreen(editingScreen.value.id, screenForm)
    } else {
      await createBigScreen(screenForm)
    }
    Message.success('保存成功')
    screenModalVisible.value = false
    loadScreens()
  } catch (error: any) {
    Message.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handlePublish = async (screen: BigScreen) => {
  if (!screen.goview_project_id) {
    Message.warning('请先绑定 GoView 项目 ID')
    return
  }
  await publishBigScreen({ screen_id: screen.id, publish_type: 1, change_log: 'OPS 大屏管理发布' })
  Message.success('发布成功')
  loadScreens()
}

const selectScreen = (screen: BigScreen) => {
  currentScreen.value = screen
  loadSnapshots()
}

const createDefaultGroup = async () => {
  await createBigScreenGroup({ name: `大屏分组 ${groups.value.length + 1}`, sort_order: groups.value.length + 1, status: 1 })
  Message.success('分组已创建')
  loadGroups()
}

const createDefaultCarousel = async () => {
  await createBigScreenCarousel({
    name: `轮播 ${carousels.value.length + 1}`,
    interval_seconds: 30,
    enabled: true,
    screen_ids: { ids: screens.value.slice(0, 5).map((item) => item.id) },
  })
  Message.success('轮播已创建')
  loadCarousels()
}

const createSnapshotRecord = async () => {
  if (!currentScreen.value) return
  await createBigScreenSnapshot({
    screen_id: currentScreen.value.id,
    file_name: `${currentScreen.value.name}.png`,
    file_path: `/artifacts/big-screen/${currentScreen.value.id}.png`,
    file_size: 0,
  })
  Message.success('快照元数据已记录')
  loadSnapshots()
}

loadAll()
</script>

<script lang="ts">
export default {
  name: 'OpsBigScreen',
}
</script>

<style scoped lang="less">
.big-screen-page {
  padding: 16px 20px 24px;
}

.summary-row,
.ops-row {
  margin-bottom: 16px;
}

.summary-card {
  min-height: 96px;
}

.summary-label {
  color: var(--color-text-2);
  font-size: 13px;
}

.summary-value {
  margin-top: 12px;
  font-size: 28px;
  line-height: 1;
  font-weight: 600;
}

.panel-card {
  margin-bottom: 16px;
  border-radius: 6px;
}

.muted {
  color: var(--color-text-3);
  font-size: 12px;
}

@media (max-width: 768px) {
  .big-screen-page {
    padding: 12px;
  }

  :deep(.arco-card-header) {
    flex-wrap: wrap;
    gap: 8px;
  }

  :deep(.arco-card-extra) {
    width: 100%;
  }

  :deep(.arco-card-extra .arco-space) {
    width: 100%;
    flex-wrap: wrap;
    justify-content: flex-start;
  }

  :deep(.arco-input-search) {
    width: 100%;
  }
}
</style>
