<script setup lang="ts">
/**
 * 销售日志列表页 (V5.0 升级)
 * 支持查看所有日志，可以通过传入 customer_id 过滤特定客户的日志
 * 客户关联使用异步远程搜索选择器
 * V5.0: 增加联系人级联多选 + contact_ids 传参
 */
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import request from '@/api/request'
import { useUserStore } from '@/store/user'

const route = useRoute()
const userStore = useUserStore()

// --- 客户搜索选择器 ---
interface CustomerOption {
    id: string
    name: string
    level: string
    contact: string | null
    phone: string | null
}

const customerOptions = ref<CustomerOption[]>([])
const customerSearchLoading = ref(false)

const handleCustomerSearch = async (query: string) => {
    if (!query || query.length < 1) {
        customerOptions.value = []
        return
    }
    customerSearchLoading.value = true
    try {
        const res: any = await request.get('/api/customers/search', { params: { q: query } })
        customerOptions.value = res || []
    } catch {
        customerOptions.value = []
    } finally {
        customerSearchLoading.value = false
    }
}

// --- 关联联系人 ---
const contactOptions = ref<any[]>([])
const loadingContacts = ref(false)

const loadContacts = async (customerId: string) => {
    if (!customerId) {
        contactOptions.value = []
        return
    }
    loadingContacts.value = true
    try {
        const res: any = await request.get(`/api/customers/${customerId}/contacts`)
        contactOptions.value = res || []
    } catch {
    } finally {
        loadingContacts.value = false
    }
}


// --- 列表状态 ---
const loading = ref(false)
const tableData = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const customerIdQuery = ref<string>((route.query.customer_id as string) || '')
const customerNameQuery = ref<string>((route.query.customer_name as string) || '')

// 客户名称映射缓存（用于列表显示）
const customerNameMap = ref<Record<string, string>>({})

const fetchLogs = async () => {
    loading.value = true
    try {
        const params: Record<string, any> = {
            page: currentPage.value,
            size: pageSize.value,
            start_date: dateRange.value?.[0] || '',
            end_date: dateRange.value?.[1] || ''
        }
        if (customerIdQuery.value) {
            params.customer_id = customerIdQuery.value
        }
        const res: any = await request.get('/api/sales-logs', { params })
        tableData.value = res.items || []
        total.value = res.total || 0

        // 获取日志中涉及的客户名称
        const unknownIds = (res.items || [])
            .map((item: any) => item.customer_id)
            .filter((id: string | null) => id && !customerNameMap.value[id])
        if (unknownIds.length > 0) {
            // 批量查名称：逐个 search（数量通常很少）
            for (const id of [...new Set(unknownIds)] as string[]) {
                try {
                    const detail: any = await request.get(`/api/customers/${id}`)
                    if (detail?.name) {
                        customerNameMap.value[id] = detail.name
                    }
                } catch {
                    // 客户可能被删除
                    customerNameMap.value[id] = '(已删除)'
                }
            }
        }
    } catch {
        // 已统一处理报错
    } finally {
        loading.value = false
    }
}

const getCustomerName = (customerId: string | null) => {
    if (!customerId) return '--'
    return customerNameMap.value[customerId] || customerId.slice(0, 8) + '...'
}

// 筛选时间范围
const dateRange = ref<[string, string] | null>(null)

const handleSearch = () => {
    currentPage.value = 1
    fetchLogs()
}

const handleReset = () => {
    dateRange.value = null
    customerIdQuery.value = ''
    customerNameQuery.value = ''
    handleSearch()
}

// --- 新建日志弹窗 ---
const dialogVisible = ref(false)
const dialogSubmitting = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
    customer_id: customerIdQuery.value || '',
    contact_ids: [] as string[],
    content: ''
})

const formRules = {
    content: [{ required: true, message: '请输入跟进日志内容', trigger: 'blur' }]
}

// watch 必须放在 form 声明之后（避免 TDZ）
watch(() => form.customer_id, (newVal) => {
    if (newVal) {
        loadContacts(newVal)
    } else {
        contactOptions.value = []
    }
    form.contact_ids = []
})

const openAddDialog = () => {
    form.customer_id = customerIdQuery.value || ''
    form.contact_ids = []
    form.content = ''
    // 如果有预置的客户，加载到选择器选项中
    if (customerIdQuery.value && customerNameQuery.value) {
        customerOptions.value = [{
            id: customerIdQuery.value,
            name: customerNameQuery.value,
            level: '',
            contact: null,
            phone: null
        }]
        // 主动加载该客户的联系人
        loadContacts(customerIdQuery.value)
    }
    dialogVisible.value = true
}

const submitForm = async () => {
    if (!formRef.value) return
    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) return

    dialogSubmitting.value = true
    try {
        await request.post('/api/sales-logs', {
            content: form.content,
            customer_id: form.customer_id || undefined,
            contact_ids: form.contact_ids.length > 0 ? form.contact_ids : undefined,
            log_date: new Date().toISOString().split('T')[0]
        })
        ElMessage.success('写跟进成功！AI 将在后台提炼客户特征。')
        dialogVisible.value = false

        // 缓存已选客户名称
        if (form.customer_id) {
            const selected = customerOptions.value.find(c => c.id === form.customer_id)
            if (selected) {
                customerNameMap.value[form.customer_id] = selected.name
            }
        }
        handleSearch()
    } catch {
        // ...
    } finally {
        dialogSubmitting.value = false
    }
}

onMounted(() => {
    fetchLogs()
})
</script>

<template>
    <div class="sales-logs-container">
        <!-- 筛选栏 -->
        <el-card shadow="never" class="filter-card">
            <div class="filter-bar">
                <el-form :inline="true" @submit.prevent>
                    <el-form-item label="跟进日期">
                        <el-date-picker
                            v-model="dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="指定客户" v-if="customerNameQuery">
                        <el-tag closable @close="handleReset" type="primary">{{ customerNameQuery }}</el-tag>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset" v-if="dateRange || customerIdQuery">重置</el-button>
                    </el-form-item>
                </el-form>
                <div class="actions">
                    <el-button type="success" :icon="Plus" @click="openAddDialog">写跟进</el-button>
                </div>
            </div>
        </el-card>

        <!-- 表格部分 -->
        <el-card shadow="never" class="table-card">
            <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
                <el-table-column prop="log_date" label="跟进日期" width="120" align="center" />
                <el-table-column label="关联客户" width="200">
                    <template #default="scope">
                        <span>{{ getCustomerName(scope.row.customer_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="跟进内容" min-width="400">
                    <template #default="scope">
                        <div class="log-content-cell">{{ scope.row.content }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="AI 画像状态" width="160" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.ai_processed" type="success" effect="light">已提取画像</el-tag>
                        <el-tag v-else type="info" effect="light">--</el-tag>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :total="total"
                    layout="total, prev, pager, next"
                    @current-change="fetchLogs"
                />
            </div>
        </el-card>

        <!-- 弹窗：写跟进 -->
        <el-dialog v-model="dialogVisible" title="填写销售跟进记录" width="600px" destroy-on-close>
            <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" label-position="top">
                <el-alert 
                    title="智能化录入" 
                    type="info" 
                    description="请直接记录沟通细节，后台 AI 将自动抽取出【核心痛点】、【偏好】及【购买意向】更新至客户档案。"
                    show-icon 
                    style="margin-bottom: 20px"
                    :closable="false"
                />
                <el-form-item label="关联客户">
                    <el-select
                        v-model="form.customer_id"
                        filterable
                        remote
                        clearable
                        reserve-keyword
                        placeholder="输入客户名称搜索..."
                        :remote-method="handleCustomerSearch"
                        :loading="customerSearchLoading"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in customerOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                            <div style="display: flex; justify-content: space-between; align-items: center">
                                <span>{{ item.name }}</span>
                                <span style="color: #999; font-size: 12px; margin-left: 12px">
                                    {{ item.level }}级 {{ item.contact || '' }}
                                </span>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联联系人" v-if="form.customer_id">
                    <el-select
                        v-model="form.contact_ids"
                        multiple
                        placeholder="（选填）选择拜访的联系人"
                        style="width: 100%"
                        :loading="loadingContacts"
                    >
                        <el-option
                            v-for="item in contactOptions"
                            :key="item.id"
                            :label="item.name + (item.title ? ` - ${item.title}` : '')"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="跟进纪要" prop="content">
                    <el-input 
                        v-model="form.content" 
                        type="textarea" 
                        :rows="6" 
                        placeholder="例如：今天下午拜访了张总，客户表示目前对价格比较敏感，需要我们下周出具一套具备更高性价比的报价方案。重点决策人是王工。" 
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="dialogSubmitting" @click="submitForm">提交并触发 AI 提取</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.sales-logs-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
}
.filter-card {
    border: none;
    border-radius: 8px;
}
.filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}
.table-card {
    border: none;
    border-radius: 8px;
}
.log-content-cell {
    white-space: pre-wrap;
    word-break: break-all;
    line-height: 1.5;
    color: #303133;
}
.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
</style>
