import { StatusTag } from '../vehicle-management/components/StatusTag';
import {
	ROLE_OPTIONS,
	TASK_STAGE_META,
	PIPELINE_STEPS,
	DEPT_KEYS,
	readRole,
	writeRole,
	deptProgress,
	pipelineIndex,
	settlementLabel,
	canSeeSettlement,
	hasPendingForRole,
	fmtMoney,
	fmtYMDHM,
	buildDeptFeeDetail,
	isDeptSubmitted
} from './vrsV2Data.js';

function stageTone(stage) {
	var meta = TASK_STAGE_META[stage];
	return (meta && meta.tone) || 'gray';
}

function PipelineStepper(props) {
	var activeIndex = props.activeIndex || 0;
	return React.createElement('ol', { className: 'vrs2-pipeline', 'aria-label': '任务进度' },
		PIPELINE_STEPS.map(function (step, idx) {
			var cls = 'vrs2-pipeline__step';
			if (idx < activeIndex) cls += ' vrs2-pipeline__step--done';
			else if (idx === activeIndex) cls += ' vrs2-pipeline__step--current';
			return React.createElement('li', { key: step.key, className: cls },
				React.createElement('span', { className: 'vrs2-pipeline__dot', 'aria-hidden': true }),
				React.createElement('span', { className: 'vrs2-pipeline__label' }, step.label)
			);
		})
	);
}

function KpiCards(props) {
	var stats = props.stats || {};
	var cards = [
		{ key: 'deposit', label: '保证金总额', value: stats.deposit, tone: 'neutral' },
		{ key: 'pending', label: '待结算总额', value: stats.pending, tone: 'warn' },
		{ key: 'refund', label: '应退还总额', value: stats.refund, tone: 'good' },
		{ key: 'pay', label: '应补缴总额', value: stats.pay, tone: 'danger' }
	];
	return React.createElement('div', { className: 'vrs2-kpi-row' },
		cards.map(function (c) {
			return React.createElement('div', { key: c.key, className: 'vrs2-kpi-card vrs2-kpi-card--' + c.tone },
				React.createElement('div', { className: 'vrs2-kpi-card__label' }, c.label),
				React.createElement('div', { className: 'vrs2-kpi-card__value tabular-nums' },
					c.value,
					React.createElement('span', { className: 'vrs2-kpi-card__unit' }, '元')
				)
			);
		})
	);
}

const Component = function (props) {
	var useState = React.useState;
	var useMemo = React.useMemo;
	var antd = window.antd;
	var App = antd.App;
	var Table = antd.Table;
	var Button = antd.Button;
	var Select = antd.Select;
	var Tabs = antd.Tabs;
	var message = antd.message;

	var row = (props && props.row) || {};
	var _role = useState(readRole());
	var role = _role[0];
	var setRole = _role[1];
	var deptData = useMemo(buildDeptFeeDetail, []);
	var progress = useMemo(function () { return deptProgress(row); }, [row]);
	var activePipe = useMemo(function () { return pipelineIndex(row.taskStage); }, [row.taskStage]);

	var stats = useMemo(function () {
		var deposit = fmtMoney(row.deposit || 10000);
		var pending = row.pendingTotal != null ? fmtMoney(row.pendingTotal) : '—';
		var refund = row.settlementDirection === 'refund' ? fmtMoney(row.settlementAmount) : '0.00';
		var pay = row.settlementDirection === 'pay' ? fmtMoney(row.settlementAmount) : '0.00';
		if (row.pendingTotal != null && row.deposit != null && !row.settlementDirection) {
			var diff = row.deposit - row.pendingTotal;
			if (diff > 0) refund = fmtMoney(diff);
			else if (diff < 0) pay = fmtMoney(Math.abs(diff));
		}
		return { deposit: deposit, pending: pending, refund: refund, pay: pay };
	}, [row]);

	function handleRoleChange(next) {
		setRole(next);
		writeRole(next);
	}

	function canSeeDept(deptKey) {
		if (role === 'biz') return true;
		return role === deptKey;
	}

	function renderDeptOverviewCards() {
		return React.createElement('div', { className: 'vrs2-dept-overview-row' },
			progress.map(function (p) {
				return React.createElement('div', { key: p.key, className: 'vrs2-dept-overview-card' },
					React.createElement('div', { className: 'vrs2-dept-overview-card__title' }, p.label),
					React.createElement(StatusTag, {
						label: p.status,
						tone: p.done ? 'green' : (p.active ? 'blue' : 'amber')
					}),
					React.createElement('div', { className: 'vrs2-dept-overview-card__meta' },
						p.name ? '提交人：' + p.name : '尚未提交'
					)
				);
			})
		);
	}

	function renderBizSection() {
		var d = deptData.biz;
		return React.createElement('section', { className: 'vm-table-card vrs2-dept-panel', key: 'biz' },
			React.createElement('header', { className: 'vrs2-dept-panel__head' },
				React.createElement('h3', null, '业务管理组费用'),
				React.createElement('div', { className: 'vrs2-dept-panel__meta' },
					React.createElement('span', { className: 'tabular-nums' }, '总金额 ', React.createElement('strong', null, d.total), ' 元'),
					React.createElement(StatusTag, { label: d.status, tone: 'blue' })
				)
			),
			React.createElement(Table, {
				className: 'vm-list-table',
				rowKey: 'key',
				size: 'small',
				pagination: false,
				dataSource: d.rows,
				columns: [
					{ title: '序号', dataIndex: 'seq', width: 56 },
					{ title: '费用项', dataIndex: 'feeItem', width: 160 },
					{ title: '金额', dataIndex: 'amount', width: 96, className: 'tabular-nums' },
					{ title: '来源', dataIndex: 'source', width: 88, render: function (v) { return React.createElement('span', { className: 'vrs2-source-tag' }, v); } },
					{ title: '最后更新', dataIndex: 'updatedAt', width: 148, className: 'tabular-nums' }
				]
			}),
			role === 'biz' && !isDeptSubmitted(row, 'biz') ? React.createElement('div', { className: 'vrs2-dept-panel__actions' },
				React.createElement(Button, { size: 'small' }, '保存'),
				React.createElement(Button, { type: 'primary', size: 'small' }, '提交本部门费用')
			) : null
		);
	}

	function renderEnergySection() {
		var d = deptData.energy;
		return React.createElement('section', { className: 'vm-table-card vrs2-dept-panel', key: 'energy' },
			React.createElement('header', { className: 'vrs2-dept-panel__head' },
				React.createElement('h3', null, '能源部费用'),
				React.createElement('div', { className: 'vrs2-dept-panel__meta' },
					React.createElement('span', { className: 'tabular-nums' }, '总金额 ', React.createElement('strong', null, d.total), ' 元'),
					React.createElement(StatusTag, { label: d.status, tone: 'amber' })
				)
			),
			React.createElement('div', { className: 'vrs2-field-grid' },
				d.fields.map(function (f) {
					return React.createElement('div', { key: f.label, className: 'vrs2-field' },
						React.createElement('span', { className: 'vrs2-field__label' }, f.label),
						React.createElement('span', { className: 'vrs2-field__value' },
							f.value,
							f.source ? React.createElement('span', { className: 'vrs2-source-tag' }, f.source) : null
						)
					);
				})
			),
			role === 'energy' ? React.createElement('div', { className: 'vrs2-dept-panel__actions' },
				React.createElement(Button, { size: 'small' }, '保存'),
				React.createElement(Button, { type: 'primary', size: 'small' }, '提交本部门费用')
			) : null
		);
	}

	function renderOpsSection() {
		var d = deptData.ops;
		return React.createElement('section', { className: 'vm-table-card vrs2-dept-panel', key: 'ops' },
			React.createElement('header', { className: 'vrs2-dept-panel__head' },
				React.createElement('h3', null, '运维部费用'),
				React.createElement('div', { className: 'vrs2-dept-panel__meta' },
					React.createElement('span', { className: 'tabular-nums' }, '总金额 ', React.createElement('strong', null, d.total), ' 元'),
					React.createElement(StatusTag, { label: d.status, tone: 'amber' })
				)
			),
			React.createElement(Table, {
				className: 'vm-list-table',
				rowKey: 'key',
				size: 'small',
				pagination: false,
				dataSource: d.rows,
				columns: [
					{ title: '序号', dataIndex: 'seq', width: 56 },
					{ title: '费用项', dataIndex: 'feeItem', width: 140 },
					{ title: '金额', dataIndex: 'amount', width: 96, className: 'tabular-nums' },
					{ title: '来源', dataIndex: 'source', width: 100, render: function (v) { return React.createElement('span', { className: 'vrs2-source-tag' }, v); } },
					{ title: '无忧包减免', dataIndex: 'discount', width: 96, className: 'tabular-nums' }
				]
			}),
			role === 'ops' ? React.createElement('div', { className: 'vrs2-dept-panel__actions' },
				React.createElement(Button, { size: 'small' }, '保存'),
				React.createElement(Button, { type: 'primary', size: 'small' }, '提交本部门费用')
			) : null
		);
	}

	function renderSafetySection() {
		var d = deptData.safety;
		return React.createElement('section', { className: 'vm-table-card vrs2-dept-panel', key: 'safety' },
			React.createElement('header', { className: 'vrs2-dept-panel__head' },
				React.createElement('h3', null, '安全部费用'),
				React.createElement('div', { className: 'vrs2-dept-panel__meta' },
					React.createElement('span', { className: 'tabular-nums' }, '总金额 ', React.createElement('strong', null, d.total), ' 元'),
					React.createElement(StatusTag, { label: d.status, tone: 'amber' })
				)
			),
			React.createElement(Table, {
				className: 'vm-list-table',
				rowKey: 'key',
				size: 'small',
				pagination: false,
				dataSource: d.feeRows,
				columns: [
					{ title: '序号', dataIndex: 'seq', width: 56 },
					{ title: '费用项', dataIndex: 'feeItem', width: 140 },
					{ title: '金额', dataIndex: 'amount', width: 96, className: 'tabular-nums' },
					{ title: '来源', dataIndex: 'source', width: 100, render: function (v) { return React.createElement('span', { className: 'vrs2-source-tag' }, v); } }
				]
			}),
			React.createElement('h4', { className: 'vrs2-subtitle' }, '违章清单（来自违章管理）'),
			React.createElement(Table, {
				className: 'vm-list-table',
				rowKey: 'key',
				size: 'small',
				pagination: false,
				dataSource: d.violations,
				columns: [
					{ title: '违章编码', dataIndex: 'code', width: 160 },
					{ title: '违法行为', dataIndex: 'act', ellipsis: true },
					{ title: '罚款', dataIndex: 'fine', width: 80, className: 'tabular-nums' },
					{ title: '是否处理', dataIndex: 'handled', width: 88 }
				]
			}),
			role === 'safety' ? React.createElement('div', { className: 'vrs2-dept-panel__actions' },
				React.createElement(Button, { size: 'small' }, '保存'),
				React.createElement(Button, { type: 'primary', size: 'small' }, '提交本部门费用')
			) : null
		);
	}

	function renderFeeWorkspace() {
		if (role === 'biz') {
			var tabItems = DEPT_KEYS.map(function (d) {
				var renderFn = renderBizSection;
				if (d.key === 'energy') renderFn = renderEnergySection;
				if (d.key === 'ops') renderFn = renderOpsSection;
				if (d.key === 'safety') renderFn = renderSafetySection;
				return { key: d.key, label: d.label, children: renderFn() };
			});
			return React.createElement('div', { className: 'vrs2-fee-workspace' },
				canSeeSettlement(role) ? KpiCards({ stats: stats }) : null,
				React.createElement(Tabs, { items: tabItems, defaultActiveKey: 'biz' })
			);
		}
		if (role === 'energy') return renderEnergySection();
		if (role === 'ops') return renderOpsSection();
		if (role === 'safety') return renderSafetySection();
		if (role === 'finance') {
			return React.createElement('div', { className: 'vm-table-card vrs2-closure-panel' },
				React.createElement('h3', null, '收付款闭环'),
				row.billNo ? React.createElement('p', null, '关联账单：', React.createElement('strong', null, row.billNo)) : React.createElement('p', { className: 'vrs2-muted' }, '尚未生成账单'),
				row.paymentRef ? React.createElement('p', null, '关联付款记录：', React.createElement('strong', null, row.paymentRef)) : null,
				row.taskStage === 'pending_payment' ? React.createElement(Button, { type: 'primary', onClick: function () { message.info('跳转付款记录（原型）'); } }, '登记付款') : null
			);
		}
		return null;
	}

	function renderFooterActions() {
		var stage = row.taskStage;
		var actions = [];
		if (role === 'biz' && stage === 'pending_main_approval' && row.slaReady) {
			actions.push(React.createElement(Button, { key: 'approve', type: 'primary', onClick: function () { message.success('已发起总审批（原型）'); } }, '发起总审批'));
		}
		if (role === 'biz' && stage === 'pending_reconcile') {
			actions.push(React.createElement(Button, { key: 'bill', type: 'primary', onClick: function () { message.info('生成账单（原型）'); } }, '生成账单'));
		}
		if (role === 'finance' && stage === 'approving' && row.financePending) {
			actions.push(React.createElement(Button, { key: 'fa', type: 'primary', onClick: function () { message.info('跳转审批待办（原型）'); } }, '财务终审'));
		}
		if (hasPendingForRole(row, role) && ['energy', 'ops', 'safety', 'biz'].indexOf(role) >= 0 && stage === 'pending_dept') {
			actions.push(React.createElement(Button, { key: 'submit', type: 'primary' }, '提交本部门费用'));
		}
		actions.push(React.createElement(Button, { key: 'back', onClick: function () { if (props.onBack) props.onBack(); } }, '返回列表'));
		return actions;
	}

	var stageMeta = TASK_STAGE_META[row.taskStage] || { label: row.taskStage };

	return React.createElement(App, null,
		React.createElement('div', { className: 'vm-page lc-page vrs2-page vrs2-detail-page' },
			React.createElement('header', { className: 'vrs2-detail-topbar' },
				React.createElement('div', { className: 'vrs2-detail-topbar__left' },
					React.createElement('button', {
						type: 'button',
						className: 'vm-btn vm-btn-back',
						onClick: function () { if (props.onBack) props.onBack(); }
					}, '返回'),
					React.createElement('div', { className: 'vrs2-detail-title-block' },
						React.createElement('h1', { className: 'vrs2-detail-title' }, row.plateNo, ' · ', row.customerName),
						React.createElement(StatusTag, { label: stageMeta.label, tone: stageTone(row.taskStage) })
					)
				),
				React.createElement('div', { className: 'vrs2-role-switch' },
					React.createElement('span', { className: 'vrs2-role-switch__label' }, '预览角色'),
					React.createElement(Select, {
						value: role,
						style: { width: 160 },
						options: ROLE_OPTIONS,
						onChange: handleRoleChange
					})
				)
			),

			React.createElement(PipelineStepper, { activeIndex: activePipe }),

			React.createElement('section', { className: 'vm-filter-card ldb-filter-card vrs2-overview-banner' },
				React.createElement('div', { className: 'vrs2-overview-grid' },
					React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, '合同'), React.createElement('strong', null, row.contractCode)),
					React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, '项目'), row.projectName),
					React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, '还车时间'), fmtYMDHM(row.returnTime)),
					React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, '还车人'), row.returnPerson),
					React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, 'E签归档'), row.esignStatus || '—'),
					canSeeSettlement(role) && row.settlementDirection
						? React.createElement('div', null, React.createElement('span', { className: 'vrs2-overview-label' }, '结算'), settlementLabel(row))
						: null
				),
				React.createElement('button', {
					type: 'button',
					className: 'vm-btn vm-btn-ghost vrs2-link-btn',
					'data-vm-icon': 'eye',
					onClick: function () { message.info('跳转还车管理查看页（原型）'); }
				}, '查看还车记录 →')
			),

			React.createElement('section', { className: 'vrs2-section' },
				React.createElement('h2', { className: 'vrs2-section__title' }, '四部门进度'),
				renderDeptOverviewCards()
			),

			React.createElement('section', { className: 'vrs2-section' },
				React.createElement('h2', { className: 'vrs2-section__title' }, role === 'finance' ? '财务闭环' : '费用工作台'),
				renderFeeWorkspace()
			),

			(row.billNo || row.paymentRef) && role !== 'finance' ? React.createElement('section', { className: 'vm-table-card vrs2-closure-panel' },
				React.createElement('h3', null, '闭环信息'),
				row.billNo ? React.createElement('p', null, '账单编号：', row.billNo) : null,
				row.paymentRef ? React.createElement('p', null, '付款记录：', row.paymentRef) : null
			) : null,

			React.createElement('footer', { className: 'vrs2-detail-footer' }, renderFooterActions())
		)
	);
};

export default Component;
