<template>
  <div class="page sync-page">
    <section class="page-hero sync-hero">
      <div>
        <h1>同步管理</h1>
        <p>按平台选择同步资产或近期开启报警同步。高邮支持资产同步，汉源支持资产与报警同步。</p>
      </div>
      <div class="sync-summary">
        <span>已选平台 {{ selectedBaseUrls.length }}</span>
        <span>报警近 {{ faultDays }} 天</span>
      </div>
    </section>

    <el-card class="modern-card" shadow="never">
      <template #header>
        <div class="section-title">
          <span>选择平台</span>
          <small>平台地址</small>
        </div>
      </template>
      <div class="platform-grid">
        <button
          v-for="platform in platforms"
          :key="platform.baseUrl"
          class="platform-card"
          :class="{ active: selectedBaseUrls.includes(platform.baseUrl) }"
          @click="togglePlatform(platform.baseUrl)"
        >
          <span class="platform-badge">{{ platform.shortName }}</span>
          <strong>{{ platform.name }}</strong>
          <small>{{ platform.baseUrl }}</small>
          <em>{{ platform.alarmSupported ? '支持报警同步' : '仅资产同步' }}</em>
        </button>
      </div>
    </el-card>

    <el-card class="modern-card" shadow="never">
      <template #header>
        <div class="section-title">
          <span>同步内容</span>
          <small>资产 / 报警</small>
        </div>
      </template>
      <div class="sync-options">
        <label class="sync-option" :class="{ active: syncAssets }">
          <input v-model="syncAssets" type="checkbox" />
          <span class="option-icon asset"></span>
          <strong>资产同步</strong>
          <small>同步单灯与监控终端</small>
        </label>
        <label class="sync-option" :class="{ active: syncFaults, disabled: !hasAlarmPlatform }">
          <input v-model="syncFaults" type="checkbox" :disabled="!hasAlarmPlatform" />
          <span class="option-icon alarm"></span>
          <strong>报警同步</strong>
          <small>仅汉源平台，按故障时间筛选</small>
        </label>
        <div class="days-box">
          <span>报警时间范围</span>
          <el-input-number v-model="faultDays" :min="1" :max="30" :disabled="!syncFaults" />
          <small>同步最近 N 天故障</small>
        </div>
      </div>
      <div class="sync-actions">
        <el-button type="primary" size="large" :loading="syncing" round @click="runSync">执行同步</el-button>
      </div>
    </el-card>

    <el-card v-if="lastResult" class="modern-card" shadow="never">
      <template #header>
        <div class="section-title">
          <span>同步结果</span>
          <small>按平台统计</small>
        </div>
      </template>
      <el-table :data="lastResult.targets ?? []" class="modern-table">
        <el-table-column label="平台" min-width="120">
          <template #default="{ row }">{{ platformName(row.baseUrl) }}</template>
        </el-table-column>
        <el-table-column prop="baseUrl" label="地址" min-width="190" />
        <el-table-column label="单灯">
          <template #default="{ row }">{{ statText(row.ilc) }}</template>
        </el-table-column>
        <el-table-column label="终端">
          <template #default="{ row }">{{ statText(row.rtu) }}</template>
        </el-table-column>
        <el-table-column label="报警">
          <template #default="{ row }">
            <span v-if="row.faults">近{{ row.faults.days }}天 {{ row.faults.total }} 条</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="160">
          <template #default="{ row }">
            <el-tag :type="row.error ? 'danger' : 'success'">{{ row.error ? '失败' : '成功' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { computed, ref, watch } from 'vue';
import { lampApi } from '../../api/modules';

const platforms = [
  { name: '高邮智慧照明', shortName: '高邮', baseUrl: 'http://36.139.220.121:8090', alarmSupported: false },
  { name: '汉源智慧照明', shortName: '汉源', baseUrl: 'http://171.208.94.46:7070', alarmSupported: true },
] as const;

const selectedBaseUrls = ref<string[]>(platforms.map((item) => item.baseUrl));
const syncAssets = ref(true);
const syncFaults = ref(false);
const faultDays = ref(7);
const syncing = ref(false);
const lastResult = ref<any>();

const hasAlarmPlatform = computed(() =>
  platforms.some((platform) => platform.alarmSupported && selectedBaseUrls.value.includes(platform.baseUrl)),
);

watch(hasAlarmPlatform, (value) => {
  if (!value) {
    syncFaults.value = false;
  }
});

function togglePlatform(baseUrl: string) {
  selectedBaseUrls.value = selectedBaseUrls.value.includes(baseUrl)
    ? selectedBaseUrls.value.filter((item) => item !== baseUrl)
    : [...selectedBaseUrls.value, baseUrl];
}

function platformName(baseUrl: string) {
  return platforms.find((platform) => platform.baseUrl === baseUrl)?.shortName ?? baseUrl;
}

function statText(stat?: any) {
  return stat ? `新增 ${stat.created} / 更新 ${stat.updated}` : '-';
}

async function runSync() {
  if (!selectedBaseUrls.value.length) {
    ElMessage.warning('请至少选择一个平台');
    return;
  }
  if (!syncAssets.value && !syncFaults.value) {
    ElMessage.warning('请至少选择资产同步或报警同步');
    return;
  }
  syncing.value = true;
  try {
    lastResult.value = await lampApi.syncPlatform({
      baseUrls: selectedBaseUrls.value,
      syncAssets: syncAssets.value,
      syncFaults: syncFaults.value,
      faultDays: faultDays.value,
    });
    const faultTotal = (lastResult.value.targets ?? []).reduce((sum: number, target: any) => sum + Number(target.faults?.total ?? 0), 0);
    ElMessage.success(`同步完成：平台 ${lastResult.value.baseUrlCount} 个${faultTotal ? `，报警 ${faultTotal} 条` : ''}`);
  } finally {
    syncing.value = false;
  }
}
</script>

<style scoped>
.sync-page {
  gap: 20px;
}

.sync-hero {
  background:
    radial-gradient(circle at 86% 12%, rgba(34, 211, 238, 0.28), transparent 30%),
    radial-gradient(circle at 16% 78%, rgba(37, 99, 235, 0.2), transparent 34%),
    linear-gradient(180deg, rgba(8, 47, 98, 0.92), rgba(3, 24, 55, 0.9));
}

.sync-summary {
  display: flex;
  gap: 10px;
}

.sync-summary span {
  padding: 10px 14px;
  border: 1px solid rgba(80, 183, 255, 0.32);
  border-radius: 6px;
  color: #dff4ff;
  background: rgba(9, 50, 103, 0.82);
  box-shadow: inset 0 0 16px rgba(37, 154, 255, 0.14);
  font-weight: 700;
}

.section-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-weight: 700;
}

.section-title small {
  color: #94a3b8;
  font-size: 12px;
}

.platform-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
}

.platform-card {
  display: grid;
  gap: 8px;
  padding: 18px;
  border: 1px solid #e2e8f0;
  border-radius: 22px;
  text-align: left;
  background: linear-gradient(135deg, #fff, #f8fafc);
  cursor: pointer;
  transition: all 0.18s ease;
}

.platform-card.active {
  border-color: #38bdf8;
  box-shadow: 0 18px 45px rgba(14, 165, 233, 0.16);
  transform: translateY(-2px);
}

.platform-card small {
  color: #64748b;
}

.platform-card em,
.platform-badge {
  width: fit-content;
  padding: 5px 10px;
  border-radius: 999px;
  color: #075985;
  background: #e0f2fe;
  font-style: normal;
  font-size: 12px;
  font-weight: 700;
}

.sync-options {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
}

.sync-option,
.days-box {
  display: grid;
  gap: 8px;
  padding: 18px;
  border: 1px solid #e2e8f0;
  border-radius: 22px;
  background: #fff;
}

.sync-option {
  cursor: pointer;
}

.sync-option input {
  display: none;
}

.sync-option.active {
  border-color: #2563eb;
  background: #eff6ff;
}

.sync-option.disabled {
  opacity: 0.52;
  cursor: not-allowed;
}

.sync-option small,
.days-box small {
  color: #64748b;
}

.option-icon {
  width: 34px;
  height: 34px;
  border-radius: 12px;
}

.option-icon.asset {
  background: linear-gradient(135deg, #2563eb, #22d3ee);
}

.option-icon.alarm {
  background: linear-gradient(135deg, #f97316, #ef4444);
}

.sync-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 18px;
}
</style>
