<template>
	<view class="fe-bottom-sheet fe-bottom-sheet--invoice" :class="{ 'fe-bottom-sheet--active': active }">
		<view class="fe-sheet-handle" />
		<view class="fe-sheet-header">
			<view class="fe-sheet-title">📄 开票归档</view>
			<view class="fe-sheet-close" @tap="onClose">✕</view>
		</view>
		<view v-if="view.sourceTitle" class="fe-sheet-source inv-source">🔗 {{ view.sourceTitle }}</view>

		<view v-if="loading" class="inv-empty">
			<text class="inv-empty__text">加载开票信息中...</text>
		</view>
		<view v-else-if="loadError" class="inv-empty">
			<text class="inv-empty__text">{{ loadError }}</text>
			<view class="fe-btn fe-btn--primary fe-btn--sm" @tap="loadDetail">重试</view>
		</view>
		<template v-else>
			<scroll-view scroll-y class="fe-sheet-body inv-body" :show-scrollbar="false">
				<view class="fe-sheet-body__inner">
					<!-- 金额三卡 -->
					<view class="inv-stats">
						<view class="inv-stat inv-stat--purple">
							<text class="inv-stat__num">{{ view.billableText }}</text>
							<text class="inv-stat__label">可开票金额</text>
						</view>
						<view class="inv-stat inv-stat--green">
							<text class="inv-stat__num">{{ view.invoicedText }}</text>
							<text class="inv-stat__label">已开票金额</text>
						</view>
						<view class="inv-stat inv-stat--yellow">
							<text class="inv-stat__num">{{ view.pendingText }}</text>
							<text class="inv-stat__label">待开票金额</text>
						</view>
					</view>

					<!-- 开票信息 -->
					<view class="inv-section">
						<text class="inv-section__title">开票信息</text>
						<view class="inv-card">
							<view class="inv-row">
								<text class="inv-row__label">发票类型</text>
								<text class="inv-row__value">{{ view.invoiceTypeText }}</text>
							</view>
							<view class="inv-row">
								<text class="inv-row__label">税率</text>
								<text class="inv-row__value">{{ view.taxRateText }}</text>
							</view>
							<view class="inv-row">
								<text class="inv-row__label">开票金额</text>
								<text class="inv-row__value inv-row__value--primary">{{ view.invoiceAmountText }}</text>
							</view>
							<view class="inv-row">
								<text class="inv-row__label">税额</text>
								<text class="inv-row__value">{{ view.taxAmountText }}</text>
							</view>
							<view class="inv-row">
								<text class="inv-row__label">价税合计</text>
								<text class="inv-row__value">{{ view.totalWithTaxText }}</text>
							</view>
						</view>
					</view>

					<!-- 开票抬头 -->
					<view class="inv-section">
						<text class="inv-section__title">开票抬头</text>
						<view class="inv-card inv-card--form">
							<view class="fe-form-group">
								<text class="fe-form-label">企业名称</text>
								<input
									class="fe-form-input"
									:class="{ 'fe-form-input--readonly': !canSubmitAction }"
									v-model="form.companyName"
									:disabled="!canSubmitAction"
									placeholder="请输入企业名称"
								/>
							</view>
							<view class="fe-form-group">
								<text class="fe-form-label">统一社会信用代码</text>
								<input
									class="fe-form-input"
									:class="{ 'fe-form-input--readonly': !canSubmitAction }"
									v-model="form.creditCode"
									:disabled="!canSubmitAction"
									placeholder="请输入统一社会信用代码"
								/>
							</view>
							<view class="fe-form-group">
								<text class="fe-form-label">开户银行及账号</text>
								<input
									class="fe-form-input"
									:class="{ 'fe-form-input--readonly': !canSubmitAction }"
									v-model="form.bankAccountInfo"
									:disabled="!canSubmitAction"
									placeholder="请输入开户银行及账号"
								/>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="fe-sheet-footer">
				<view
					v-if="!canSubmitAction"
					class="fe-btn fe-btn--secondary fe-btn--lg fe-btn--full"
					@tap="onClose"
				>已归档 · 关闭</view>
				<view
					v-else-if="submitting"
					class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full inv-btn--disabled"
				>提交中...</view>
				<view
					v-else
					class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full"
					@tap="onSubmit"
				>申请开票</view>
			</view>
		</template>
	</view>
</template>

<script>
import { showToast } from '@/common/chat-data.js'
import { getOrderInvoice, archiveOrderInvoice } from '@/api/order.js'
import { getDraftDetail } from '@/api/draft.js'
import { mapOrderInvoice } from '@/utils/invoice.js'
import { mapDraftDetailToCard } from '@/utils/draft.js'

const EMPTY_VIEW = {
	sourceTitle: '',
	billableText: '¥0',
	invoicedText: '¥0',
	pendingText: '¥0',
	invoiceType: 'vat_special',
	invoiceTypeText: '增值税专用发票',
	taxRate: 0.06,
	taxRateText: '6%',
	invoiceAmount: 0,
	invoiceAmountText: '¥0',
	taxAmount: 0,
	taxAmountText: '¥0',
	totalWithTax: 0,
	totalWithTaxText: '¥0',
	archived: false,
	canSubmit: true
}

export default {
	name: 'FeInvoiceSheet',
	props: {
		active: { type: Boolean, default: false },
		orderId: { type: [Number, String], default: null },
		draftId: { type: [Number, String], default: null },
		sourceTitle: { type: String, default: '' },
		/** 流程已完成：仅查看，禁止申请开票 */
		readonly: { type: Boolean, default: false }
	},
	data() {
		return {
			loading: false,
			loadError: '',
			submitting: false,
			orderIdInner: null,
			view: Object.assign({}, EMPTY_VIEW),
			form: {
				companyName: '',
				creditCode: '',
				bankAccountInfo: ''
			}
		}
	},
	computed: {
		canSubmitAction() {
			return !this.readonly && !!this.view.canSubmit
		}
	},
	watch: {
		active(val) {
			if (val) this.loadDetail()
		},
		orderId() {
			if (this.active) this.loadDetail()
		},
		draftId() {
			if (this.active) this.loadDetail()
		}
	},
	methods: {
		onClose() {
			this.$emit('close')
		},
		async resolveOrderId() {
			if (this.orderId != null && this.orderId !== '') return this.orderId
			if (this.draftId == null || this.draftId === '') return null
			try {
				const draftRaw = await getDraftDetail(this.draftId, { showError: false })
				if (!draftRaw) return null
				return draftRaw.orderId != null && draftRaw.orderId !== ''
					? draftRaw.orderId
					: (draftRaw.order_id != null && draftRaw.order_id !== '' ? draftRaw.order_id : null)
			} catch (e) {
				return null
			}
		},
		async resolveSourceTitle(orderId) {
			if (this.sourceTitle) return this.sourceTitle
			if (this.draftId == null || this.draftId === '') return ''
			try {
				const draftRaw = await getDraftDetail(this.draftId, { showError: false })
				const card = mapDraftDetailToCard(draftRaw || {})
				const title = (card && card.title) || (draftRaw && draftRaw.title) || ''
				const no = (draftRaw && (draftRaw.orderNo || draftRaw.order_no))
					|| (card && card.orderNo)
					|| ''
				if (title && no) return `${title} ${no}`
				return title || (no ? `订单 ${no}` : '')
			} catch (e) {
				return orderId != null ? `订单 #${orderId}` : ''
			}
		},
		async loadDetail() {
			this.loading = true
			this.loadError = ''
			this.submitting = false
			this.view = Object.assign({}, EMPTY_VIEW)
			this.form = { companyName: '', creditCode: '', bankAccountInfo: '' }
			try {
				const orderId = await this.resolveOrderId()
				this.orderIdInner = orderId
				if (orderId == null || orderId === '') {
					this.loadError = '缺少订单信息'
					return
				}
				const sourceTitle = await this.resolveSourceTitle(orderId)
				const raw = await getOrderInvoice(orderId, { showError: false })
				const mapped = mapOrderInvoice(raw || {}, { sourceTitle })
				this.view = mapped
				this.form = {
					companyName: mapped.companyName || '',
					creditCode: mapped.creditCode || '',
					bankAccountInfo: mapped.bankAccountInfo || ''
				}
			} catch (e) {
				this.loadError = (e && (e.msg || e.message)) || '开票信息加载失败'
				showToast(this.loadError)
			} finally {
				this.loading = false
			}
		},
		async onSubmit() {
			if (this.readonly) {
				showToast('开票已归档，仅可查看')
				return
			}
			if (!this.canSubmitAction || this.submitting) return
			const orderId = this.orderIdInner
			if (orderId == null || orderId === '') {
				showToast('缺少订单信息')
				return
			}
			const companyName = (this.form.companyName || '').trim()
			const creditCode = (this.form.creditCode || '').trim()
			if (!companyName) {
				showToast('请填写企业名称')
				return
			}
			if (!creditCode) {
				showToast('请填写统一社会信用代码')
				return
			}

			this.submitting = true
			try {
				const res = await archiveOrderInvoice(orderId, {
					companyName,
					creditCode,
					bankAccountInfo: (this.form.bankAccountInfo || '').trim(),
					invoiceType: this.view.invoiceType || 'vat_special',
					taxRate: this.view.taxRate,
					invoiceAmount: this.view.invoiceAmount,
					taxAmount: this.view.taxAmount,
					totalWithTax: this.view.totalWithTax,
					taxCleared: true,
					invoiceIssued: true
				}, { showError: true })
				showToast((res && (res.message || res.msg)) || '开票申请已提交')
				this.$emit('success', {
					orderId,
					draftId: this.draftId,
					result: res
				})
				this.onClose()
			} catch (e) {
				if (e && e.__handled) return
			} finally {
				this.submitting = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.fe-bottom-sheet--invoice {
	max-height: 90vh;
}

.fe-sheet-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.fe-sheet-close {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	background: $fe-gray-100;
	color: $fe-muted;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.inv-source {
	padding: 0 40rpx 8rpx;
}

.inv-body {
	max-height: 62vh;
}

.inv-empty {
	padding: 80rpx 32rpx;
	text-align: center;
}

.inv-empty__text {
	display: block;
	font-size: 28rpx;
	color: #94A3B8;
	margin-bottom: 24rpx;
}

.inv-stats {
	display: flex;
	gap: 16rpx;
	margin-bottom: 28rpx;
}

.inv-stat {
	flex: 1;
	min-width: 0;
	border-radius: $fe-radius-md;
	padding: 24rpx 12rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
}

.inv-stat--purple {
	background: #EDE9FE;
}

.inv-stat--green {
	background: #D1FAE5;
}

.inv-stat--yellow {
	background: #FEF3C7;
}

.inv-stat__num {
	font-size: 28rpx;
	font-weight: 800;
	color: $fe-foreground;
	line-height: 1.2;
}

.inv-stat__label {
	font-size: 20rpx;
	color: $fe-muted;
}

.inv-section {
	margin-bottom: 28rpx;
}

.inv-section__title {
	display: block;
	font-size: 28rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 16rpx;
}

.inv-card {
	background: $fe-gray-50;
	border-radius: $fe-radius-md;
	padding: 8rpx 24rpx;
	border: 1rpx solid $fe-border-light;
	box-sizing: border-box;
}

.inv-card--form {
	padding: 24rpx;
}

.inv-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1rpx solid $fe-border-light;
}

.inv-row:last-child {
	border-bottom: none;
}

.inv-row__label {
	font-size: 26rpx;
	color: $fe-muted;
}

.inv-row__value {
	font-size: 26rpx;
	font-weight: 600;
	color: $fe-foreground;
	text-align: right;
	max-width: 60%;
}

.inv-row__value--primary {
	color: $fe-primary;
	font-weight: 700;
}

.fe-form-group {
	margin-bottom: 20rpx;
}

.fe-form-group:last-child {
	margin-bottom: 0;
}

.fe-form-input--readonly {
	background: $fe-gray-100;
	color: $fe-gray-700;
	opacity: 1;
}

.inv-btn--disabled {
	opacity: 0.55;
	pointer-events: none;
}
</style>
