<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { visitsApi } from '@/api/visits'
import { uploadApi } from '@/api/upload'
import ImagePreview from '@/components/ImagePreview.vue'
import { ElMessage } from 'element-plus'
import api from '@/api/index'

const router = useRouter()
const todayVisitCount = ref(0)
const visits = ref<any[]>([])
const todayNoteCount = ref(0)
const dailyNotes = ref<any[]>([])
const previewImageUrl = ref('')
const previewDialogVisible = ref(false)
const photoUrls = ref<Record<string, string>>({})
const loading = ref(false)

const todayTotal = computed(() => todayVisitCount.value + todayNoteCount.value)

const categoryColors: Record<string, string> = {
  '行政事务': '#1C3738', '合同整理': '#4A6741', '发票处理': '#C4934A',
  '内部会议': '#B8472E', '培训学习': '#5B7FA5', '其他': '#7B7568',
}

const categoryGlyphs: Record<string, string> = {
  '行政事务': '政', '合同整理': '约', '发票处理': '票',
  '内部会议': '议', '培训学习': '学', '其他': '杂',
}

async function loadToday() {
  loading.value = true
  try {
    const [vRes, nRes] = await Promise.all([
      visitsApi.getToday(),
      api.get('/daily-notes/today'),
    ])
    todayVisitCount.value = vRes.data.count
    visits.value = vRes.data.visits
    todayNoteCount.value = nRes.data.count
    dailyNotes.value = nRes.data.notes
    for (const v of visits.value) {
      if (v.photos?.length > 0) {
        for (const key of v.photos) {
          try {
            const urlRes = await uploadApi.getDownloadUrl(key)
            photoUrls.value[key] = urlRes.data.download_url
          } catch (_) {}
        }
      }
    }
  } catch (e: any) {
    ElMessage.error('加载失败')
  } finally { loading.value = false }
}

function previewPhoto(url: string) { previewImageUrl.value = url; previewDialogVisible.value = true }

onMounted(loadToday)
</script>

<template>
  <div class="mobile-home">
    <!-- ═══ Editorial Stat Banner ═══ -->
    <div class="stat-banner">
      <div class="stat-masthead">
        <span class="stat-label-sm">TODAY</span>
        <span class="stat-date">{{ new Date().toLocaleDateString('zh-CN', { month:'long', day:'numeric', weekday:'short' }) }}</span>
      </div>
      <div class="stat-main">
        <span class="stat-number">{{ todayTotal }}</span>
        <span class="stat-unit">条记录</span>
        <div class="stat-breakdown">
          <span class="stat-piece">拜访 <strong>{{ todayVisitCount }}</strong></span>
          <span class="stat-sep">·</span>
          <span class="stat-piece">纪要 <strong>{{ todayNoteCount }}</strong></span>
        </div>
      </div>
      <!-- Decorative ink-wash corner -->
      <div class="stat-ornament"></div>
    </div>

    <!-- ═══ Primary Quick Actions ═══ -->
    <div class="quick-actions">
      <button class="action-btn action-btn--primary" @click="router.push('/m/visit/new')">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        <span class="action-btn__text">今日拜访</span>
      </button>
      <button class="action-btn action-btn--secondary" @click="router.push('/m/note/new')">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
          <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
        </svg>
        <span class="action-btn__text">今日纪要</span>
      </button>
    </div>

    <!-- ═══ Secondary Quick Links ═══ -->
    <div class="quick-links">
      <button class="link-chip" @click="router.push('/m/work-plan/new')">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
          <line x1="16" y1="2" x2="16" y2="6"></line>
          <line x1="8" y1="2" x2="8" y2="6"></line>
          <line x1="3" y1="10" x2="21" y2="10"></line>
        </svg>
        工作计划
      </button>
      <button class="link-chip" @click="router.push('/m/mini-biz/new')">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="1" x2="12" y2="23"></line>
          <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
        </svg>
        商机跟单
      </button>
      <button class="link-chip" @click="router.push('/m/key-visit/new')">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
        </svg>
        要客拜访
      </button>
      <button class="link-chip" @click="router.push('/m/leaves')">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
        </svg>
        请假
      </button>
    </div>

    <!-- ═══ Section Divider ═══ -->
    <div class="section-head" v-if="dailyNotes.length || visits.length">
      <span class="section-title">今日记录</span>
      <span class="section-line"></span>
    </div>

    <div v-loading="loading" class="records-area">
      <!-- ═══ Daily Notes ═══ -->
      <template v-if="dailyNotes.length">
        <article
          v-for="(n, i) in dailyNotes"
          :key="n.id"
          class="record-card record-card--note"
          :class="{ 'record-card--offset': i % 2 === 1 }"
          @click="router.push(`/m/note/${n.id}/edit`)"
        >
          <div class="record-accent" :style="{ background: categoryColors[n.category] || '#7B7568' }"></div>
          <div class="record-body">
            <div class="record-header">
              <span class="record-glyph" :style="{ background: categoryColors[n.category] || '#7B7568' }">
                {{ categoryGlyphs[n.category] || '记' }}
              </span>
              <span class="record-category">{{ n.category }}</span>
              <span v-if="n.time_range" class="record-time">{{ n.time_range }}</span>
            </div>
            <p class="record-content">{{ n.content }}</p>
            <div class="record-footer" v-if="n.time_range">
              <span class="record-time">{{ n.time_range }}</span>
            </div>
          </div>
        </article>
      </template>

      <!-- ═══ Visit Records ═══ -->
      <template v-if="visits.length">
        <article
          v-for="(v, i) in visits"
          :key="v.id"
          class="record-card record-card--visit"
          :class="{ 'record-card--offset': (dailyNotes.length + i) % 2 === 1 }"
          @click="router.push(`/m/visit/${v.id}/edit`)"
        >
          <div class="record-accent record-accent--gold"></div>
          <div class="record-body">
            <div class="record-header">
              <span class="record-glyph record-glyph--visit">访</span>
              <strong class="record-customer">{{ v.customer_name || '未知客户' }}</strong>
              <span class="record-badge" :class="'badge--' + v.visit_method">{{ v.visit_method }}</span>
            </div>
            <p class="record-content">{{ v.communication_content || '暂无沟通内容' }}</p>
            <p v-if="v.customer_demand" class="record-demand">
              <span class="demand-marker">◆</span> {{ v.customer_demand }}
            </p>
            <div v-if="v.photos?.length" class="record-photos">
              <img v-for="key in v.photos" :key="key" :src="photoUrls[key] || ''" class="record-photo" @click.stop="previewPhoto(photoUrls[key])" />
            </div>
            <div class="record-footer" v-if="v.time_range">
              <span class="record-time">{{ v.time_range }}</span>
            </div>
          </div>
        </article>
      </template>

      <!-- Empty State -->
      <div v-if="visits.length === 0 && dailyNotes.length === 0 && !loading" class="empty-state">
        <div class="empty-glyph">—</div>
        <p class="empty-text">今日暂无记录</p>
        <p class="empty-hint">点击上方按钮开始填报</p>
      </div>
    </div>

    <ImagePreview v-model="previewDialogVisible" :image-url="previewImageUrl" />
  </div>
</template>

<style scoped>
/* ═══ Page ═══ */
.mobile-home {
  padding-bottom: 24px;
  max-width: 100%;
  position: relative;
}

/* ═══ Stat Banner — Editorial Masthead ═══ */
.stat-banner {
  position: relative;
  background: var(--surface);
  border: 1px solid var(--warm-border);
  padding: 20px 22px;
  margin-bottom: 18px;
  overflow: hidden;
}

.stat-masthead {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stat-label-sm {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.2em;
  color: var(--warm-gray);
}

.stat-date {
  font-family: var(--font-body);
  font-size: 12px;
  color: var(--warm-gray);
  letter-spacing: 0.04em;
}

.stat-main {
  display: flex;
  align-items: baseline;
  gap: 8px;
  flex-wrap: wrap;
}

.stat-number {
  font-family: var(--font-heading);
  font-size: 56px;
  color: var(--ink);
  line-height: 1;
  letter-spacing: 0.04em;
}

.stat-unit {
  font-family: var(--font-body);
  font-size: 16px;
  color: var(--warm-gray);
  letter-spacing: 0.06em;
}

.stat-breakdown {
  width: 100%;
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 6px;
}

.stat-piece {
  font-family: var(--font-body);
  font-size: 13px;
  color: var(--warm-gray);
  letter-spacing: 0.03em;
}

.stat-piece strong {
  font-family: var(--font-mono);
  color: var(--ink);
  font-size: 15px;
}

.stat-sep {
  color: var(--gold);
  font-weight: 300;
}

/* Decorative gold slash */
.stat-ornament {
  position: absolute;
  top: -20px;
  right: -20px;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, transparent 50%, rgba(196,147,74,0.08) 50%);
  pointer-events: none;
}

/* ═══ Quick Actions ═══ */
.quick-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px 12px;
  border: 1px solid var(--warm-border);
  cursor: pointer;
  font-family: var(--font-body);
  font-size: 15px;
  letter-spacing: 0.04em;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.action-btn:active {
  transform: scale(0.97);
}

.action-btn--primary {
  background: var(--ink);
  color: #fff;
  border-color: var(--ink);
}

.action-btn--primary:hover {
  background: var(--ink-light);
}

.action-btn--secondary {
  background: var(--surface);
  color: var(--ink);
  border-color: var(--ink);
}

.action-btn--secondary:hover {
  background: var(--c-primary-bg);
}

.action-btn__text {
  font-weight: 500;
}

/* ═══ Quick Links (Chips) ═══ */
.quick-links {
  display: flex;
  gap: 8px;
  margin-bottom: 22px;
  flex-wrap: wrap;
}

.link-chip {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 9px 15px;
  background: var(--surface);
  border: 1px solid var(--warm-border);
  color: var(--ink);
  font-family: var(--font-body);
  font-size: 13px;
  letter-spacing: 0.03em;
  cursor: pointer;
  transition: all 0.2s;
}

.link-chip:hover {
  border-color: var(--gold);
  color: var(--vermilion);
}

.link-chip:active {
  background: var(--paper-dark);
}

/* ═══ Section Head ═══ */
.section-head {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 14px;
}

.section-title {
  font-family: var(--font-heading);
  font-size: 18px;
  color: var(--ink);
  letter-spacing: 0.06em;
  white-space: nowrap;
}

.section-line {
  flex: 1;
  height: 2px;
  background: var(--gold);
}

/* ═══ Record Cards ═══ */
.records-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-card {
  background: var(--surface);
  border: 1px solid var(--warm-border);
  display: flex;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}
.record-card:active { transform: scale(0.99); }

.record-card--offset {
  margin-left: 16px;
}

.record-card:hover {
  box-shadow: 0 4px 12px rgba(28,55,56,0.06);
}

/* Left accent stripe */
.record-accent {
  width: 4px;
  flex-shrink: 0;
}

.record-accent--gold {
  background: var(--gold);
}

.record-body {
  flex: 1;
  padding: 14px 16px;
  min-width: 0;
}

.record-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

/* Category glyph — single Chinese character badge */
.record-glyph {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 22px;
  height: 22px;
  color: #fff;
  font-family: var(--font-heading);
  font-size: 13px;
  flex-shrink: 0;
}

.record-glyph--visit {
  background: var(--gold);
}

.record-category {
  font-family: var(--font-heading);
  font-size: 13px;
  color: var(--ink);
  letter-spacing: 0.04em;
  font-weight: 600;
}

.record-badge {
  font-family: var(--font-body);
  font-size: 11px;
  padding: 1px 8px;
  letter-spacing: 0.04em;
  margin-left: auto;
  border: 1px solid;
}
.badge--上门 { color: #4A6741; border-color: #4A6741; }
.badge--电话 { color: #5B7FA5; border-color: #5B7FA5; }
.badge--微信 { color: #22c55e; border-color: #22c55e; }
.badge--出差 { color: #C4934A; border-color: #C4934A; }


.record-customer {
  font-family: var(--font-heading);
  font-size: 15px;
  color: var(--ink);
  letter-spacing: 0.03em;
  flex: 1;
}

.record-time {
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--warm-gray);
  letter-spacing: 0.03em;
  margin-left: auto;
}

.record-content {
  font-family: var(--font-body);
  font-size: 14px;
  color: var(--c-text);
  line-height: 1.7;
  margin: 0 0 8px;
  word-break: break-all;
}

.record-demand {
  font-family: var(--font-body);
  font-size: 13px;
  color: var(--vermilion);
  margin: 0 0 8px;
  line-height: 1.6;
}

.demand-marker {
  color: var(--gold);
  font-size: 10px;
}

.record-photos {
  display: flex;
  gap: 6px;
  margin: 8px 0;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 2px;
}

.record-photo {
  width: 68px;
  height: 68px;
  object-fit: cover;
  flex-shrink: 0;
  border: 2px solid var(--warm-border);
}

.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

/* ═══ Empty State ═══ */
.empty-state {
  text-align: center;
  padding: 48px 0;
}

.empty-glyph {
  font-family: var(--font-heading);
  font-size: 40px;
  color: var(--gold);
  opacity: 0.4;
  margin-bottom: 8px;
}

.empty-text {
  font-family: var(--font-body);
  font-size: 15px;
  color: var(--warm-gray);
  margin: 0 0 4px;
}

.empty-hint {
  font-family: var(--font-body);
  font-size: 12px;
  color: var(--c-text-muted);
  margin: 0;
}
</style>
