<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import { ElMessage, ElMessageBox } from 'element-plus'
import { todayStr } from '@/utils'
import { getMgrStyle, loadManagerColors } from '@/utils/managerColor'
import { useScreenshot } from '@/utils/screenshot'
import api from '@/api/index'
import { miniBusinessApi } from '@/api/miniBusiness'
import EditLogPanel from '@/components/EditLogPanel.vue'

const auth = useAuthStore()
const themeStore = useThemeStore()
const loading = ref(false)
const isLight = computed(() => themeStore.currentTheme === 'light')
const miniBusiness = ref<any[]>([])
const customers = ref<any[]>([])
const allManagers = ref<any[]>([])
const shotRef = ref<HTMLElement | null>(null)
const { capturing, captureEl } = useScreenshot()

const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const form = ref<any>({})
const statusPick = ref<Record<string, string>>({})
const miniStatuses = ['跟进中', '已签约', '已流失']

// ── Detail + Follow-up logs ──
const detailVisible = ref(false)
const selectedBusiness = ref<any>(null)
const logs = ref<any[]>([])
const logForm = ref({ log_date: '', method: '电话', content: '' })
const logMethods = ['电话', '微信', '上门', '邮件', '其他']
const logMethodIcons: Record<string, string> = { '电话': '📞', '微信': '💬', '上门': '🏢', '邮件': '📧', '其他': '📋' }
const logMethodColors: Record<string, string> = { '电话': '#5B7FA5', '微信': '#22c55e', '上门': '#4A6741', '邮件': '#C4934A', '其他': '#7B7568' }
const logLoading = ref(false)
const logSaving = ref(false)

// ── Filters ──
const filterManager = ref('')
const filterStatus = ref('')

const managerOptions = computed(() => {
  const seen = new Set<string>()
  return miniBusiness.value
    .map((m: any) => m.manager_name || '未知')
    .filter((n: string) => { if (seen.has(n)) return false; seen.add(n); return true })
    .sort()
})

const filteredItems = computed(() => {
  let list = miniBusiness.value
  if (filterManager.value) list = list.filter((m: any) => (m.manager_name || '未知') === filterManager.value)
  if (filterStatus.value) list = list.filter((m: any) => m.status === filterStatus.value)
  return list
})

function resetFilters() {
  filterManager.value = ''
  filterStatus.value = ''
}

async function handleScreenshot() {
  const d = new Date().toISOString().slice(0, 10)
  await captureEl(shotRef.value, `商机跟单_${d}.png`)
}

const managerSummary = computed(() => {
  const map: Record<string, number> = {}
  miniBusiness.value.forEach((m: any) => {
    const n = m.manager_name || '未知'
    map[n] = (map[n] || 0) + 1
  })
  return Object.entries(map).sort((a, b) => b[1] - a[1])
})

onMounted(async () => {
  await Promise.all([loadItems(), loadCustomers(), loadManagerColors()])
  if (auth.isDirector || auth.isLeader) {
    api.get('/users/', { params: { role: 'manager' } }).then(r => { allManagers.value = r.data }).catch(() => {})
  }
})

const customerSearch = ref('')

async function loadCustomers(q?: string) {
  try {
    const params: any = { page_size: 500 }
    if (q) params.search = q
    const res = await api.get('/customers/', { 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 loadItems() {
  loading.value = true
  try {
    const res = await api.get('/mini-business/')
    miniBusiness.value = res.data
  } catch (e: any) { ElMessage.error('加载失败') }
  finally { loading.value = false }
}

function openCreate() {
  dialogMode.value = 'create'
  form.value = { customer_id: '', product_type: '', amount: '', follow_up_detail: '', status: '跟进中', expected_revenue_date: '', manager_id: auth.userId || '' }
  dialogVisible.value = true
}

function openEdit(item: any) {
  dialogMode.value = 'edit'
  form.value = { ...item }
  if (item.customer_id && item.customer_name && !customers.value.find((c: any) => c.id === item.customer_id)) {
    customers.value.unshift({ id: item.customer_id, name: item.customer_name })
  }
  dialogVisible.value = true
}

async function handleSave() {
    if (!form.value.customer_id) { ElMessage.warning('请选择客户单位'); return }
  try {
    if (dialogMode.value === 'create') {
      await api.post('/mini-business/', form.value)
    } else {
      await api.put(`/mini-business/${form.value.id}`, form.value)
    }
    ElMessage.success(dialogMode.value === 'create' ? '已创建' : '已更新')
    dialogVisible.value = false
    await loadItems()
  } catch (e: any) { ElMessage.error('保存失败: ' + (e.response?.data?.detail || e.message)) }
}

async function handleDelete(id: string) {
  try {
    await ElMessageBox.confirm('确定删除？', '确认', { type: 'warning' })
    await api.delete(`/mini-business/${id}`)
    ElMessage.success('已删除')
    await loadItems()
  } catch (e: any) { if (e !== 'cancel') ElMessage.error('删除失败') }
}

// ── Detail + Follow-up logs ──
async function openDetail(item: any) {
  selectedBusiness.value = item
  detailVisible.value = true
  logForm.value = { log_date: new Date().toISOString().slice(0, 10), method: '电话', content: '' }
  await loadLogs()
}

async function loadLogs() {
  logLoading.value = true
  try {
    const res = await miniBusinessApi.getLogs(selectedBusiness.value.id)
    logs.value = res.data || []
  } catch (_) { logs.value = [] }
  finally { logLoading.value = false }
}

async function handleCreateLog() {
  if (!logForm.value.content.trim()) { ElMessage.warning('请输入跟进内容'); return }
  logSaving.value = true
  try {
    await miniBusinessApi.createLog(selectedBusiness.value.id, logForm.value)
    ElMessage.success('跟进记录已添加')
    logForm.value = { log_date: new Date().toISOString().slice(0, 10), method: '电话', content: '' }
    await loadLogs()
  } catch (e: any) { ElMessage.error('添加失败: ' + (e.response?.data?.detail || e.message)) }
  finally { logSaving.value = false }
}

async function handleDeleteLog(logId: string) {
  try {
    await ElMessageBox.confirm('确定删除该跟进记录？', '确认', { type: 'warning' })
    await miniBusinessApi.deleteLog(logId)
    ElMessage.success('已删除')
    await loadLogs()
  } catch (e: any) { if (e !== 'cancel') ElMessage.error('删除失败') }
}

async function quickStatusChange(row: any, newStatus: string) {
  try {
    await ElMessageBox.confirm(`确定将状态改为「${newStatus}」？`, '确认', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
    await api.put(`/mini-business/${row.id}`, { status: newStatus })
    ElMessage.success('状态已更新')
    await loadItems()
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error('更新失败: ' + (e.response?.data?.detail || e.message))
    delete statusPick.value[row.id]
  }
}
</script>

<template>
  <div class="mini-biz-page" v-loading="loading">
    <div ref="shotRef">
    <div class="page-head">
      <div class="page-head-row">
        <div>
          <h2 class="page-title">商机跟单</h2>
          <p class="page-desc">小微业务商机管道，按状态跟踪签约进展。</p>
        </div>
        <div class="page-head-actions">
          <el-button type="primary" @click="openCreate" class="screenshot-hide">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:4px">
              <line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            新建商机
          </el-button>
          <el-button type="warning" :loading="capturing" @click="handleScreenshot" class="screenshot-hide">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:4px">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
              <circle cx="8.5" cy="8.5" r="1.5"></circle>
              <polyline points="21 15 16 10 5 21"></polyline>
            </svg>
            截图导出
          </el-button>
        </div>
      </div>
      <div class="page-rule"></div>
      <div v-if="managerSummary.length" class="summary-bar">
        <span class="summary-label">客户经理汇总</span>
        <span v-for="[name, count] in managerSummary" :key="name" class="summary-chip" :class="{ 'summary-chip--active': filterManager === name }" :style="getMgrStyle(name, isLight)" @click="filterManager = filterManager === name ? '' : name">{{ name }} · {{ count }}</span>
      </div>
    </div>

    <!-- Filter Bar -->
    <div class="filter-bar">
      <div class="filter-row">
        <div class="filter-item">
          <label class="filter-label">客户经理</label>
          <el-select v-model="filterManager" clearable placeholder="全部" size="small" style="width:150px">
            <el-option v-for="m in managerOptions" :key="m" :label="m" :value="m" />
          </el-select>
        </div>
        <div class="filter-item">
          <label class="filter-label">状态</label>
          <el-select v-model="filterStatus" clearable placeholder="全部" size="small" style="width:120px">
            <el-option v-for="s in miniStatuses" :key="s" :label="s" :value="s" />
          </el-select>
        </div>
        <el-button v-if="filterManager || filterStatus" size="small" plain @click="resetFilters">重置</el-button>
        <span class="filter-count">{{ filteredItems.length }} / {{ miniBusiness.length }} 条</span>
      </div>
    </div>

    <el-card>
      <el-table :data="filteredItems" stripe size="small" v-if="filteredItems.length" v-column-resize>
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="customer_name" label="客户" width="160">
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail(row)">{{ row.customer_name }}</el-link>
            <el-tooltip v-if="row.edit_log?.length > 1" placement="top">
              <template #content>最后编辑：{{ row.edit_log[row.edit_log.length-1].editor }} · {{ row.edit_log.length-1 }}次修改</template>
              <span class="edit-indicator" title="有过修改">🕐</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="客户经理" width="100">
          <template #default="{ row }">
            <span class="mgr-tag" :style="getMgrStyle(row.manager_name, isLight)">{{ row.manager_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="product_type" label="产品类型" width="130" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="follow_up_detail" label="跟进内容" min-width="250" show-overflow-tooltip />
        <el-table-column label="状态" width="130">
          <template #default="{ row }">
            <el-select
              v-model="statusPick[row.id]"
              size="small"
              style="width:100%"
              :placeholder="row.status"
              @change="(v: string) => quickStatusChange(row, v)"
              @visible-change="(v: boolean) => { if (v) statusPick[row.id] = row.status }"
            >
              <el-option v-for="s in miniStatuses" :key="s" :label="s" :value="s" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="expected_revenue_date" label="预计列收" width="110" />
        <el-table-column label="操作" width="80" fixed="right" class-name="screenshot-hide">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!miniBusiness.length" class="empty">暂无商机记录</div>
      <div v-else-if="miniBusiness.length && !filteredItems.length" class="empty">无匹配结果</div>
    </el-card>
    </div><!-- /shotRef -->

    <!-- Dialog -->
    <el-dialog v-model="dialogVisible" :title="(dialogMode === 'create' ? '新建' : '编辑') + ' 小微商机'" width="500px">
      <el-form label-position="top">
        <el-form-item label="客户单位 *">
          <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" />
            <template #empty>
              <div v-if="customerSearch" class="select-empty-create">
                <p style="color:var(--warm-gray);font-size:13px;margin:0 0 8px">未找到「{{ customerSearch }}」</p>
                <button type="button" class="quick-create-btn" @click.stop="handleQuickCreate">+ 新建客户「{{ customerSearch }}」</button>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item v-if="auth.isDirector || auth.isLeader" label="客户经理">
          <el-select v-model="form.manager_id" filterable placeholder="选择客户经理" style="width:100%">
            <el-option v-for="m in allManagers" :key="m.id" :label="m.name" :value="m.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型"><el-input v-model="form.product_type" placeholder="如：云专线、SD-WAN" /></el-form-item>
        <el-form-item label="金额"><el-input v-model="form.amount" placeholder="如：50000元/年" /></el-form-item>
        <el-form-item label="跟进内容"><el-input v-model="form.follow_up_detail" type="textarea" :rows="4" placeholder="请输入跟进详情" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="跟进中" value="跟进中" />
            <el-option label="已签约" value="已签约" />
            <el-option label="已流失" value="已流失" />
          </el-select>
        </el-form-item>
        <el-form-item label="预计列收时间">
          <el-date-picker v-model="form.expected_revenue_date" type="month" placeholder="选择月份" style="width:100%" value-format="YYYY-MM" />
        </el-form-item>
      </el-form>
      <EditLogPanel v-if="dialogMode === 'edit'" :edit-log="form.edit_log || []" />
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- Detail Dialog with Follow-up Timeline -->
    <el-dialog v-model="detailVisible" :title="selectedBusiness?.customer_name + ' — 商机跟单'" width="650px" v-if="selectedBusiness">
      <!-- Business Info -->
      <div class="detail-info">
        <div class="detail-row"><span class="detail-label">产品类型</span><span>{{ selectedBusiness.product_type }}</span></div>
        <div class="detail-row"><span class="detail-label">金额</span><span>{{ selectedBusiness.amount }}</span></div>
        <div class="detail-row"><span class="detail-label">状态</span><span :style="{ color: selectedBusiness.status === '已签约' ? '#4A6741' : selectedBusiness.status === '已流失' ? '#B8472E' : '#C4934A' }">{{ selectedBusiness.status }}</span></div>
        <div class="detail-row"><span class="detail-label">预计列收</span><span>{{ selectedBusiness.expected_revenue_date }}</span></div>
        <div class="detail-row"><span class="detail-label">客户经理</span><span class="mgr-tag" :style="getMgrStyle(selectedBusiness.manager_name, isLight)">{{ selectedBusiness.manager_name }}</span></div>
        <div class="detail-row" v-if="selectedBusiness.follow_up_detail"><span class="detail-label">商机概述</span><span>{{ selectedBusiness.follow_up_detail }}</span></div>
      </div>

      <div style="margin-top:12px">
        <el-button size="small" @click="detailVisible = false; openEdit(selectedBusiness)">编辑商机</el-button>
      </div>

      <!-- Follow-up Timeline -->
      <div class="log-section">
        <h4 class="log-title">跟进记录</h4>
        <div v-loading="logLoading" class="log-list">
          <div v-if="logs.length === 0 && !logLoading" class="log-empty">暂无跟进记录</div>
          <div v-for="l in logs" :key="l.id" class="log-item">
            <span class="log-icon">{{ logMethodIcons[l.method] || '📋' }}</span>
            <div class="log-body">
              <div class="log-header">
                <span class="log-date">{{ l.log_date }}</span>
                <span class="log-method-chip" :style="{ background: logMethodColors[l.method] || '#7B7568', color: '#fff', padding: '1px 8px', fontSize: '11px' }">{{ l.method }}</span>
                <span class="log-author">{{ l.created_by_name }}</span>
              </div>
              <div class="log-content">{{ l.content }}</div>
            </div>
            <el-button size="small" type="danger" text @click="handleDeleteLog(l.id)" class="log-del">删除</el-button>
          </div>
        </div>

        <!-- Add Log Form -->
        <div class="log-add">
          <div class="log-add-row">
            <el-date-picker v-model="logForm.log_date" type="date" value-format="YYYY-MM-DD" size="small" style="width:140px" />
            <div class="log-method-chips">
              <button v-for="m in logMethods" :key="m" type="button" class="log-chip" :class="{ 'log-chip--active': logForm.method === m }" :style="logForm.method === m ? { background: logMethodColors[m], borderColor: logMethodColors[m], color: '#fff' } : {}" @click="logForm.method = m">{{ m }}</button>
            </div>
          </div>
          <el-input v-model="logForm.content" type="textarea" :rows="2" placeholder="输入跟进内容..." size="small" style="margin-top:6px" />
          <el-button type="primary" size="small" :loading="logSaving" @click="handleCreateLog" style="margin-top:6px">添加跟进</el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.edit-indicator { font-size: 12px; margin-left: 3px; opacity: 0.5; cursor: help; }
.page-head { margin-bottom: 20px; }
.page-head-row { display: flex; justify-content: space-between; align-items: flex-start; }
.page-head-actions { display: flex; gap: 8px; align-items: center; flex-shrink: 0; }
.page-title { margin: 0; font-family: var(--font-heading); font-size: 22px; font-weight: 400; color: var(--ink); letter-spacing: 0.06em; }
.page-desc { margin: 4px 0 0; font-size: 13px; color: var(--c-text-muted); font-family: var(--font-body); }
.page-rule { width: 32px; height: 3px; background: var(--gold); margin-top: 12px; }
.summary-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 14px; padding: 10px 14px; background: var(--c-bg-light, #faf9f6); border-radius: 6px; border: 1px solid var(--c-border, #e8e5df); }
.summary-label { font-size: 12px; color: var(--c-text-muted); font-family: var(--font-body); margin-right: 4px; }
.summary-chip { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; color: var(--mgr-chip-text); white-space: nowrap; cursor: pointer; transition: opacity 0.2s, transform 0.15s; }
.summary-chip:hover { opacity: 0.8; transform: translateY(-1px); }
.summary-chip--active { outline: 2px solid var(--gold); outline-offset: 1px; }
.mgr-tag { display: inline-block; padding: 1px 9px; border-radius: 10px; font-size: 12px; color: var(--mgr-chip-text); white-space: nowrap; }
.empty { text-align: center; color: var(--c-text-muted); padding: 48px 0; font-family: var(--font-body); }
.filter-bar { margin-bottom: 16px; padding: 12px 16px; background: var(--surface); border: 1px solid var(--warm-border); }
.filter-row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-label { font-size: 13px; color: var(--warm-gray); font-family: var(--font-body); white-space: nowrap; }
.filter-count { font-size: 12px; color: var(--c-text-muted); font-family: var(--font-mono); margin-left: auto; }
.quick-create-btn { display: inline-flex; align-items: center; gap: 4px; background: none; border: 1px dashed var(--gold); padding: 6px 12px; color: var(--gold-dark); font-family: var(--font-body); font-size: 12px; cursor: pointer; transition: all 0.2s; }
.quick-create-btn:hover { border-color: var(--vermilion); color: var(--vermilion); background: rgba(184,71,46,0.03); }
.select-empty-create { padding: 8px 12px; text-align: center; }

/* ── Detail Dialog ── */
.detail-info { background: var(--c-bg-light, #faf9f6); border-radius: 6px; padding: 14px 18px; }
.detail-row { display: flex; gap: 12px; padding: 4px 0; font-size: 13px; }
.detail-label { color: var(--warm-gray); min-width: 70px; flex-shrink: 0; }

/* ── Log Timeline ── */
.log-section { margin-top: 18px; border-top: 1px solid var(--warm-border); padding-top: 14px; }
.log-title { margin: 0 0 12px; font-family: var(--font-heading); font-size: 16px; color: var(--ink); }
.log-list { display: flex; flex-direction: column; gap: 10px; max-height: 300px; overflow-y: auto; margin-bottom: 14px; }
.log-empty { text-align: center; color: var(--warm-gray); font-size: 13px; padding: 20px 0; }
.log-item { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; background: var(--surface); border: 1px solid var(--warm-border); }
.log-icon { font-size: 18px; flex-shrink: 0; margin-top: 2px; }
.log-body { flex: 1; min-width: 0; }
.log-header { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
.log-date { font-family: var(--font-mono); font-size: 12px; color: var(--ink); }
.log-author { font-size: 11px; color: var(--warm-gray); margin-left: auto; }
.log-content { font-size: 13px; color: var(--c-text); line-height: 1.6; }
.log-del { flex-shrink: 0; opacity: 0.5; }
.log-del:hover { opacity: 1; }
.log-method-chip { border-radius: 3px; white-space: nowrap; }

/* ── Add Log Form ── */
.log-add { border-top: 1px solid var(--warm-border); padding-top: 12px; }
.log-add-row { display: flex; gap: 8px; align-items: center; }
.log-method-chips { display: flex; gap: 4px; }
.log-chip { padding: 4px 10px; border: 1px solid var(--warm-border); background: var(--surface); font-size: 12px; cursor: pointer; transition: all 0.2s; }
.log-chip:hover { border-color: var(--ink); }
.log-chip--active { font-weight: 600; }
.required-star { color: var(--vermilion); font-weight: 700; }
</style>
