import { StatusTag } from '../vehicle-management/components/StatusTag';
import { TablePagination, DEFAULT_PAGE_SIZE } from '../../common/TablePagination';
import { OperationActions } from '../../common/OperationActions';
import {
	ROLE_OPTIONS,
	TASK_STAGE_META,
	SEED_ROWS,
	readRole,
	writeRole,
	deptProgress,
	settlementLabel,
	canSeeSettlement,
	hasPendingForRole,
	pendingHint,
	getPrimaryAction,
	fmtYMDHM
} from './vrsV2Data.js';

var LIST_CHROME_OFFSET = 420;

function SearchIconSvg() {
	return React.createElement('svg', {
		xmlns: 'http://www.w3.org/2000/svg', width: 16, height: 16, viewBox: '0 0 24 24',
		fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true
	},
		React.createElement('circle', { cx: 11, cy: 11, r: 8 }),
		React.createElement('path', { d: 'm21 21-4.3-4.3' })
	);
}

function ExportIconSvg() {
	return React.createElement('svg', {
		xmlns: 'http://www.w3.org/2000/svg', width: 16, height: 16, viewBox: '0 0 24 24',
		fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true
	},
		React.createElement('path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }),
		React.createElement('polyline', { points: '7 10 12 15 17 10' }),
		React.createElement('line', { x1: 12, x2: 12, y1: 15, y2: 3 })
	);
}

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

function DeptProgressBar(props) {
	var items = props.items || [];
	return React.createElement('div', { className: 'vrs2-dept-progress', 'aria-label': '四部门填报进度' },
		items.map(function (item) {
			var cls = 'vrs2-dept-progress__seg';
			if (item.done) cls += ' vrs2-dept-progress__seg--done';
			else if (item.active) cls += ' vrs2-dept-progress__seg--active';
			return React.createElement('div', {
				key: item.key,
				className: cls,
				title: item.label + '：' + item.status + (item.name ? '（' + item.name + '）' : '')
			},
				React.createElement('span', { className: 'vrs2-dept-progress__label' }, item.label.replace('部', '').replace('组', '').slice(0, 2))
			);
		})
	);
}

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 Dropdown = antd.Dropdown;
	var message = antd.message;

	var _role = useState(readRole());
	var role = _role[0];
	var setRole = _role[1];
	var _listTab = useState('mine');
	var listTab = _listTab[0];
	var setListTab = _listTab[1];
	var _data = useState(SEED_ROWS);
	var allRows = _data[0];
	var _filters = useState({ keyword: '', stage: undefined, settlement: undefined });
	var filters = _filters[0];
	var setFilters = _filters[1];
	var _applied = useState({ keyword: '', stage: undefined, settlement: undefined });
	var applied = _applied[0];
	var setApplied = _applied[1];
	var _page = useState(1);
	var page = _page[0];
	var setPage = _page[1];
	var _pageSize = useState(DEFAULT_PAGE_SIZE);
	var pageSize = _pageSize[0];
	var setPageSize = _pageSize[1];

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

	var stageOptions = useMemo(function () {
		return Object.keys(TASK_STAGE_META).map(function (k) {
			return { value: k, label: TASK_STAGE_META[k].label };
		});
	}, []);

	var settlementOptions = [
		{ value: 'refund', label: '应退还' },
		{ value: 'pay', label: '应补缴' },
		{ value: 'pending', label: '待核算' }
	];

	var filteredRows = useMemo(function () {
		return allRows.filter(function (r) {
			if (listTab === 'mine' && !hasPendingForRole(r, role)) return false;
			if (listTab === 'progress' && (r.taskStage === 'archived' || r.taskStage === 'withdrawn')) return false;
			if (listTab === 'done' && r.taskStage !== 'archived') return false;

			if (applied.keyword) {
				var kw = applied.keyword.toLowerCase();
				var hay = [r.plateNo, r.contractCode, r.customerName, r.projectName].join(' ').toLowerCase();
				if (hay.indexOf(kw) < 0) return false;
			}
			if (applied.stage && r.taskStage !== applied.stage) return false;
			if (applied.settlement === 'refund' && r.settlementDirection !== 'refund') return false;
			if (applied.settlement === 'pay' && r.settlementDirection !== 'pay') return false;
			if (applied.settlement === 'pending' && r.settlementDirection) return false;
			return true;
		});
	}, [allRows, listTab, role, applied]);

	var pagedRows = useMemo(function () {
		var start = (page - 1) * pageSize;
		return filteredRows.slice(start, start + pageSize);
	}, [filteredRows, page, pageSize]);

	var mineCount = useMemo(function () {
		return allRows.filter(function (r) { return hasPendingForRole(r, role); }).length;
	}, [allRows, role]);

	function handleSearch() {
		setApplied(Object.assign({}, filters));
		setPage(1);
	}

	function handleReset() {
		var empty = { keyword: '', stage: undefined, settlement: undefined };
		setFilters(empty);
		setApplied(empty);
		setPage(1);
	}

	function openRow(row, action) {
		if (action === 'bill') {
			message.info('生成账单（原型）：' + row.contractCode);
			return;
		}
		if (action === 'approve') {
			message.success('已发起总审批（原型）');
			return;
		}
		if (action === 'finance_approve') {
			message.info('跳转审批中心待办（原型）');
			return;
		}
		if (action === 'payment') {
			message.info('跳转收款/付款记录并关联应结款（原型）');
			return;
		}
		if (props && typeof props.onOpenDetail === 'function') {
			props.onOpenDetail(row);
		}
	}

	var columns = [
		{
			title: '车辆信息',
			key: 'vehicle',
			width: 168,
			className: 'vm-stacked-cell-td',
			render: function (_, r) {
				return React.createElement('div', { className: 'vm-stack' },
					React.createElement('span', { className: 'vm-stack-primary' }, r.plateNo),
					React.createElement('span', { className: 'vm-stack-secondary' }, r.contractCode)
				);
			}
		},
		{
			title: '客户 / 项目',
			key: 'customer',
			width: 200,
			className: 'vm-stacked-cell-td',
			render: function (_, r) {
				return React.createElement('div', { className: 'vm-stack' },
					React.createElement('span', { className: 'vm-stack-primary' }, r.customerName),
					React.createElement('span', { className: 'vm-stack-secondary' }, r.projectName)
				);
			}
		},
		{
			title: '还车时间',
			dataIndex: 'returnTime',
			key: 'returnTime',
			width: 132,
			render: fmtYMDHM
		},
		{
			title: '任务进度',
			key: 'deptProgress',
			width: 148,
			render: function (_, r) {
				return React.createElement(DeptProgressBar, { items: deptProgress(r) });
			}
		},
		{
			title: '当前阶段',
			key: 'taskStage',
			width: 108,
			render: function (_, r) {
				var meta = TASK_STAGE_META[r.taskStage] || { label: r.taskStage, tone: 'gray' };
				return React.createElement(StatusTag, { label: meta.label, tone: stageTone(r.taskStage) });
			}
		}
	];

	if (canSeeSettlement(role)) {
		columns.push({
			title: '结算预览',
			key: 'settlement',
			width: 120,
			className: 'tabular-nums',
			render: function (_, r) {
				if (!r.settlementDirection) return React.createElement('span', { className: 'vrs2-muted' }, '待核算');
				var cls = r.settlementDirection === 'refund' ? 'vrs2-settle vrs2-settle--refund' : 'vrs2-settle vrs2-settle--pay';
				return React.createElement('span', { className: cls }, settlementLabel(r));
			}
		});
	}

	columns.push(
		{
			title: '我的待办',
			key: 'pendingHint',
			width: 148,
			render: function (_, r) {
				var hint = pendingHint(r, role);
				if (hint === '—') return React.createElement('span', { className: 'vrs2-muted' }, '—');
				return React.createElement('span', { className: 'vrs2-pending-hint' }, hint);
			}
		},
		{
			title: '操作',
			key: 'actions',
			width: 168,
			fixed: 'right',
			render: function (_, r) {
				var primary = getPrimaryAction(r, role);
				var moreItems = [
					{ key: 'view-detail', label: '查看详情', onClick: function () { openRow(r, 'view'); } }
				];
				if (role === 'biz' && r.canRevoke) {
					moreItems.push({ key: 'revoke', label: '撤回审批', onClick: function () { message.success('撤回成功（原型）'); } });
				}
				return React.createElement(OperationActions, {
					view: { label: primary.label, onClick: function () { openRow(r, primary.action); } },
					more: moreItems
				});
			}
		}
	);

	var listTabs = [
		{ key: 'mine', label: '待我处理' + (mineCount ? ' (' + mineCount + ')' : '') },
		{ key: 'progress', label: '进行中' },
		{ key: 'done', label: '已完成' }
	];

	return React.createElement(App, null,
		React.createElement('div', { className: 'vm-page lc-page vrs2-page lc-page--list-dense' },
			React.createElement('header', { className: 'vrs2-page-header' },
				React.createElement('div', { className: 'vrs2-page-header__left' },
					React.createElement('h1', { className: 'vm-page-title' }, '还车应结款'),
					React.createElement('span', { className: 'vrs2-badge-new' }, '新')
				),
				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('div', { className: 'vm-filter-card ldb-filter-card' },
				React.createElement('div', { className: 'vm-filter-grid vm-filter-grid--compact' },
					React.createElement('label', { className: 'vm-filter-field vm-filter-field--wide' },
						React.createElement('span', { className: 'vm-filter-label' }, '合同 / 车牌 / 客户'),
						React.createElement('div', { className: 'vm-filter-input-wrap' },
							React.createElement('span', { className: 'vm-filter-input-icon' }, React.createElement(SearchIconSvg)),
							React.createElement('input', {
								className: 'vm-filter-input',
								placeholder: '输入关键词搜索',
								value: filters.keyword,
								onChange: function (e) { setFilters(function (p) { return Object.assign({}, p, { keyword: e.target.value }); }); }
							})
						)
					),
					React.createElement('label', { className: 'vm-filter-field' },
						React.createElement('span', { className: 'vm-filter-label' }, '任务阶段'),
						React.createElement(Select, {
							allowClear: true,
							placeholder: '全部',
							value: filters.stage,
							options: stageOptions,
							onChange: function (v) { setFilters(function (p) { return Object.assign({}, p, { stage: v }); }); }
						})
					),
					canSeeSettlement(role) ? React.createElement('label', { className: 'vm-filter-field' },
						React.createElement('span', { className: 'vm-filter-label' }, '结算方向'),
						React.createElement(Select, {
							allowClear: true,
							placeholder: '全部',
							value: filters.settlement,
							options: settlementOptions,
							onChange: function (v) { setFilters(function (p) { return Object.assign({}, p, { settlement: v }); }); }
						})
					) : null
				),
				React.createElement('div', { className: 'vm-filter-actions' },
					React.createElement(Button, { type: 'primary', onClick: handleSearch }, '查询'),
					React.createElement(Button, { onClick: handleReset }, '重置'),
					React.createElement(Button, { icon: React.createElement(ExportIconSvg), onClick: function () { message.info('导出（原型）'); } }, '导出')
				)
			),

			React.createElement('section', { className: 'vm-table-card' },
				React.createElement('div', { className: 'vm-table-toolbar' },
					React.createElement(Tabs, {
						activeKey: listTab,
						items: listTabs,
						onChange: function (k) { setListTab(k); setPage(1); }
					})
				),
				React.createElement('div', { className: 'vm-table-wrap' },
					React.createElement(Table, {
						className: 'vm-list-table',
						rowKey: 'key',
						size: 'small',
						pagination: false,
						scroll: { x: 1100, y: 'calc(100vh - ' + LIST_CHROME_OFFSET + 'px)' },
						dataSource: pagedRows,
						columns: columns
					})
				),
				React.createElement(TablePagination, {
					current: page,
					pageSize: pageSize,
					total: filteredRows.length,
					onChange: function (p, ps) { setPage(p); setPageSize(ps); }
				})
			)
		)
	);
};

export default Component;
