<script setup lang="ts">
/**
 * 销项发票管理页 (AR)
 * 多条件查询 + 回款标记 + 新增 + 导出
 */
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus, Search, Download } from '@element-plus/icons-vue'
import request from '@/api/request'
import { useUserStore } from '@/store/user'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'

const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.data_scope === 'all' || (userStore.userInfo?.role_name || '').toLowerCase() === 'admin')

// --- 客户搜索 ---
interface CustomerOption { id: string; name: string; level: string; contact: string | null }
const customerOptions = ref<CustomerOption[]>([])
const customerSearchLoading = ref(false)
const handleCustomerSearch = async (query: string) => {
    if (!query) { 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 loading = ref(false)
const tableData = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const filters = reactive({
    customer_name: '',
    invoice_number: '',
    payment_status: '',
    dateRange: null as [string, string] | null,
})

const fetchList = async () => {
    loading.value = true
    try {
        const params: Record<string, any> = {
            page: currentPage.value,
            size: pageSize.value,
        }
        if (filters.customer_name) params.customer_name = filters.customer_name
        if (filters.invoice_number) params.invoice_number = filters.invoice_number
        if (filters.payment_status) params.payment_status = filters.payment_status
        if (filters.dateRange?.[0]) params.start_date = filters.dateRange[0]
        if (filters.dateRange?.[1]) params.end_date = filters.dateRange[1]

        const res: any = await request.get('/api/finance/sales-invoices', { params })
        tableData.value = res.items || []
        total.value = res.total || 0
    } catch {
        //
    } finally {
        loading.value = false
    }
}

const handleSearch = () => { currentPage.value = 1; fetchList() }
const handleReset = () => {
    filters.customer_name = ''
    filters.invoice_number = ''
    filters.payment_status = ''
    filters.dateRange = null
    handleSearch()
}

// --- 新增 ---
const addDialogVisible = ref(false)
const addSubmitting = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = reactive({
    issuer: '',
    receiver_customer_id: '',
    invoice_number: '',
    amount: 0,
    billing_date: '',
    remark: '',
})
const addFormRules = {
    issuer: [{ required: true, message: '请输入开票方', trigger: 'blur' }],
    receiver_customer_id: [{ required: true, message: '请选择受票客户', trigger: 'change' }],
    invoice_number: [{ required: true, message: '请输入发票号', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入票面金额', trigger: 'blur' }],
    billing_date: [{ required: true, message: '请选择开票日期', trigger: 'change' }],
}

const openAddDialog = () => {
    addForm.issuer = ''
    addForm.receiver_customer_id = ''
    addForm.invoice_number = ''
    addForm.amount = 0
    addForm.billing_date = ''
    addForm.remark = ''
    customerOptions.value = []
    addDialogVisible.value = true
}

const submitAdd = async () => {
    if (!addFormRef.value) return
    const valid = await addFormRef.value.validate().catch(() => false)
    if (!valid) return
    addSubmitting.value = true
    try {
        await request.post('/api/finance/sales-invoices', addForm)
        ElMessage.success('销项发票创建成功')
        addDialogVisible.value = false
        handleSearch()
    } catch {
        //
    } finally {
        addSubmitting.value = false
    }
}

// --- OCR 解析上传（支持批量） ---
const uploadProcessing = ref(false)
const aiParsing = ref(false)
let uploadAbortController: AbortController | null = null

interface OcrQueueItem {
  name: string
  status: 'waiting' | 'processing' | 'success' | 'error'
  message: string
}
const ocrQueue = ref<OcrQueueItem[]>([])

const handleOCRUpload = async (_file: UploadFile, fileList: any[]) => {
    const rawFiles = fileList.filter((f: any) => f.raw).map((f: any) => f.raw as File)
    if (!rawFiles.length) return

    // 单文件：填入表单（旧逻辑）
    if (rawFiles.length === 1) {
        const file = rawFiles[0]
        uploadProcessing.value = true
        aiParsing.value = true
        uploadAbortController = new AbortController()
        try {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('scene', 'invoice')
            const token = userStore.token || localStorage.getItem('crm_token') || ''
            const response = await fetch('/api/finance/ocr', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` },
                body: formData,
                signal: uploadAbortController.signal,
            })
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
            const result = await response.json()
            if (result.code !== 200) throw new Error(result.message || 'OCR 识别失败')
            const aiData = result.data?.ocr_data || {}
            ElMessage.success('🤖 AI 识别成功，数据已尝试填入表单')
            addForm.issuer = aiData.seller_name || aiData.merchant || aiData.merchant_name || addForm.issuer
            addForm.invoice_number = aiData.invoice_num || aiData.invoice_number || addForm.invoice_number
            addForm.amount = parseFloat(aiData.amount) || addForm.amount
            addForm.billing_date = aiData.date || addForm.billing_date
            const buyerName = (aiData.buyer_name || aiData.customer_name || '').replace(/[\r\n\t]/g, '').trim()
            if (buyerName) {
                await handleCustomerSearch(buyerName)
                if (customerOptions.value.length > 0) {
                    addForm.receiver_customer_id = customerOptions.value[0].id
                    ElMessage.success(`已自动匹配并选中受票客户: ${customerOptions.value[0].name}`)
                } else {
                    ElMessage.warning(`AI提取受票方为「${buyerName}」，但系统中未找到该客户。`)
                }
            }
        } catch (e: any) {
            if (e.name === 'AbortError') return
            ElMessage.warning('AI 解析失败或服务不可用，请手动填写。')
        } finally {
            uploadProcessing.value = false
            aiParsing.value = false
            uploadAbortController = null
        }
        return
    }

    // 多文件：批量处理，逐个 OCR + 自动创建
    ocrQueue.value = rawFiles.map(f => ({ name: f.name, status: 'waiting' as const, message: '' }))
    uploadProcessing.value = true
    uploadAbortController = new AbortController()
    const signal = uploadAbortController.signal

    for (let i = 0; i < rawFiles.length; i++) {
        if (signal.aborted) break

        const file = rawFiles[i]
        ocrQueue.value[i].status = 'processing'
        ocrQueue.value[i].message = '🤖 解析中...'

        try {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('scene', 'invoice')
            const token = userStore.token || localStorage.getItem('crm_token') || ''
            const response = await fetch('/api/finance/ocr', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` },
                body: formData,
                signal,
            })
            if (!response.ok) throw new Error(`HTTP ${response.status}`)
            const result = await response.json()
            if (result.code !== 200) throw new Error(result.message || 'OCR 失败')

            const aiData = result.data?.ocr_data || {}
            const issuer = aiData.seller_name || aiData.merchant || aiData.merchant_name || ''
            const invoiceNumber = aiData.invoice_num || aiData.invoice_number || ''
            const amount = parseFloat(aiData.amount) || 0
            const billingDate = aiData.date || new Date().toISOString().split('T')[0]
            const buyerName = (aiData.buyer_name || aiData.customer_name || '').replace(/[\r\n\t]/g, '').trim()

            // 自动查找客户
            let customerId = ''
            if (buyerName) {
                await handleCustomerSearch(buyerName)
                if (customerOptions.value.length > 0) customerId = customerOptions.value[0].id
            }

            if (issuer && invoiceNumber && amount > 0 && customerId) {
                await request.post('/api/finance/sales-invoices', {
                    issuer, receiver_customer_id: customerId, invoice_number: invoiceNumber,
                    amount, billing_date: billingDate, remark: 'AI批量导入',
                })
                ocrQueue.value[i].status = 'success'
                ocrQueue.value[i].message = `✅ ${invoiceNumber}`
            } else {
                ocrQueue.value[i].status = 'error'
                ocrQueue.value[i].message = '⚠️ 数据不完整，请手动创建'
            }
        } catch (e: any) {
            if (e.name === 'AbortError') break
            ocrQueue.value[i].status = 'error'
            ocrQueue.value[i].message = `❌ ${e.message || '失败'}`
        }
    }

    uploadProcessing.value = false
    uploadAbortController = null
    if (!signal.aborted) {
        const ok = ocrQueue.value.filter(q => q.status === 'success').length
        ElMessage.success(`批量处理完成：${ok}/${rawFiles.length} 自动创建成功`)
        handleSearch()
    }
    setTimeout(() => { ocrQueue.value = [] }, 5000)
}

// --- Dialog 关闭保护 ---
const handleDialogClose = (done: () => void) => {
    if (uploadProcessing.value) {
        ElMessageBox.confirm(
            'OCR 批量处理正在进行中，关闭将中断所有未完成的任务。确定关闭？',
            '提示',
            { confirmButtonText: '确认关闭', cancelButtonText: '继续等待', type: 'warning' }
        ).then(() => {
            if (uploadAbortController) { uploadAbortController.abort(); uploadAbortController = null }
            uploadProcessing.value = false
            ocrQueue.value = []
            done()
        }).catch(() => {})
    } else {
        done()
    }
}

// --- 回款标记 ---
const paymentDialogVisible = ref(false)
const paymentSubmitting = ref(false)
const paymentFormRef = ref<FormInstance>()
const paymentForm = reactive({
    id: '',
    payment_status: '已结清' as string,
    payment_amount: 0,
    payment_date: '',
})

const openPaymentDialog = (row: any) => {
    paymentForm.id = row.id
    paymentForm.payment_status = row.payment_status === '已结清' ? '已结清' : '已结清'
    paymentForm.payment_amount = row.amount
    paymentForm.payment_date = new Date().toISOString().split('T')[0]
    paymentDialogVisible.value = true
}

const submitPayment = async () => {
    paymentSubmitting.value = true
    try {
        await request.put(`/api/finance/sales-invoices/${paymentForm.id}`, {
            payment_status: paymentForm.payment_status,
            payment_amount: paymentForm.payment_amount,
            payment_date: paymentForm.payment_date,
        })
        ElMessage.success('回款状态更新成功')
        paymentDialogVisible.value = false
        fetchList()
    } catch {
        //
    } finally {
        paymentSubmitting.value = false
    }
}

// --- 导出 ---
const handleExport = async () => {
    try {
        const params: any = {}
        if (filters.customer_name) params.customer_name = filters.customer_name
        if (filters.invoice_number) params.invoice_number = filters.invoice_number
        if (filters.payment_status) params.payment_status = filters.payment_status
        if (filters.dateRange?.[0]) params.start_date = filters.dateRange[0]
        if (filters.dateRange?.[1]) params.end_date = filters.dateRange[1]

        const res = await request.get('/api/finance/sales-invoices/export', {
            params,
            responseType: 'blob'
        })
        const blob = new Blob([res as any], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `sales_invoices_${new Date().toISOString().split('T')[0]}.xlsx`
        a.click()
        window.URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
    } catch {
        ElMessage.error('导出失败')
    }
}

// --- 状态标签颜色 ---
const statusTag = (status: string) => {
    if (status === '已结清') return 'success'
    if (status === '部分回款') return 'warning'
    return 'danger'
}

onMounted(fetchList)
</script>

<template>
    <div class="sales-invoice-container">
        <!-- 筛选栏 -->
        <el-card shadow="never" class="filter-card">
            <div class="filter-bar">
                <el-form :inline="true" @submit.prevent>
                    <el-form-item label="客户名称">
                        <el-input v-model="filters.customer_name" placeholder="客户名称" clearable style="width: 160px" />
                    </el-form-item>
                    <el-form-item label="发票号">
                        <el-input v-model="filters.invoice_number" placeholder="发票号" clearable style="width: 160px" />
                    </el-form-item>
                    <el-form-item label="回款状态">
                        <el-select v-model="filters.payment_status" placeholder="全部" clearable style="width: 120px">
                            <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="filters.dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始"
                            end-placeholder="结束"
                            value-format="YYYY-MM-DD"
                            style="width: 240px"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
                <div class="actions">
                    <el-button type="success" :icon="Plus" @click="openAddDialog">新增发票</el-button>
                    <el-button v-if="isAdmin" type="warning" :icon="Download" @click="handleExport">导出</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="invoice_number" label="发票号" width="180" show-overflow-tooltip />
                <el-table-column prop="issuer" label="开票方" width="180" show-overflow-tooltip />
                <el-table-column prop="customer_name" label="受票客户" width="180" show-overflow-tooltip />
                <el-table-column prop="amount" label="票面金额" width="120" align="right">
                    <template #default="{ row }">¥ {{ Number(row.amount).toLocaleString() }}</template>
                </el-table-column>
                <el-table-column prop="billing_date" label="开票日期" width="120" align="center" />
                <el-table-column prop="payment_status" label="回款状态" width="110" align="center">
                    <template #default="{ row }">
                        <el-tag :type="statusTag(row.payment_status)" effect="light">{{ row.payment_status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="payment_amount" label="已回款" width="120" align="right">
                    <template #default="{ row }">¥ {{ Number(row.payment_amount || 0).toLocaleString() }}</template>
                </el-table-column>
                <el-table-column prop="payment_date" label="回款日期" width="120" align="center" />
                <el-table-column label="操作" width="120" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-if="row.payment_status !== '已结清'"
                            type="primary"
                            link
                            size="small"
                            @click="openPaymentDialog(row)"
                        >回款标记</el-button>
                        <span v-else style="color: #67c23a; font-size: 12px">已结清</span>
                    </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, sizes, prev, pager, next"
                    :page-sizes="[10, 20, 50]"
                    @current-change="fetchList"
                    @size-change="handleSearch"
                />
            </div>
        </el-card>

        <!-- 新增发票弹窗 -->
        <el-dialog v-model="addDialogVisible" title="发票智能录入" width="600px" destroy-on-close :before-close="handleDialogClose">
            <div style="margin-bottom: 20px" v-loading="uploadProcessing || aiParsing" :element-loading-text="uploadProcessing ? '文件上传中...' : '🤖 AI 正在识别发票表单字段...'">
                <el-upload
                    drag
                    :auto-upload="false"
                    :show-file-list="false"
                    accept=".pdf,.jpg,.jpeg,.png"
                    multiple
                    @change="handleOCRUpload"
                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将发票原件(PDF/图片)拖到此处，或 <em>点击上传进行AI填单</em>
                    </div>
                    <div class="el-upload__tip" style="font-size:12px;color:#909399">支持 PDF/图片/MD 文件。单文件自动填入表单，多文件自动批量创建发票</div>
                </el-upload>
                <!-- 批量处理队列 -->
                <div v-if="ocrQueue.length" style="margin-top: 10px">
                    <div v-for="(item, idx) in ocrQueue" :key="idx" style="display:flex; justify-content:space-between; align-items:center; padding: 4px 8px; border-bottom: 1px solid #f0f0f0; font-size: 13px">
                        <span style="color:#606266; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:280px">{{ item.name }}</span>
                        <el-tag v-if="item.status === 'waiting'" size="small" type="info" effect="plain">等待中</el-tag>
                        <el-tag v-else-if="item.status === 'processing'" size="small" type="warning" effect="dark">处理中</el-tag>
                        <el-tag v-else-if="item.status === 'success'" size="small" type="success" effect="dark">{{ item.message }}</el-tag>
                        <el-tag v-else size="small" type="danger" effect="dark">{{ item.message }}</el-tag>
                    </div>
                </div>
            </div>
            
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
                <el-form-item label="开票方" prop="issuer">
                    <el-input v-model="addForm.issuer" placeholder="我方公司名称" />
                </el-form-item>
                <el-form-item label="受票客户" prop="receiver_customer_id">
                    <el-select
                        v-model="addForm.receiver_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"
                        >
                            <span>{{ item.name }}</span>
                            <span style="color: #999; font-size: 12px; margin-left: 8px">{{ item.level }}级</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发票号" prop="invoice_number">
                    <el-input v-model="addForm.invoice_number" placeholder="INV-20260312-001" />
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="票面金额" prop="amount">
                            <el-input-number v-model="addForm.amount" :min="0.01" :precision="2" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开票日期" prop="billing_date">
                            <el-date-picker v-model="addForm.billing_date" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注">
                    <el-input v-model="addForm.remark" type="textarea" :rows="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="addSubmitting" @click="submitAdd">确认创建</el-button>
            </template>
        </el-dialog>

        <!-- 回款标记弹窗 -->
        <el-dialog v-model="paymentDialogVisible" title="回款标记" width="450px" destroy-on-close>
            <el-form ref="paymentFormRef" :model="paymentForm" label-width="100px">
                <el-form-item label="回款状态">
                    <el-select v-model="paymentForm.payment_status" style="width: 100%">
                        <el-option label="部分回款" value="部分回款" />
                        <el-option label="已结清" value="已结清" />
                    </el-select>
                </el-form-item>
                <el-form-item label="回款金额">
                    <el-input-number v-model="paymentForm.payment_amount" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
                <el-form-item label="回款日期">
                    <el-date-picker v-model="paymentForm.payment_date" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="paymentDialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="paymentSubmitting" @click="submitPayment">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.sales-invoice-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;
    flex-wrap: wrap;
    gap: 12px;
}
.actions { display: flex; gap: 8px; }
.table-card { border: none; border-radius: 8px; }
.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
</style>
