<template>
	<view class="fe-bottom-sheet fe-bottom-sheet--settlement" :class="{ 'fe-bottom-sheet--active': active }">
		<view class="fe-sheet-handle" />
		<view class="fe-sheet-header">
			<view class="fe-sheet-title">
				结算确认单
				<text
					v-if="view.statusLabel"
					class="fe-sheet-badge"
					:class="view.statusClass === 'success' ? 'fe-sheet-badge--success' : 'fe-sheet-badge--danger'"
				>{{ view.statusLabel }}</text>
			</view>
			<view class="fe-sheet-close" @tap="onClose">✕</view>
		</view>
		<view class="fe-sheet-source">{{ view.sourceTitle || '结算单' }}</view>

		<view v-if="loading" class="fe-settlement-empty">
			<text class="fe-settlement-empty__text">加载结算单中...</text>
		</view>
		<view v-else-if="loadError" class="fe-settlement-empty">
			<text class="fe-settlement-empty__text">{{ loadError }}</text>
			<view class="fe-btn fe-btn--primary fe-btn--sm fe-settlement-empty__btn" @tap="loadDetail">重试</view>
		</view>
		<template v-else>
			<scroll-view scroll-y class="fe-sheet-body settle-body" :show-scrollbar="false">
				<view class="fe-sheet-body__inner">
					<!-- 紫色汇总：企业总支出 + 多工种人均 / 到手 -->
					<view class="settle-hero">
						<view class="settle-hero__col">
							<text class="settle-hero__label">企业总支出</text>
							<text class="settle-hero__value">{{ view.enterpriseTotalText }}</text>
						</view>
						<view class="settle-hero__col">
							<text class="settle-hero__label">平均每人</text>
							<view
								v-for="g in view.workTypeGroups"
								:key="g.msgKey"
								class="settle-hero__line"
							>
								<text v-if="view.multiWorkType" class="settle-hero__type">{{ g.workType }}</text>
								<text class="settle-hero__value">{{ g.avgEnterpriseText }}</text>
							</view>
						</view>
						<view class="settle-hero__col">
							<text class="settle-hero__label">员工到手</text>
							<view
								v-for="g in view.workTypeGroups"
								:key="g.msgKey"
								class="settle-hero__line"
							>
								<text v-if="view.multiWorkType" class="settle-hero__type">{{ g.workType }}</text>
								<text class="settle-hero__value settle-hero__value--mint">{{ g.avgNetText }}</text>
							</view>
						</view>
					</view>

					<!-- 资金明细 -->
					<view class="settle-card">
						<text class="settle-card__title">资金明细</text>
						<view
							v-for="fee in view.fees"
							:key="fee.msgKey"
							class="settle-row"
						>
							<text class="settle-row__label">{{ fee.name }}</text>
							<text class="settle-row__value">{{ fee.amountText }}</text>
						</view>
						<view class="settle-row settle-row--total">
							<text class="settle-row__label settle-row__label--primary">企业总支出</text>
							<text class="settle-row__value settle-row__value--primary">{{ view.totalText }}</text>
						</view>
					</view>

					<!-- 员工实发：按工种 -->
					<view class="settle-card">
						<text class="settle-card__title">员工实发</text>
						<view
							v-for="g in view.workTypeGroups"
							:key="g.msgKey"
							class="settle-payout"
						>
							<text v-if="view.multiWorkType" class="settle-payout__type">{{ g.workType }}</text>
							<view class="settle-row">
								<text class="settle-row__label">实发总额（{{ g.workerCountText }}）</text>
								<text class="settle-row__value settle-row__value--mint">{{ g.netTotalText }}</text>
							</view>
							<view class="settle-row">
								<text class="settle-row__label">人均到手</text>
								<text class="settle-row__value">{{ g.avgNetText }}</text>
							</view>
						</view>
					</view>

					<!-- 合规标签 -->
					<view class="settle-tags">
						<view
							v-for="tag in view.complianceTags"
							:key="tag.msgKey"
							class="settle-tag"
						>
							<text class="settle-tag__text">✓ {{ tag.text }}</text>
						</view>
					</view>
					<view class="settle-compliance">
						<text class="settle-compliance__text">✓ {{ view.complianceRemark }}</text>
					</view>
				</view>
			</scroll-view>

			<view class="fe-sheet-footer">
				<!-- 无导出按钮；只读/已支付仅关闭，待支付确认并支付 -->
				<view
					v-if="!canPayAction"
					class="fe-btn fe-btn--secondary fe-btn--lg fe-btn--full"
					@tap="onClose"
				>{{ readonly ? '已结算 · 关闭' : '关闭' }}</view>
				<view
					v-else-if="paying"
					class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full fe-settlement-btn--disabled"
				>支付中...</view>
				<view
					v-else
					class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full"
					@tap="onConfirmPay"
				>确认并支付</view>
			</view>
		</template>
	</view>
</template>

<script>
import { showToast } from '@/common/chat-data.js'
import { getOrderSettlement, confirmPaySettlement, startSettlement } from '@/api/order.js'
import { getDraftDetail } from '@/api/draft.js'
import { mapSettlementSummary } from '@/utils/settlement.js'
import { normalizeWorkerGroups, mapDraftDetailToCard } from '@/utils/draft.js'

const EMPTY_VIEW = {
	sourceTitle: '',
	statusLabel: '待支付',
	statusClass: 'danger',
	enterpriseTotalText: '¥0.00',
	netText: '¥0.00',
	deductionText: '-¥0.00',
	grossText: '¥0.00',
	totalText: '¥0.00',
	fees: [],
	workTypeGroups: [],
	multiWorkType: false,
	complianceTags: [],
	complianceRemark: '',
	canPay: false
}

export default {
	name: 'FeSettlementSheet',
	props: {
		active: { type: Boolean, default: false },
		orderId: { type: [Number, String], default: null },
		draftId: { type: [Number, String], default: null },
		/** 流程已完成：仅查看，禁止支付 */
		readonly: { type: Boolean, default: false }
	},
	data() {
		return {
			loading: false,
			loadError: '',
			paying: false,
			view: Object.assign({}, EMPTY_VIEW),
			draftGroups: [],
			draftTitle: ''
		}
	},
	computed: {
		canPayAction() {
			return !this.readonly && !!this.view.canPay
		}
	},
	watch: {
		active(val) {
			if (val) this.loadDetail()
		},
		orderId() {
			if (this.active) this.loadDetail()
		},
		draftId() {
			if (this.active) this.loadDetail()
		}
	},
	methods: {
		toast: showToast,
		onClose() {
			this.$emit('close')
		},
		async loadDraftGroups() {
			this.draftGroups = []
			this.draftTitle = ''
			if (this.draftId == null || this.draftId === '') return
			try {
				const detail = await getDraftDetail(this.draftId, { showError: false })
				const card = mapDraftDetailToCard(detail || {})
				this.draftGroups = normalizeWorkerGroups(detail || {})
				this.draftTitle = (card && card.title) || (detail && detail.title) || ''
			} catch (e) {
				this.draftGroups = []
			}
		},
		async loadDetail() {
			if (this.orderId == null || this.orderId === '') {
				this.view = Object.assign({}, EMPTY_VIEW)
				this.loadError = '缺少订单信息'
				return
			}
			this.loading = true
			this.loadError = ''
			try {
				await this.loadDraftGroups()
				let raw = null
				try {
					raw = await getOrderSettlement(this.orderId, { showError: false })
				} catch (e) {
					// 只读查看不发起结算；否则尚无结算单时尝试发起（幂等）
					if (this.readonly) throw e
					try {
						raw = await startSettlement(this.orderId, { allowBeforeEndDate: false }, { showError: false })
					} catch (e2) {
						throw e
					}
				}
				this.view = mapSettlementSummary(raw || {}, {
					workerGroups: this.draftGroups,
					title: this.draftTitle
				})
			} catch (e) {
				this.view = Object.assign({}, EMPTY_VIEW)
				this.loadError = (e && (e.msg || e.message)) || '结算单加载失败'
				showToast(this.loadError)
			} finally {
				this.loading = false
			}
		},
		async onConfirmPay() {
			if (this.readonly) {
				showToast('结算已完成，仅可查看')
				return
			}
			if (this.paying || !this.canPayAction) return
			if (this.orderId == null || this.orderId === '') {
				showToast('缺少订单信息')
				return
			}
			this.paying = true
			try {
				const raw = await confirmPaySettlement(
					this.orderId,
					{ paymentChannel: 'wechat' },
					{ showError: true }
				)
				this.view = mapSettlementSummary(raw || {}, {
					workerGroups: this.draftGroups,
					title: this.draftTitle
				})
				showToast((raw && raw.message) || '支付完成')
				this.$emit('paid', {
					orderId: this.orderId,
					settlementId: this.view.settlementId,
					draftId: this.draftId
				})
			} catch (e) {
				// request 已 toast
			} finally {
				this.paying = false
			}
		}
	}
}
</script>

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

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

.fe-sheet-close {
	font-size: 32rpx;
	color: $fe-muted;
	padding: 8rpx 12rpx;
	line-height: 1;
}

.fe-sheet-badge--danger {
	background: #EF4444;
}

.fe-sheet-badge--success {
	background: #10B981;
}

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

.settle-hero {
	display: flex;
	gap: 12rpx;
	padding: 28rpx 20rpx;
	border-radius: $fe-radius-md;
	background: linear-gradient(135deg, #7C3AED 0%, #6D28D9 100%);
	margin-bottom: 24rpx;
	box-sizing: border-box;
}

.settle-hero__col {
	flex: 1;
	min-width: 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
}

.settle-hero__label {
	font-size: 22rpx;
	color: rgba(255, 255, 255, 0.78);
}

.settle-hero__line {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 2rpx;
}

.settle-hero__type {
	font-size: 20rpx;
	color: rgba(255, 255, 255, 0.7);
	max-width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.settle-hero__value {
	font-size: 28rpx;
	font-weight: 700;
	color: #fff;
	line-height: 1.25;
	word-break: break-all;
	text-align: center;
}

.settle-hero__value--mint {
	color: #A7F3D0;
}

.settle-card {
	background: $fe-gray-50;
	border-radius: $fe-radius-md;
	padding: 24rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid $fe-border-light;
	box-sizing: border-box;
}

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

.settle-payout + .settle-payout {
	margin-top: 20rpx;
	padding-top: 16rpx;
	border-top: 1rpx dashed $fe-border-light;
}

.settle-payout__type {
	display: block;
	font-size: 24rpx;
	font-weight: 700;
	color: $fe-primary;
	margin-bottom: 10rpx;
}

.settle-row {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 16rpx;
	padding: 10rpx 0;
}

.settle-row--total {
	margin-top: 8rpx;
	padding-top: 16rpx;
	border-top: 1rpx solid $fe-border-light;
}

.settle-row__label {
	font-size: 26rpx;
	color: $fe-muted;
	flex: 1;
	min-width: 0;
}

.settle-row__label--primary {
	color: $fe-primary;
	font-weight: 700;
}

.settle-row__value {
	font-size: 26rpx;
	font-weight: 700;
	color: $fe-foreground;
	flex-shrink: 0;
}

.settle-row__value--primary {
	color: $fe-primary;
}

.settle-row__value--mint {
	color: #059669;
}

.settle-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	margin-bottom: 16rpx;
}

.settle-tag {
	padding: 8rpx 16rpx;
	border-radius: 999rpx;
	background: #D1FAE5;
}

.settle-tag__text {
	font-size: 22rpx;
	color: #047857;
	font-weight: 600;
}

.settle-compliance {
	padding: 16rpx 20rpx;
	border-radius: $fe-radius-md;
	background: #ECFDF5;
	margin-bottom: 8rpx;
}

.settle-compliance__text {
	font-size: 24rpx;
	color: #047857;
	line-height: 1.5;
	font-weight: 600;
}

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

.fe-settlement-empty__text {
	display: block;
	font-size: 28rpx;
	color: #94A3B8;
}

.fe-settlement-empty__btn {
	margin: 28rpx auto 0;
	display: inline-flex;
}

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