<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { todayStr } from '@/utils'
import api from '@/api/index'
import EditLogPanel from '@/components/EditLogPanel.vue'

const router = useRouter()
const route = useRoute()
const isEdit = computed(() => !!route.params.id)
const submitLoading = ref(false)

const categories = ['行政事务', '合同整理', '发票处理', '内部会议', '培训学习', '其他']

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

const timeRangeValue = ref<any>(null)
const form = ref({
  note_date: todayStr(),
  category: '其他',
  content: '',
  time_range: '',
})

function onTimeRangeChange(val: [string, string] | null) {
  form.value.time_range = val ? val.join('-') : ''
}
function parseTimeRange(str: string): [string, string] | null {
  if (!str || !str.includes('-')) return null
  const parts = str.split('-')
  return parts.length >= 2 ? [parts[0], parts[1]] as [string, string] : null
}

onMounted(async () => {
  if (isEdit.value) {
    try {
      const res = await api.get(`/daily-notes/${route.params.id}`)
      const n = res.data
      form.value = {
        note_date: n.note_date,
        category: n.category,
        content: n.content || '',
        time_range: n.time_range || '',
      }
      timeRangeValue.value = parseTimeRange(n.time_range)
    } catch (_) {}
  }
})

async function handleSubmit() {
  if (!form.value.content.trim()) { ElMessage.warning('请输入纪要内容'); return }
  submitLoading.value = true
  try {
    if (isEdit.value) {
      await api.put(`/daily-notes/${route.params.id}`, form.value)
      ElMessage.success('纪要已更新')
    } else {
      await api.post('/daily-notes/', form.value)
      ElMessage.success('纪要已提交')
    }
    router.push('/m')
  } catch (e: any) {
    ElMessage.error('提交失败: ' + (e.response?.data?.detail || e.message))
  } finally { submitLoading.value = false }
}

async function handleDelete() {
  try {
    await ElMessageBox.confirm('确定删除这条纪要？', '确认', { type: 'warning' })
    await api.delete(`/daily-notes/${route.params.id}`)
    ElMessage.success('已删除')
    router.push('/m')
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  }
}
</script>

<template>
  <div class="form-page">
    <!-- ═══ Editorial Header ═══ -->
    <header class="form-editorial-header">
      <button type="button" class="form-back-btn" @click="router.back()">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="19" y1="12" x2="5" y2="12"></line>
          <polyline points="12 19 5 12 12 5"></polyline>
        </svg>
      </button>
      <div class="form-title-group">
        <h2 class="form-title">{{ isEdit ? '编辑纪要' : '今日纪要' }}</h2>
        <span class="form-subtitle">DAILY NOTE</span>
      </div>
      <div class="form-rule"></div>
    </header>

    <el-form label-position="top" class="editorial-form">
      <el-form-item>
        <template #label>
          <span class="form-label">日期</span>
        </template>
        <el-date-picker v-model="form.note_date" type="date" style="width:100%" />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">分类</span>
        </template>
        <div class="category-grid">
          <button
            v-for="c in categories"
            :key="c"
            type="button"
            class="cat-chip"
            :class="{ 'cat-chip--active': form.category === c }"
            :style="form.category === c ? { background: catColors[c], borderColor: catColors[c], color: '#fff' } : {}"
            @click="form.category = c"
          >
            {{ c }}
          </button>
        </div>
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">时间范围 <span class="form-label-hint">可选</span></span>
        </template>
        <el-time-picker
          v-model="timeRangeValue"
          is-range
          format="HH:mm"
          value-format="HH:mm"
          range-separator="至"
          start-placeholder="开始"
          end-placeholder="结束"
          style="width:100%"
          @change="onTimeRangeChange"
        />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">工作内容 <span class="form-label-required">*</span></span>
        </template>
        <el-input v-model="form.content" type="textarea" :rows="5" placeholder="今天做了什么..." />
      </el-form-item>

      <div class="form-actions">
        <button class="submit-btn" :disabled="submitLoading" @click="handleSubmit">
          <span v-if="submitLoading" class="btn-loading"></span>
          {{ isEdit ? '保存修改' : '提交纪要' }}
        </button>
        <button v-if="isEdit" type="button" class="delete-btn" @click="handleDelete">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
          </svg>
          删除
        </button>
      </div>
      <EditLogPanel v-if="isEdit" :edit-log="form.edit_log || []" />
    </el-form>
  </div>
</template>

<style scoped>
/* ═══ Page ═══ */
.form-page { max-width: 100%; margin: 0 auto; padding-bottom: 20px; }

/* ═══ Editorial Header ═══ */
.form-editorial-header {
  display: flex; align-items: flex-start; gap: 14px;
  margin-bottom: 26px; flex-wrap: wrap;
}

.form-back-btn {
  background: var(--surface); border: 1px solid var(--warm-border);
  padding: 8px 10px; cursor: pointer; color: var(--warm-gray);
  display: flex; align-items: center; transition: all var(--transition);
  flex-shrink: 0; margin-top: 2px;
}
.form-back-btn:hover { color: var(--ink); border-color: var(--ink); }

.form-title-group {
  display: flex; flex-direction: column; gap: 0; flex: 1;
}

.form-title {
  margin: 0; font-family: var(--font-heading);
  font-size: 24px; font-weight: 400; color: var(--ink);
  letter-spacing: 0.06em; line-height: 1.3;
}

.form-subtitle {
  font-family: var(--font-mono);
  font-size: 9px; color: var(--gold); letter-spacing: 0.2em;
}

.form-rule {
  width: 100%; height: 2px; background: var(--warm-border);
  margin-top: 6px; position: relative;
}
.form-rule::after {
  content: ''; position: absolute; left: 0; top: 0;
  width: 32px; height: 2px; background: var(--gold);
}

/* ═══ Form Labels ═══ */
.form-label {
  font-family: var(--font-heading) !important;
  font-size: 14px !important; color: var(--ink) !important;
  letter-spacing: 0.04em; font-weight: 500 !important;
}
.form-label-hint {
  font-family: var(--font-body);
  font-size: 11px; color: var(--warm-gray);
  letter-spacing: 0.03em; font-weight: 400; margin-left: 6px;
}
.form-label-required { color: var(--vermilion); margin-left: 2px; }

.editorial-form .el-form-item { margin-bottom: 20px; }

/* ═══ Category Grid ═══ */
.category-grid { display: flex; flex-wrap: wrap; gap: 8px; }

.cat-chip {
  padding: 10px 16px;
  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.25s;
}

.cat-chip:hover { border-color: var(--gold); }
.cat-chip--active { font-weight: 600; }

/* ═══ Actions ═══ */
.form-actions {
  display: flex; gap: 10px; margin-top: 28px;
}

.submit-btn {
  flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px;
  padding: 16px; background: var(--ink); color: #fff; border: none;
  font-family: var(--font-heading);
  font-size: 16px; letter-spacing: 0.08em; cursor: pointer; transition: all 0.25s;
}
.submit-btn:hover { background: var(--ink-light); }
.submit-btn:active { transform: scale(0.98); }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }

.delete-btn {
  display: flex; align-items: center; gap: 6px;
  padding: 16px 20px;
  background: var(--surface); color: var(--vermilion);
  border: 1px solid var(--vermilion);
  font-family: var(--font-body);
  font-size: 14px; letter-spacing: 0.04em; cursor: pointer; transition: all 0.25s;
}
.delete-btn:hover { background: var(--vermilion); color: #fff; }

.btn-loading {
  width: 16px; height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-top-color: #fff; border-radius: 50%;
  animation: spin 0.6s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
