import React from 'react';
import { Select, InputNumber, Input, Image, Cascader, Button, DatePicker, Popover, Checkbox, Modal } from 'antd';
import dayjs from 'dayjs';
import { ChevronDown, Plus, Trash2, Copy } from 'lucide-react';
import {
	getLessorCompanies,
	getLessorCompanyById,
	getLeaseCustomerById,
	getCustomerInvoicePreview,
	getLessorAccountPreview,
	getLessorContactPreview,
	getCustomerContactPreview,
	getCustomerAttachmentPreviewUrl,
	MOCK_LEASE_CUSTOMERS,
	DEFAULT_MILEAGE_STANDARD,
	MILEAGE_PERIOD_OPTIONS,
	CUSTOMER_CREDENTIAL_ITEMS,
	DEFAULT_FEE_INFO,
	PAYMENT_PERIOD_OPTIONS,
	HYDROGEN_PAYMENT_METHOD_OPTIONS,
	CONTRACT_CODE_PREFIX,
} from '../contract-template-management/contract-template-vars.js';
import {
	buildBrandModelCascaderOptions,
	createEmptyLeaseOrderRow,
	createDefaultLeaseOrderState,
	createEmptyDelegateRow,
	createDefaultPowerOfAttorneyState,
	PROVINCE_CITY_CASCADER_OPTIONS,
	LEASE_EXTRA_SERVICE_CATALOG,
	calcRentServiceSubtotal,
	countLeaseOrderRows,
	normalizeExtraServices,
	getReadyVehiclePlateOptions,
	sumExtraServiceFees,
	calcLeaseOrderKpis,
	formatKpiAmount,
	getExtraServiceNames,
} from './lease-order-vars.js';

function LeaseOrderServiceContentField(props) {
	var selected = props.value || [];
	var onChange = props.onChange;
	var modalOpenState = React.useState(false);
	var draftState = React.useState([]);
	var modalOpen = modalOpenState[0];
	var setModalOpen = modalOpenState[1];
	var draft = draftState[0];
	var setDraft = draftState[1];
	var serviceNames = getExtraServiceNames(selected);

	function openModal() {
		setDraft(selected.slice());
		setModalOpen(true);
	}

	function handleCancel() {
		setModalOpen(false);
	}

	function toggleDraftValue(value) {
		setDraft(function (prev) {
			if (prev.indexOf(value) >= 0) {
				return prev.filter(function (item) { return item !== value; });
			}
			return prev.concat([value]);
		});
	}

	function handleConfirm() {
		onChange(draft.slice());
		setModalOpen(false);
	}

	return React.createElement('div', { className: 'lc-lease-order-service-field' },
		React.createElement('div', {
			className: 'lc-form-readonly lc-form-readonly--synced lc-lease-order-service-field__display',
			'aria-label': '服务内容',
			'aria-readonly': 'true',
		},
			serviceNames.length
				? React.createElement('ul', { className: 'lc-lease-order-service-field__list' },
					serviceNames.map(function (name, index) {
						return React.createElement('li', { key: selected[index] || name }, name);
					}),
				)
				: React.createElement('span', { className: 'lc-form-readonly__empty' }, '—'),
		),
		React.createElement(Button, {
			type: 'default',
			size: 'small',
			className: 'lc-lease-order-service-field__pick-btn',
			onClick: openModal,
		}, '选择服务项'),
		React.createElement(Modal, {
			title: '选择服务内容',
			open: modalOpen,
			onCancel: handleCancel,
			onOk: handleConfirm,
			okText: '确定',
			cancelText: '取消',
			mask: true,
			centered: true,
			width: 520,
			className: 'lc-lease-order-service-modal',
			destroyOnClose: true,
		},
			React.createElement('div', { className: 'lc-lease-order-service-modal__table-wrap', role: 'region', 'aria-label': '服务内容列表' },
				React.createElement('table', { className: 'lc-lease-order-service-modal__table' },
					React.createElement('thead', null,
						React.createElement('tr', null,
							React.createElement('th', { scope: 'col', className: 'lc-lease-order-service-modal__col-check' }, '多选'),
							React.createElement('th', { scope: 'col' }, '费用项'),
							React.createElement('th', { scope: 'col', className: 'lc-lease-order-service-modal__col-fee' }, '元/月'),
						),
					),
					React.createElement('tbody', null,
						LEASE_EXTRA_SERVICE_CATALOG.map(function (item) {
							var checked = draft.indexOf(item.value) >= 0;
							return React.createElement('tr', { key: item.value },
								React.createElement('td', { className: 'lc-lease-order-service-modal__col-check' },
									React.createElement(Checkbox, {
										checked: checked,
										onChange: function () { toggleDraftValue(item.value); },
										'aria-label': '选择' + item.name,
									}),
								),
								React.createElement('td', null, item.name),
								React.createElement('td', { className: 'lc-lease-order-service-modal__col-fee tabular-nums' }, item.fee),
							);
						}),
					),
				),
			),
		),
	);
}

function LeaseOrderAmountField(props) {
	return React.createElement('div', { className: 'lc-form-inline-sentence lc-lease-order-table__amount' },
		React.createElement('div', { className: 'lc-lease-order-table__amount-field' }, props.children),
		React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '元'),
	);
}

function LeaseOrderRowActions(props) {
	var rowId = props.rowId;
	var onCopy = props.onCopy;
	var onRemove = props.onRemove;
	var copyCountState = React.useState(1);
	var popoverOpenState = React.useState(false);
	var copyCount = copyCountState[0];
	var setCopyCount = copyCountState[1];
	var popoverOpen = popoverOpenState[0];
	var setPopoverOpen = popoverOpenState[1];

	function handleOpenChange(open) {
		setPopoverOpen(open);
		if (open) setCopyCount(1);
	}

	function handleConfirmCopy() {
		var count = copyCount != null ? Math.max(1, Math.floor(copyCount)) : 1;
		onCopy(rowId, count);
		setPopoverOpen(false);
		setCopyCount(1);
	}

	var popoverContent = React.createElement('div', { className: 'lc-lease-order-copy-popover' },
		React.createElement('p', { className: 'lc-lease-order-copy-popover__title' }, '复制品牌车型'),
		React.createElement('label', { className: 'lc-lease-order-copy-popover__field' },
			React.createElement('span', { className: 'lc-lease-order-copy-popover__label' }, '复制条数'),
			React.createElement(InputNumber, {
				className: 'lc-form-number vm-focus-border',
				controls: false,
				min: 1,
				step: 1,
				precision: 0,
				value: copyCount,
				onChange: function (v) { setCopyCount(v != null ? v : 1); },
				'aria-label': '复制条数',
			}),
		),
		React.createElement('div', { className: 'lc-lease-order-copy-popover__actions' },
			React.createElement(Button, {
				size: 'small',
				onClick: function () { setPopoverOpen(false); },
			}, '取消'),
			React.createElement(Button, {
				size: 'small',
				type: 'primary',
				onClick: handleConfirmCopy,
			}, '确定'),
		),
	);

	return React.createElement('div', { className: 'lc-lease-order-editor__actions' },
		React.createElement(Popover, {
			trigger: 'click',
			placement: 'leftTop',
			open: popoverOpen,
			onOpenChange: handleOpenChange,
			content: popoverContent,
		},
			React.createElement('button', {
				type: 'button',
				className: 'lc-lease-order-editor__action-btn lc-lease-order-editor__copy-btn',
				'aria-label': '复制该行品牌车型',
			}, React.createElement(Copy, { size: 14, 'aria-hidden': true })),
		),
		React.createElement('button', {
			type: 'button',
			className: 'lc-lease-order-editor__action-btn lc-lease-order-editor__remove-btn',
			onClick: function () { onRemove(rowId); },
			'aria-label': '删除该行',
		}, React.createElement(Trash2, { size: 14, 'aria-hidden': true })),
	);
}

function LeaseOrderEditor(props) {
	var order = props.order || createDefaultLeaseOrderState();
	var onChange = props.onChange;
	var rows = order.rows || [];

	function patchOrder(patch) {
		onChange(Object.assign({}, order, patch));
	}

	function withSyncedVehicleCount(nextRows) {
		return {
			rows: nextRows,
			insuredVehicleCount: countLeaseOrderRows(nextRows),
		};
	}

	function updateRows(nextRows) {
		patchOrder(withSyncedVehicleCount(nextRows));
	}

	function updateRow(id, patch) {
		updateRows(rows.map(function (row) {
			if (row.id !== id) return row;
			var next = Object.assign({}, row, patch);
			if ('rent' in patch || 'extraServices' in patch) {
				next.rentServiceSubtotal = calcRentServiceSubtotal(next.rent, normalizeExtraServices(next));
			}
			return next;
		}));
	}

	function addRow() {
		updateRows(rows.concat([createEmptyLeaseOrderRow()]));
	}

	function removeRow(id) {
		if (rows.length <= 1) {
			updateRows([createEmptyLeaseOrderRow()]);
			return;
		}
		updateRows(rows.filter(function (row) { return row.id !== id; }));
	}

	function copyRow(id, count) {
		var sourceIndex = -1;
		var sourceRow = null;
		for (var i = 0; i < rows.length; i++) {
			if (rows[i].id === id) {
				sourceIndex = i;
				sourceRow = rows[i];
				break;
			}
		}
		if (sourceIndex < 0 || !sourceRow) return;
		var brandModel = sourceRow.brandModel ? sourceRow.brandModel.slice() : [];
		var copies = [];
		for (var c = 0; c < count; c++) {
			var nextRow = createEmptyLeaseOrderRow();
			nextRow.brandModel = brandModel.slice();
			copies.push(nextRow);
		}
		var nextRows = rows.slice();
		nextRows.splice.apply(nextRows, [sourceIndex + 1, 0].concat(copies));
		updateRows(nextRows);
	}

	var cascaderOptions = buildBrandModelCascaderOptions();
	var deliveryDateValue = order.deliveryDate ? dayjs(order.deliveryDate) : null;
	var insuredVehicleCount = countLeaseOrderRows(rows);
	var orderKpis = calcLeaseOrderKpis(rows);

	React.useEffect(function () {
		if (order.insuredVehicleCount === insuredVehicleCount) return;
		patchOrder({ insuredVehicleCount: insuredVehicleCount });
	}, [rows.length]);

	return React.createElement('div', { className: 'lc-lease-order-editor' },
		React.createElement('div', { className: 'lc-lease-order-kpi-row vm-kpi-row', role: 'group', 'aria-label': '订单费用汇总' },
			React.createElement('div', { className: 'vm-kpi-card lc-lease-order-kpi-card' },
				React.createElement('span', { className: 'vm-kpi-main' },
					React.createElement('span', { className: 'vm-kpi-eyebrow' }, '租金及服务费含税总价'),
					React.createElement('span', { className: 'vm-kpi-val tabular-nums' }, formatKpiAmount(orderKpis.rentServiceTaxTotal)),
				),
			),
			React.createElement('div', { className: 'vm-kpi-card lc-lease-order-kpi-card' },
				React.createElement('span', { className: 'vm-kpi-main' },
					React.createElement('span', { className: 'vm-kpi-eyebrow' }, '保证金总计'),
					React.createElement('span', { className: 'vm-kpi-val tabular-nums' }, formatKpiAmount(orderKpis.depositTotal)),
				),
			),
			React.createElement('div', { className: 'vm-kpi-card lc-lease-order-kpi-card' },
				React.createElement('span', { className: 'vm-kpi-main' },
					React.createElement('span', { className: 'vm-kpi-eyebrow' }, '首期租金及服务费含税'),
					React.createElement('span', { className: 'vm-kpi-val tabular-nums' }, formatKpiAmount(orderKpis.firstPeriodRentService)),
				),
			),
		),
		React.createElement('div', { className: 'lc-lease-order-editor__summary lc-form-grid lc-form-grid--pair' },
			React.createElement(FormField, { label: '租赁车辆数' },
				React.createElement('div', { className: 'lc-form-inline-sentence' },
					React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '租赁车辆含保险总计'),
					React.createElement('div', { className: 'lc-form-inline-sentence__readonly' },
						React.createElement(ReadonlyValue, {
							value: insuredVehicleCount > 0 ? String(insuredVehicleCount) : '',
							label: '租赁车辆含保险总计',
						}),
					),
					React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '辆'),
				),
			),
			React.createElement(FormField, { label: '保险金额/辆', required: true },
				React.createElement('div', { className: 'lc-form-inline-sentence' },
					React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '三者责任险'),
					React.createElement(InputNumber, {
						className: 'lc-form-number lc-form-inline-sentence__input vm-focus-border',
						controls: false,
						min: 0,
						step: 0.01,
						precision: 2,
						value: order.thirdPartyLiabilityMillion,
						onChange: function (v) { patchOrder({ thirdPartyLiabilityMillion: v }); },
						'aria-label': '三者责任险金额',
					}),
					React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '万元、车损'),
				),
			),
		),
		React.createElement('div', { className: 'lc-lease-order-editor__table-wrap', role: 'region', 'aria-label': '租赁订单车辆列表' },
			React.createElement('table', { className: 'lc-lease-order-editor__table' },
				React.createElement('thead', null,
					React.createElement('tr', { className: 'lc-lease-order-editor__head-row' },
						React.createElement('th', { rowSpan: 2, scope: 'col', className: 'lc-lease-order-editor__th-brand' }, '品牌 / 车型'),
						React.createElement('th', { rowSpan: 2, scope: 'col' }, '车牌号'),
						React.createElement('th', { rowSpan: 2, scope: 'col', className: 'lc-lease-order-editor__th-subtotal' }, '租金及服务费小计（元/月/辆，含税）'),
						React.createElement('th', { colSpan: 3, scope: 'colgroup', className: 'lc-lease-order-editor__th-group' }, '价格及服务内容'),
						React.createElement('th', { rowSpan: 2, scope: 'col' }, '保证金（元/辆）'),
						React.createElement('th', { rowSpan: 2, scope: 'col', className: 'lc-lease-order-editor__th-period' }, '车辆租赁期限'),
						React.createElement('th', { rowSpan: 2, scope: 'col', className: 'lc-lease-order-editor__actions-col' }, '操作'),
					),
					React.createElement('tr', { className: 'lc-lease-order-editor__head-row lc-lease-order-editor__head-row--sub' },
						React.createElement('th', { scope: 'col' }, '车辆租金（元/月/辆，含税）'),
						React.createElement('th', { scope: 'col' }, '服务费（含税）'),
						React.createElement('th', { scope: 'col' }, '服务内容'),
					),
				),
				React.createElement('tbody', null,
					rows.map(function (row) {
						var extraServices = normalizeExtraServices(row);
						var subtotal = calcRentServiceSubtotal(row.rent, extraServices);
						var serviceFeeTotal = sumExtraServiceFees(extraServices);
						var plateOptions = getReadyVehiclePlateOptions(row.brandModel);
						var leasePeriodValue = row.leasePeriodStart && row.leasePeriodEnd
							? [dayjs(row.leasePeriodStart), dayjs(row.leasePeriodEnd)]
							: null;
						return React.createElement('tr', { key: row.id },
							React.createElement('td', null,
								React.createElement(Cascader, {
									className: 'lc-form-cascader vm-focus-border',
									options: cascaderOptions,
									value: row.brandModel && row.brandModel.length ? row.brandModel : undefined,
									onChange: function (value) {
										var nextBrandModel = value || [];
										var nextPlateOptions = getReadyVehiclePlateOptions(nextBrandModel);
										var plateStillValid = !row.plateNo || nextPlateOptions.some(function (opt) {
											return opt.value === row.plateNo;
										});
										updateRow(row.id, {
											brandModel: nextBrandModel,
											plateNo: plateStillValid ? row.plateNo : '',
										});
									},
									placeholder: '请选择品牌 / 型号',
									showSearch: true,
									'aria-label': '品牌车型',
								}),
							),
							React.createElement('td', null,
								React.createElement(Select, {
									className: 'lc-form-select vm-focus-border',
									value: row.plateNo || undefined,
									onChange: function (value) {
										updateRow(row.id, { plateNo: value != null ? value : '' });
									},
									options: plateOptions,
									placeholder: '请选择车牌号',
									allowClear: true,
									showSearch: true,
									optionFilterProp: 'label',
									disabled: plateOptions.length === 0,
									notFoundContent: row.brandModel && row.brandModel.length >= 2
										? '暂无已备车车辆'
										: '请先选择品牌车型',
									'aria-label': '车牌号',
								}),
							),
							React.createElement('td', null,
								React.createElement(LeaseOrderAmountField, null,
									React.createElement(ReadonlyValue, {
										value: subtotal != null ? String(subtotal) : '',
										label: '租金及服务费小计',
									}),
								),
							),
							React.createElement('td', null,
								React.createElement(LeaseOrderAmountField, null,
									React.createElement(InputNumber, {
										className: 'lc-form-number vm-focus-border',
										controls: false,
										min: 0,
										step: 0.01,
										precision: 2,
										value: row.rent,
										onChange: function (v) { updateRow(row.id, { rent: v }); },
										placeholder: '车辆租金',
										style: { width: '100%' },
										'aria-label': '车辆租金',
									}),
								),
							),
							React.createElement('td', null,
								React.createElement(LeaseOrderAmountField, null,
									React.createElement(ReadonlyValue, {
										value: serviceFeeTotal > 0 ? String(serviceFeeTotal) : '',
										label: '服务费',
									}),
								),
							),
							React.createElement('td', null,
								React.createElement(LeaseOrderServiceContentField, {
									value: extraServices,
									onChange: function (values) {
										updateRow(row.id, { extraServices: values || [] });
									},
								}),
							),
							React.createElement('td', null,
								React.createElement(LeaseOrderAmountField, null,
									React.createElement(InputNumber, {
										className: 'lc-form-number vm-focus-border',
										controls: false,
										min: 0,
										step: 0.01,
										precision: 2,
										value: row.deposit,
										onChange: function (v) { updateRow(row.id, { deposit: v }); },
										style: { width: '100%' },
										'aria-label': '保证金',
									}),
								),
							),
							React.createElement('td', null,
								React.createElement(DatePicker.RangePicker, {
									className: 'lc-form-datepicker vm-focus-border',
									style: { width: '100%' },
									placeholder: ['开始日期', '结束日期'],
									value: leasePeriodValue,
									onChange: function (_dates, dateStrings) {
										updateRow(row.id, {
											leasePeriodStart: dateStrings && dateStrings[0] ? dateStrings[0] : null,
											leasePeriodEnd: dateStrings && dateStrings[1] ? dateStrings[1] : null,
										});
									},
									'aria-label': '车辆租赁期限',
								}),
							),
							React.createElement('td', { className: 'lc-lease-order-editor__actions-col' },
								React.createElement(LeaseOrderRowActions, {
									rowId: row.id,
									onCopy: copyRow,
									onRemove: removeRow,
								}),
							),
						);
					}),
				),
			),
		),
		React.createElement('div', { className: 'lc-lease-order-editor__toolbar' },
			React.createElement(Button, {
				type: 'dashed',
				className: 'lc-lease-order-editor__add-btn',
				onClick: addRow,
				icon: React.createElement(Plus, { size: 14, 'aria-hidden': true }),
			}, '添加车辆'),
		),
		React.createElement('div', { className: 'lc-lease-order-editor__delivery lc-form-grid lc-form-grid--pair' },
			React.createElement(FormField, { label: '车辆交付（交还）地点' },
				React.createElement(Cascader, {
					className: 'lc-form-cascader vm-focus-border',
					options: PROVINCE_CITY_CASCADER_OPTIONS,
					value: order.deliveryRegion && order.deliveryRegion.length ? order.deliveryRegion : undefined,
					onChange: function (value) { patchOrder({ deliveryRegion: value || [] }); },
					placeholder: '请选择省 / 市',
					showSearch: true,
					'aria-label': '车辆交付交还地点',
				}),
			),
			React.createElement(FormField, { label: '车辆交付时间' },
				React.createElement(DatePicker, {
					className: 'lc-form-datepicker vm-focus-border',
					style: { width: '100%' },
					placeholder: '请选择日期',
					value: deliveryDateValue,
					onChange: function (_date, dateString) {
						patchOrder({ deliveryDate: dateString || null });
					},
					'aria-label': '车辆交付时间',
				}),
			),
		),
	);
}

function PowerOfAttorneyEditor(props) {
	var poa = props.poa || createDefaultPowerOfAttorneyState();
	var onChange = props.onChange;
	var delegates = poa.delegates || [];

	function patchPoa(patch) {
		onChange(Object.assign({}, poa, patch));
	}

	function updateDelegates(nextDelegates) {
		patchPoa({ delegates: nextDelegates });
	}

	function updateDelegate(id, patch) {
		updateDelegates(delegates.map(function (row) {
			if (row.id !== id) return row;
			return Object.assign({}, row, patch);
		}));
	}

	function addDelegate() {
		updateDelegates(delegates.concat([createEmptyDelegateRow()]));
	}

	function removeDelegate(id) {
		if (delegates.length <= 1) {
			updateDelegates([createEmptyDelegateRow()]);
			return;
		}
		updateDelegates(delegates.filter(function (row) { return row.id !== id; }));
	}

	return React.createElement('div', { className: 'lc-poa-editor' },
		delegates.map(function (row, index) {
			return React.createElement('div', {
				key: row.id,
				className: 'lc-poa-editor__row',
				role: 'group',
				'aria-label': '委托人 ' + (index + 1),
			},
				delegates.length > 1 ? React.createElement('div', { className: 'lc-poa-editor__row-head' },
					React.createElement('span', { className: 'lc-poa-editor__row-index' }, '委托人 ' + (index + 1)),
				) : null,
				React.createElement('div', { className: 'lc-poa-editor__fields lc-poa-editor__fields--inline' },
					React.createElement(FormField, { label: '姓名' },
						React.createElement(Input, {
							className: 'lc-form-input vm-focus-border',
							value: row.name,
							onChange: function (e) { updateDelegate(row.id, { name: e.target.value }); },
							placeholder: '请输入姓名',
							allowClear: true,
							'aria-label': '委托人姓名',
						}),
					),
					React.createElement(FormField, { label: '联系方式' },
						React.createElement(Input, {
							className: 'lc-form-input vm-focus-border',
							value: row.contact,
							onChange: function (e) { updateDelegate(row.id, { contact: e.target.value }); },
							placeholder: '请输入联系方式',
							allowClear: true,
							'aria-label': '委托人联系方式',
						}),
					),
					React.createElement(FormField, { label: '证件号码' },
						React.createElement(Input, {
							className: 'lc-form-input vm-focus-border',
							value: row.idNumber,
							onChange: function (e) { updateDelegate(row.id, { idNumber: e.target.value }); },
							placeholder: '请输入证件号码',
							allowClear: true,
							'aria-label': '委托人证件号码',
						}),
					),
					React.createElement('div', { className: 'lc-poa-editor__row-action lc-poa-editor__row-action--ops' },
						React.createElement('span', { className: 'lc-poa-editor__ops-label' }, '操作'),
						React.createElement('button', {
							type: 'button',
							className: 'lc-poa-editor__remove-btn',
							onClick: function () { removeDelegate(row.id); },
							'aria-label': '删除委托人 ' + (index + 1),
							title: '删除',
						}, React.createElement(Trash2, { size: 14, 'aria-hidden': true })),
					),
				),
			);
		}),
		React.createElement('div', { className: 'lc-poa-editor__toolbar' },
			React.createElement(Button, {
				type: 'dashed',
				className: 'lc-poa-editor__add-btn',
				onClick: addDelegate,
				icon: React.createElement(Plus, { size: 14, 'aria-hidden': true }),
			}, '新增委托人'),
		),
	);
}

function CustomerCredentialThumb(props) {
	var label = props.label;
	var previewUrl = props.previewUrl;
	return React.createElement('div', { className: 'lc-attach-thumb' },
		React.createElement(Image, {
			className: 'lc-attach-thumb__img',
			src: previewUrl,
			alt: label,
			preview: { src: previewUrl },
			fallback: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect width="100%" height="100%" fill="#f1f5f9"/></svg>'),
		}),
		React.createElement('div', { className: 'lc-attach-thumb__meta' },
			React.createElement('span', { className: 'lc-attach-thumb__label' }, label),
		),
	);
}

function FormField(props) {
	return React.createElement('label', { className: 'lc-form-field' },
		React.createElement('span', { className: 'lc-form-field__label' },
			props.required ? React.createElement('span', { className: 'lc-form-field__required', 'aria-hidden': 'true' }, '*') : null,
			props.label,
		),
		props.children,
	);
}

function ReadonlyValue(props) {
	var hasValue = props.value != null && String(props.value).trim() !== '';
	return React.createElement('div', {
		className: 'lc-form-readonly lc-form-readonly--synced',
		'aria-readonly': 'true',
		'aria-label': props.label,
	},
		hasValue
			? props.value
			: React.createElement('span', { className: 'lc-form-readonly__empty' }, props.emptyHint || '—'),
	);
}

function EditorCard(props) {
	var collapsible = props.collapsible;
	var expanded = collapsible ? props.expanded !== false : true;
	var titleEl = React.createElement('h3', { id: props.titleId, className: 'vm-section-title' }, props.title);
	var toggleEl = collapsible ? React.createElement('button', {
		type: 'button',
		className: 'lc-form-card__toggle',
		onClick: props.onToggle,
		'aria-expanded': expanded,
		'aria-controls': props.bodyId,
	},
		React.createElement('span', null, expanded ? '收起' : '展开'),
		React.createElement(ChevronDown, {
			size: 14,
			className: 'lc-form-card__toggle-icon' + (expanded ? ' is-expanded' : ''),
			'aria-hidden': true,
		}),
	) : null;

	return React.createElement('section', {
		className: 'vm-detail-card lc-form-card' + (collapsible && !expanded ? ' is-collapsed' : ''),
		'aria-labelledby': props.titleId,
	},
		collapsible
			? React.createElement('div', { className: 'lc-form-card__header' }, titleEl, toggleEl)
			: titleEl,
		props.desc && expanded ? React.createElement('p', { className: 'lc-form-card__desc' }, props.desc) : null,
		expanded ? React.createElement('div', {
			id: props.bodyId,
			className: collapsible ? 'lc-form-card__body' : undefined,
		}, props.children) : null,
	);
}

export default function LeaseContractEditorForm(props) {
	var lessorId = props.lessorId;
	var customerId = props.customerId;
	var contractCode = props.contractCode || '';
	var mileage = props.mileage || DEFAULT_MILEAGE_STANDARD;
	var feeInfo = props.feeInfo || DEFAULT_FEE_INFO;
	var onLessorChange = props.onLessorChange;
	var onCustomerChange = props.onCustomerChange;
	var onContractCodeChange = props.onContractCodeChange;
	var onMileageChange = props.onMileageChange;
	var onFeeInfoChange = props.onFeeInfoChange;

	var lessorCompanies = getLessorCompanies();
	var selectedLessor = getLessorCompanyById(lessorId);
	var selectedCustomer = getLeaseCustomerById(customerId);
	var invoice = getCustomerInvoicePreview(selectedCustomer);
	var lessorAccount = getLessorAccountPreview(selectedLessor);
	var lessorContact = getLessorContactPreview(selectedLessor);
	var customerContact = getCustomerContactPreview(selectedCustomer);
	var lessorEmptyHint = lessorId ? undefined : '请先选择甲方签约主体';
	var customerEmptyHint = customerId ? undefined : '请先选择乙方客户';
	var showPrepayAmount = feeInfo.hydrogenPaymentMethod === 'prepay';

	function patchMileage(patch) {
		onMileageChange(Object.assign({}, mileage, patch));
	}

	function patchFeeInfo(patch) {
		onFeeInfoChange(Object.assign({}, feeInfo, patch));
	}

	var signingExpandedState = React.useState(true);
	var signingExpanded = signingExpandedState[0];
	var setSigningExpanded = signingExpandedState[1];
	var mileageExpandedState = React.useState(true);
	var mileageExpanded = mileageExpandedState[0];
	var setMileageExpanded = mileageExpandedState[1];
	var feeExpandedState = React.useState(true);
	var feeExpanded = feeExpandedState[0];
	var setFeeExpanded = feeExpandedState[1];

	return React.createElement('div', { className: 'lc-create-editor-scroll' },
		React.createElement(EditorCard, {
			titleId: 'lc-card-signing',
			title: '签约信息',
			collapsible: true,
			expanded: signingExpanded,
			onToggle: function () { setSigningExpanded(!signingExpanded); },
			bodyId: 'lc-card-signing-body',
		},
			React.createElement('div', { className: 'lc-form-grid' },
				React.createElement(FormField, { label: '合同编号', required: true },
					React.createElement(Input, {
						className: 'lc-form-input lc-contract-code-input vm-focus-border',
						addonBefore: CONTRACT_CODE_PREFIX,
						value: contractCode,
						onChange: function (e) { onContractCodeChange(e.target.value); },
						placeholder: '请输入合同编号',
						allowClear: true,
						'aria-label': '合同编号',
					}),
				),
				React.createElement('div', { className: 'lc-form-grid lc-form-grid--pair' },
				React.createElement(FormField, {
					label: '甲方',
					required: true,
				},
					React.createElement(Select, {
						className: 'lc-form-select vm-focus-border',
						placeholder: '请选择甲方签约主体',
						value: lessorId || undefined,
						allowClear: true,
						onChange: function (value) { onLessorChange(value || ''); },
						options: lessorCompanies.map(function (c) {
							return { value: c.id, label: c.legalName };
						}),
						'aria-label': '甲方签约主体',
					}),
				),
				React.createElement(FormField, {
					label: '乙方',
					required: true,
				},
					React.createElement(Select, {
						className: 'lc-form-select vm-focus-border',
						placeholder: '请选择或搜索客户',
						value: customerId || undefined,
						allowClear: true,
						showSearch: true,
						optionFilterProp: 'label',
						onChange: function (value) { onCustomerChange(value || ''); },
						options: MOCK_LEASE_CUSTOMERS.map(function (c) {
							return { value: c.id, label: c.name };
						}),
						'aria-label': '乙方客户',
					}),
				),
				),
			),
			selectedCustomer ? React.createElement('div', { className: 'lc-form-subblock' },
				React.createElement('div', { className: 'lc-form-subblock__section' },
					React.createElement('h3', { id: 'lc-lessor-account-title', className: 'vm-section-title' }, '甲方信息'),
					React.createElement('div', {
						id: 'lc-lessor-account-panel',
						className: 'lc-form-grid lc-form-grid--cols-2 lc-form-grid--readonly lc-invoice-readonly-panel lc-lessor-account-readonly-panel',
						role: 'region',
						'aria-labelledby': 'lc-lessor-account-title',
						'aria-readonly': 'true',
						'aria-label': '甲方信息，来自甲方档案只读',
					},
						React.createElement(FormField, { label: '户名' }, React.createElement(ReadonlyValue, { value: lessorAccount.accountName, emptyHint: lessorEmptyHint })),
						React.createElement(FormField, { label: '开户行' }, React.createElement(ReadonlyValue, { value: lessorAccount.bankName, emptyHint: lessorEmptyHint })),
						React.createElement(FormField, { label: '账号' }, React.createElement(ReadonlyValue, { value: lessorAccount.bankAccount, emptyHint: lessorEmptyHint })),
						React.createElement(FormField, { label: '通讯地址' }, React.createElement(ReadonlyValue, { value: lessorContact.mailAddress, emptyHint: lessorEmptyHint })),
						React.createElement(FormField, { label: '联系人姓名及电话' },
							React.createElement('div', { className: 'lc-form-contact-pair' },
								React.createElement(ReadonlyValue, { value: lessorContact.contactName, emptyHint: lessorEmptyHint }),
								React.createElement(ReadonlyValue, { value: lessorContact.contactPhone, emptyHint: lessorEmptyHint }),
							),
						),
						React.createElement(FormField, { label: '邮箱' }, React.createElement(ReadonlyValue, { value: lessorContact.email, emptyHint: lessorEmptyHint })),
					),
				),
				React.createElement('div', { className: 'lc-form-subblock__section' },
					React.createElement('h3', { id: 'lc-invoice-info-title', className: 'vm-section-title' }, '乙方信息'),
					React.createElement('div', {
						id: 'lc-invoice-info-panel',
						className: 'lc-form-grid lc-form-grid--cols-2 lc-form-grid--readonly lc-invoice-readonly-panel',
						role: 'region',
						'aria-labelledby': 'lc-invoice-info-title',
						'aria-readonly': 'true',
						'aria-label': '乙方信息，来自客户表只读',
					},
						React.createElement(FormField, { label: '企业名称' }, React.createElement(ReadonlyValue, { value: invoice.companyName, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '开户银行' }, React.createElement(ReadonlyValue, { value: invoice.bank, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '银行账号' }, React.createElement(ReadonlyValue, { value: invoice.bankAccount, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '纳税人识别号' }, React.createElement(ReadonlyValue, { value: invoice.taxId, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '企业地址' }, React.createElement(ReadonlyValue, { value: invoice.mailingAddress, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '企业电话' }, React.createElement(ReadonlyValue, { value: invoice.companyPhone, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '通讯地址' }, React.createElement(ReadonlyValue, { value: customerContact.mailAddress, emptyHint: customerEmptyHint })),
						React.createElement(FormField, { label: '联系人姓名及电话' },
							React.createElement('div', { className: 'lc-form-contact-pair' },
								React.createElement(ReadonlyValue, { value: customerContact.contactName, emptyHint: customerEmptyHint }),
								React.createElement(ReadonlyValue, { value: customerContact.contactPhone, emptyHint: customerEmptyHint }),
							),
						),
						React.createElement(FormField, { label: '邮箱' }, React.createElement(ReadonlyValue, { value: customerContact.email, emptyHint: customerEmptyHint })),
					),
				),
				React.createElement('div', { className: 'lc-form-subblock__section' },
					React.createElement('h4', { className: 'lc-form-subblock__title' }, '客户资质证照'),
					React.createElement('div', {
						className: 'lc-attach-gallery',
						'aria-label': '客户资质证照预览',
					},
						CUSTOMER_CREDENTIAL_ITEMS.map(function (item) {
							var previewUrl = getCustomerAttachmentPreviewUrl(selectedCustomer, item.key, item.label);
							return React.createElement(CustomerCredentialThumb, {
								key: item.key,
								label: item.label,
								previewUrl: previewUrl,
							});
						}),
					),
				),
			) : null,
		),
		React.createElement(EditorCard, {
			titleId: 'lc-card-mileage',
			title: '里程标准',
			collapsible: true,
			expanded: mileageExpanded,
			onToggle: function () { setMileageExpanded(!mileageExpanded); },
			bodyId: 'lc-card-mileage-body',
		},
			React.createElement('div', { className: 'lc-form-grid' },
				React.createElement(FormField, { label: '是否有里程要求', required: true },
					React.createElement(Select, {
						className: 'lc-form-select vm-focus-border',
						value: mileage.hasRequirement ? 'yes' : 'no',
						onChange: function (value) {
							patchMileage({ hasRequirement: value === 'yes' });
						},
						options: [
							{ value: 'yes', label: '是' },
							{ value: 'no', label: '否' },
						],
						'aria-label': '是否有里程要求',
					}),
				),
				mileage.hasRequirement ? React.createElement('div', {
					className: 'lc-mileage-types',
					role: 'radiogroup',
					'aria-label': '里程要求类型',
				},
					MILEAGE_PERIOD_OPTIONS.map(function (option) {
						var checked = mileage.period === option.value;
						return React.createElement('label', {
							key: option.value,
							className: 'lc-mileage-type' + (checked ? ' is-active' : ''),
						},
							React.createElement('input', {
								type: 'radio',
								name: 'lc-mileage-period',
								className: 'lc-mileage-type__radio',
								checked: checked,
								onChange: function () { patchMileage({ period: option.value }); },
							}),
							React.createElement('span', { className: 'lc-mileage-type__text' }, option.labelBefore),
							React.createElement(InputNumber, {
								className: 'lc-form-number lc-mileage-type__input vm-focus-border',
								min: 0,
								step: 100,
								disabled: !checked,
								value: checked ? mileage.targetKm : null,
								onChange: function (v) {
									if (checked) {
										patchMileage({ targetKm: v != null ? v : DEFAULT_MILEAGE_STANDARD.targetKm });
									}
								},
								'aria-label': option.labelBefore + '里程',
							}),
							React.createElement('span', { className: 'lc-mileage-type__text' }, option.labelAfter),
						);
					}),
				) : null,
			),
		),
		React.createElement(EditorCard, {
			titleId: 'lc-card-fee',
			title: '费用信息',
			collapsible: true,
			expanded: feeExpanded,
			onToggle: function () { setFeeExpanded(!feeExpanded); },
			bodyId: 'lc-card-fee-body',
		},
			React.createElement('div', { className: 'lc-form-grid lc-form-grid--pair' },
				React.createElement(FormField, { label: '付款周期', required: true },
					React.createElement(Select, {
						className: 'lc-form-select vm-focus-border',
						value: feeInfo.paymentPeriod,
						onChange: function (value) {
							patchFeeInfo({ paymentPeriod: value != null ? value : DEFAULT_FEE_INFO.paymentPeriod });
						},
						options: PAYMENT_PERIOD_OPTIONS,
						'aria-label': '付款周期',
					}),
				),
				React.createElement(FormField, { label: '氢费支付方式', required: true },
					React.createElement(Select, {
						className: 'lc-form-select vm-focus-border',
						value: feeInfo.hydrogenPaymentMethod,
						onChange: function (value) {
							var next = value || DEFAULT_FEE_INFO.hydrogenPaymentMethod;
							patchFeeInfo({
								hydrogenPaymentMethod: next,
								prepayAmount: next === 'prepay' ? feeInfo.prepayAmount : null,
							});
						},
						options: HYDROGEN_PAYMENT_METHOD_OPTIONS,
						'aria-label': '氢费支付方式',
					}),
				),
				showPrepayAmount ? React.createElement(FormField, { label: '预付款金额', required: true },
					React.createElement(InputNumber, {
						className: 'lc-form-number vm-focus-border',
						controls: false,
						min: 0,
						step: 0.01,
						precision: 2,
						value: feeInfo.prepayAmount,
						onChange: function (v) { patchFeeInfo({ prepayAmount: v }); },
						addonAfter: '元',
						style: { width: '100%' },
						'aria-label': '预付款金额',
					}),
				) : null,
				showPrepayAmount ? React.createElement(FormField, { label: '支付时间', required: true },
					React.createElement('div', { className: 'lc-form-inline-sentence' },
						React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '提前'),
						React.createElement(InputNumber, {
							className: 'lc-form-number lc-form-inline-sentence__input vm-focus-border',
							controls: true,
							min: 1,
							step: 1,
							precision: 0,
							value: feeInfo.payAheadWorkdays,
							onChange: function (v) {
								patchFeeInfo({
									payAheadWorkdays: v != null ? v : DEFAULT_FEE_INFO.payAheadWorkdays,
								});
							},
							'aria-label': '提前支付工作日天数',
						}),
						React.createElement('span', { className: 'lc-form-inline-sentence__text' }, '个工作日支付'),
					),
				) : null,
				React.createElement(FormField, { label: '还车氢量差单价', required: true },
					React.createElement(InputNumber, {
						className: 'lc-form-number vm-focus-border',
						controls: false,
						min: 0,
						step: 0.01,
						precision: 2,
						value: feeInfo.returnHydrogenDiffUnitPrice,
						onChange: function (v) { patchFeeInfo({ returnHydrogenDiffUnitPrice: v }); },
						addonAfter: '元',
						style: { width: '100%' },
						'aria-label': '还车氢量差单价',
					}),
				),
			),
		),
	);
}

export function LeaseContractLeaseOrderSection(props) {
	var leaseOrder = props.leaseOrder;
	var onLeaseOrderChange = props.onLeaseOrderChange;

	return React.createElement('div', { className: 'lc-create-editor-scroll lc-create-editor-scroll--section' },
		React.createElement(LeaseOrderEditor, {
			order: leaseOrder || createDefaultLeaseOrderState(),
			onChange: onLeaseOrderChange,
		}),
	);
}

export function LeaseContractPowerOfAttorneySection(props) {
	var powerOfAttorney = props.powerOfAttorney;
	var onPowerOfAttorneyChange = props.onPowerOfAttorneyChange;

	return React.createElement('div', { className: 'lc-create-editor-scroll lc-create-editor-scroll--section' },
		React.createElement(PowerOfAttorneyEditor, {
			poa: powerOfAttorney || createDefaultPowerOfAttorneyState(),
			onChange: onPowerOfAttorneyChange,
		}),
	);
}
