<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 { visitsApi } from '@/api/visits'
import { customersApi } from '@/api/customers'
import { uploadApi } from '@/api/upload'
import { compressImage } from '@/utils/image'
import { useAuthStore } from '@/stores/auth'
import ImagePreview from '@/components/ImagePreview.vue'
import EditLogPanel from '@/components/EditLogPanel.vue'
import api from '@/api/index'

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

const form = ref({
  customer_id: '',
  visit_date: todayStr(),
  visit_method: '上门',
  time_range: '',
  visitor_name: '',
  visitor_phone: '',
  communication_content: '',
  customer_demand: '',
  companions: [] as string[],
  photos: [] as string[],
})

const timeRangeValue = ref<any>(null)
const customers = ref<any[]>([])
const managers = ref<any[]>([])
const uploadedPhotos = ref<string[]>([])
const photoPreviews = ref<string[]>([])
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')
const uploading = ref(false)
const customerSearch = ref('')

onMounted(async () => {
  await loadCustomers()
  try {
    const res = await api.get('/users/', { params: { role: 'manager' } })
    managers.value = res.data
  } catch (_) {}
  if (isEdit.value) {
    try {
      const res = await visitsApi.get(route.params.id as string)
      const v = res.data
      // 确保当前客户在 select 选项列表中，避免显示 UUID
      if (v.customer_id && v.customer_name && !customers.value.find(c => c.id === v.customer_id)) {
        customers.value.unshift({ id: v.customer_id, name: v.customer_name })
      }
      form.value = {
        customer_id: v.customer_id,
        visit_date: v.visit_date,
        visit_method: v.visit_method,
        time_range: v.time_range,
        visitor_name: v.visitor_name || '',
        visitor_phone: v.visitor_phone || '',
        communication_content: v.communication_content || '',
        customer_demand: v.customer_demand || '',
        companions: (v.companions || []).map(String),
        photos: v.photos || [],
      }
      uploadedPhotos.value = v.photos || []
      // Parse time range back into picker
      if (v.time_range && v.time_range.includes('-')) {
        const parts = v.time_range.split('-')
        timeRangeValue.value = [parts[0], parts[1]]
      }
      for (const key of (v.photos || [])) {
        try {
          const urlRes = await uploadApi.getDownloadUrl(key)
          photoPreviews.value.push(urlRes.data.download_url)
        } catch (_) { photoPreviews.value.push('') }
      }
    } catch (_) {}
  }
})

async function loadCustomers(q?: string) {
  try {
    const params: any = { page_size: 100 }
    if (q) params.search = q
    const res = await customersApi.list(params)
    customers.value = res.data.items || []
  } catch (_) {}
}

async function handleCustomerSearch(query: string) {
  customerSearch.value = query
  if (query) { await loadCustomers(query) }
  else { await loadCustomers() }
}

async function handleQuickCreate() {
  const name = customerSearch.value.trim()
  if (!name) { ElMessage.warning('请输入单位名称'); return }
  try {
    const res = await api.post('/customers/quick-create', null, { params: { name } })
    const newCust = res.data
    customers.value.unshift(newCust)
    form.value.customer_id = newCust.id
    customerSearch.value = ''
    ElMessage.success(`已创建客户：${name}`)
    await loadCustomers()
  } catch (e: any) {
    ElMessage.error('创建失败: ' + (e.response?.data?.detail || e.message))
  }
}

async function handlePhotoUpload(event: Event) {
  const target = event.target as HTMLInputElement
  if (!target.files?.length) return
  if (uploadedPhotos.value.length >= 9) { ElMessage.warning('最多9张照片'); return }

  uploading.value = true
  for (const file of Array.from(target.files)) {
    if (uploadedPhotos.value.length >= 9) break
    const previewUrl = URL.createObjectURL(file)
    photoPreviews.value.push(previewUrl)
    try {
      // Compress before upload to reduce storage & transfer
      const compressed = await compressImage(file, { maxPixels: 1920, quality: 0.8 })
      const res = await uploadApi.getPresignedUrl(compressed.name, compressed.type || 'image/jpeg')
      await uploadApi.uploadFile(res.data.upload_url, compressed)
      uploadedPhotos.value.push(res.data.object_key)
      form.value.photos = [...uploadedPhotos.value]
    } catch (e: any) {
      const idx = photoPreviews.value.indexOf(previewUrl)
      if (idx >= 0) photoPreviews.value.splice(idx, 1)
      URL.revokeObjectURL(previewUrl)
      ElMessage.error('上传失败: ' + (e.response?.data?.detail || e.message))
    }
  }
  uploading.value = false
  target.value = ''
}

function onTimeRangeChange(val: [string, string] | null) {
  form.value.time_range = val ? val.join('-') : ''
}

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

function removePhoto(index: number) {
  if (index < photoPreviews.value.length) {
    URL.revokeObjectURL(photoPreviews.value[index])
    photoPreviews.value.splice(index, 1)
  }
  uploadedPhotos.value.splice(index, 1)
  form.value.photos = [...uploadedPhotos.value]
}

function splitCompanions(values: string[]) {
  // UUIDs → companions (system users), non-UUID strings → companion_names (external)
  const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
  const sys: string[] = []; const ext: string[] = []
  for (const v of values) {
    if (uuidRe.test(v)) sys.push(v)
    else if (v.trim()) ext.push(v.trim())
  }
  return { companions: sys, companion_names: ext }
}

async function handleSubmit() {
  if (!form.value.customer_id) { ElMessage.warning('请选择客户'); return }
  submitLoading.value = true
  try {
    const { companions, companion_names } = splitCompanions(form.value.companions || [])
    const body = { ...form.value, companions, companion_names }
    if (isEdit.value) {
      await visitsApi.update(route.params.id as string, body)
      ElMessage.success('记录已更新')
    } else {
      await visitsApi.create(body)
      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' })
    deleting.value = true
    await visitsApi.delete(route.params.id as string)
    ElMessage.success('已删除')
    router.push('/m')
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  } finally { deleting.value = false }
}
</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">VISIT RECORD</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-select
          v-model="form.customer_id"
          filterable
          remote
          :remote-method="handleCustomerSearch"
          placeholder="搜索/选择客户"
          style="width:100%"
        >
          <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
        </el-select>
        <div v-if="customerSearch && !customers.some(c => c.name === customerSearch)" style="margin-top:8px">
          <button type="button" class="quick-create-btn" @click="handleQuickCreate">
            <svg width="14" height="14" 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>
            新建客户「{{ customerSearch }}」
          </button>
        </div>
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">拜访日期</span>
        </template>
        <el-date-picker v-model="form.visit_date" type="date" style="width:100%" />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">拜访方式</span>
        </template>
        <div class="method-grid">
          <button
            v-for="m in ['上门','电话','微信','出差']"
            :key="m"
            type="button"
            class="method-chip"
            :class="{ 'method-chip--active': form.visit_method === m, ['method--' + m]: true }"
            @click="form.visit_method = m"
          >{{ m }}</button>
        </div>
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">时间范围</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-hint">可输入外部人员</span></span>
        </template>
        <el-select v-model="form.companions" multiple filterable allow-create default-first-option placeholder="选择或输入姓名（可多选）" style="width:100%">
          <el-option v-for="m in managers" :key="m.id" :label="m.name" :value="m.id" :disabled="m.id === auth.userId" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">拜访人姓名</span>
        </template>
        <el-input v-model="form.visitor_name" placeholder="实际拜访人姓名" />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">拜访人电话 <span class="form-label-hint">可选</span></span>
        </template>
        <el-input v-model="form.visitor_phone" placeholder="联系电话（可选）" />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">沟通内容</span>
        </template>
        <el-input v-model="form.communication_content" type="textarea" :rows="4" placeholder="本次拜访沟通内容..." />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">客户需求</span>
        </template>
        <el-input v-model="form.customer_demand" type="textarea" :rows="2" placeholder="客户提出的需求..." />
      </el-form-item>

      <el-form-item>
        <template #label>
          <span class="form-label">拜访照片 <span class="form-label-hint">最多9张</span></span>
        </template>
        <div class="photo-area">
          <div v-for="(key, idx) in uploadedPhotos" :key="key" class="photo-item">
            <img :src="photoPreviews[idx]" class="photo-thumb" v-if="photoPreviews[idx]" @click.stop="previewPhoto(photoPreviews[idx])" />
            <span class="photo-label">照片{{ idx + 1 }}</span>
            <button type="button" class="photo-remove-btn" @click="removePhoto(idx)">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
          <label v-if="uploadedPhotos.length < 9" class="upload-btn">
            <span class="upload-btn__inner">
              <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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="17 8 12 3 7 8"></polyline>
                <line x1="12" y1="3" x2="12" y2="15"></line>
              </svg>
              {{ uploading ? '上传中...' : '拍照/选图' }}
            </span>
            <input type="file" accept="image/*" multiple @change="handlePhotoUpload" class="file-input-hidden" />
          </label>
        </div>
      </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" :disabled="deleting" @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>

    <ImagePreview v-model="previewDialogVisible" :image-url="previewImageUrl" />
  </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 Spacing ═══ */
.editorial-form .el-form-item {
  margin-bottom: 20px;
}

/* ═══ Quick Create Button ═══ */
.quick-create-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: 1px dashed var(--gold);
  padding: 8px 14px;
  color: var(--gold-dark);
  font-family: var(--font-body);
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  letter-spacing: 0.03em;
}

.quick-create-btn:hover {
  border-color: var(--vermilion);
  color: var(--vermilion);
  background: rgba(184,71,46,0.03);
}

/* ═══ Photo Area ═══ */
.photo-area {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.photo-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--paper);
  border: 1px solid var(--warm-border);
  padding: 6px 10px;
}

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

.photo-label {
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--warm-gray);
  letter-spacing: 0.03em;
}

.photo-remove-btn {
  background: none;
  border: none;
  color: var(--vermilion);
  cursor: pointer;
  padding: 2px;
  display: flex;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.photo-remove-btn:hover { opacity: 1; }

.upload-btn { cursor: pointer; position: relative; display: inline-block; }

.upload-btn__inner {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 18px;
  border: 1px dashed var(--warm-border);
  color: var(--warm-gray);
  font-family: var(--font-body);
  font-size: 13px;
  transition: all 0.2s;
  letter-spacing: 0.03em;
}

.upload-btn__inner:hover {
  border-color: var(--gold);
  color: var(--gold-dark);
}

.file-input-hidden {
  position: absolute; left: 0; top: 0;
  width: 100%; height: 100%;
  opacity: 0; cursor: pointer;
}

/* ═══ 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;
}

/* ═══ Loading Animation ═══ */
.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); } }

/* ═══ Method Chips ═══ */
.method-grid { display: flex; gap: 8px; flex-wrap: wrap; }

.method-chip {
  flex: 1; min-width: 64px;
  padding: 10px 8px;
  background: var(--surface);
  border: 1px solid var(--warm-border);
  font-family: var(--font-body);
  font-size: 13px; letter-spacing: 0.04em;
  cursor: pointer; transition: all 0.25s;
  text-align: center;
}

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

.method--上门.method-chip--active { background: #4A6741; border-color: #4A6741; color: #fff; }
.method--电话.method-chip--active { background: #5B7FA5; border-color: #5B7FA5; color: #fff; }
.method--微信.method-chip--active { background: #22c55e; border-color: #22c55e; color: #fff; }
.method--出差.method-chip--active { background: #C4934A; border-color: #C4934A; color: #fff; }
</style>
