/**
 * 坯布库存查询：常量、格式化、查询参数组装
 */
import {
	formatRoll,
	formatWeightKg,
	fetchAllOrderList,
	LIST_PAGE_SIZE,
} from '@/common/storeFabricBusinessOut';

export { formatRoll, formatWeightKg, fetchAllOrderList, LIST_PAGE_SIZE };

/** 第一维度：坯布汇总表格列 */
export const GROUP_TABLE_COLUMNS = [
	{ label: '坯布', key: 'fabric_label', width: 300 },
	{ label: '仓库名称', key: 'warehouse_name', width: 180 },
	{ label: '库存匹数', key: 'stock_roll_display', width: 130 },
	{ label: '库存数量', key: 'stock_weight_display', width: 160 },
];

/** 第二维度：排除上期/本期字段后的表格列 */
export const STOCK_TABLE_COLUMNS = [
	{ label: '颜色', key: 'gray_fabric_color_name', width: 120 },
	{ label: '坯布编号', key: 'grey_fabric_code', width: 140 },
	{ label: '坯布名称', key: 'grey_fabric_name', width: 160 },
	{ label: '等级', key: 'grey_fabric_level_name', width: 100 },
	{ label: '幅宽', key: 'grey_fabric_width_and_unit_name', width: 120 },
	{ label: '克重', key: 'grey_fabric_gram_weight_and_unit_name', width: 120 },
	{ label: '成分', key: 'component', width: 120 },
	{ label: '客户', key: 'customer_name', width: 120 },
	{ label: '织厂', key: 'supplier_name', width: 140 },
	{ label: '机台号', key: 'machine_number', width: 100 },
	{ label: '针寸数', key: 'needle_size', width: 100 },
	{ label: '纱批', key: 'yarn_batch', width: 120 },
	{ label: '原料纱名', key: 'raw_material_yarn_name', width: 140 },
	{ label: '原料批号', key: 'raw_material_batch_num', width: 120 },
	{ label: '原料品牌', key: 'raw_material_batch_brand', width: 120 },
	{ label: '仓库', key: 'warehouse_name', width: 140 },
	{ label: '收货单位', key: 'receiver_name', width: 140 },
	{ label: '工厂备注', key: 'warehouse_remark', width: 140 },
	{ label: '染厂用坯单号', key: 'dye_unit_use_order_no', width: 150 },
	{ label: '生产通知单号', key: 'produce_order_no', width: 150 },
	{ label: '出坯单号', key: 'source_code', width: 140 },
	{ label: '出坯日期', key: 'source_time', width: 120 },
	{ label: '坯布备注', key: 'source_remark', width: 140 },
	{ label: '预约匹数', key: 'book_roll_display', width: 110 },
	{ label: '库存匹数', key: 'stock_roll_display', width: 110 },
	{ label: '库存数量', key: 'stock_weight_display', width: 140 },
	{ label: '库存成本', key: 'stock_cost_display', width: 110 },
	{ label: '单价', key: 'single_price_display', width: 100 },
	{ label: '毛重成本', key: 'buoyant_weight_price_display', width: 110 },
];

/** 细码明细表格列 */
export const WAREHOUSE_DETAIL_COLUMNS = [
	{ label: '序号', key: 'seq', width: 70 },
	{ label: '卷号', key: 'volume_number', width: 90 },
	{ label: '匹数', key: 'roll', width: 90 },
	{ label: '数量(KG)', key: 'weight', width: 110 },
	{ label: '条码', key: 'bar_code', width: 240 },
	{ label: '仓位', key: 'position', width: 100 },
	{ label: '颜色', key: 'gray_fabric_color_name', width: 100 },
	{ label: '织厂', key: 'supplier_name', width: 120 },
	{ label: '机台', key: 'machine_number', width: 90 },
	{ label: '库龄(天)', key: 'days_of_age', width: 90 },
];

export function formatStockWeightWithUnit(weight, unitName) {
	const val = formatWeightKg(weight);
	if (val === 0 && (weight === 0 || weight === '0')) return unitName ? `0 ${unitName}` : '0';
	if (!weight && weight !== 0) return '-';
	return unitName ? `${val} ${unitName}` : `${val}`;
}

export function formatDisplayCell(value) {
	if (value === null || value === undefined || value === '') return '-';
	return String(value);
}

export function toQueryString(params = {}) {
	return Object.keys(params)
		.filter((key) => {
			const val = params[key];
			return val !== '' && val !== null && val !== undefined;
		})
		.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');
}

export function parsePageQuery(options = {}) {
	const parsed = { ...options };
	['grey_fabric_id', 'warehouse_id', 'supplier_id', 'gray_fabric_color_id', 'warehouse_sum_id'].forEach((key) => {
		if (parsed[key] !== undefined && parsed[key] !== '') {
			const num = Number(parsed[key]);
			if (!Number.isNaN(num)) parsed[key] = num;
		}
	});
	return parsed;
}

/** 第一维度接口筛选：仅坯布编号、坯布名称 */
export function buildGroupListQuery(filters = {}) {
	const params = {};
	if (filters.grey_fabric_code) params.grey_fabric_code = filters.grey_fabric_code;
	if (filters.grey_fabric_name) params.grey_fabric_name = filters.grey_fabric_name;
	return params;
}

/** 第二维度接口筛选：坯布 id + 机台号 */
export function buildStockListQuery(filters = {}, context = {}) {
	const params = {};
	if (context.grey_fabric_id) params.grey_fabric_id = context.grey_fabric_id;
	if (filters.machine_number) params.machine_number = filters.machine_number;
	return params;
}

export function buildDetailQuery(row = {}, context = {}) {
	const params = {};
	const greyFabricId = row.grey_fabric_id || context.grey_fabric_id;
	if (greyFabricId) params.grey_fabric_id = greyFabricId;
	if (row.warehouse_id || context.warehouse_id) {
		params.warehouse_id = row.warehouse_id || context.warehouse_id;
	}
	if (row.supplier_id) params.supplier_id = row.supplier_id;
	if (row.gray_fabric_color_id) params.gray_fabric_color_id = row.gray_fabric_color_id;
	if (row.machine_number) params.machine_number = row.machine_number;
	if (row.yarn_batch) params.yarn_batch = row.yarn_batch;
	if (row.produce_order_no) params.produce_order_no = row.produce_order_no;
	if (row.source_code) params.source_code = row.source_code;
	if (row.id) params.warehouse_sum_id = row.id;
	if (row.warehouse_sum_id) params.warehouse_sum_id = row.warehouse_sum_id;
	return params;
}

export function buildStockListNavigateQuery(item) {
	return {
		grey_fabric_id: item.grey_fabric_id,
		grey_fabric_code: item.grey_fabric_code || '',
		grey_fabric_name: item.grey_fabric_name || '',
		warehouse_id: item.warehouse_id || '',
	};
}

export function buildDetailNavigateQuery(row, context = {}) {
	const detailQuery = buildDetailQuery(row, context);
	return {
		...detailQuery,
		grey_fabric_code: row.grey_fabric_code || context.grey_fabric_code || '',
		grey_fabric_name: row.grey_fabric_name || context.grey_fabric_name || '',
		gray_fabric_color_name: row.gray_fabric_color_name || '',
		supplier_name: row.supplier_name || '',
		machine_number: row.machine_number || '',
		yarn_batch: row.yarn_batch || '',
		warehouse_name: row.warehouse_name || '',
		stock_roll: row.stock_roll_display || '',
		stock_weight: row.stock_weight_display || '',
	};
}

export function mapGroupTableRow(row) {
	const code = row.grey_fabric_code || '';
	const name = row.grey_fabric_name || '';
	return {
		...row,
		_key: `${row.grey_fabric_id || ''}_${row.warehouse_id || ''}`,
		fabric_label: code && name ? `${code}#${name}` : (code || name || '-'),
		warehouse_name: formatDisplayCell(row.warehouse_name || row.receiver_name),
		stock_roll_display: formatRoll(row.stock_roll),
		stock_weight_display: formatStockWeightWithUnit(row.stock_weight, row.unit_name),
	};
}

export function mapStockTableRow(row) {
	const unitName = row.unit_name || '';
	return {
		...row,
		_key: row.id || `${row.grey_fabric_id}_${row.gray_fabric_color_id}_${row.supplier_id}_${row.machine_number}`,
		gray_fabric_color_name: formatDisplayCell(row.gray_fabric_color_name),
		grey_fabric_code: formatDisplayCell(row.grey_fabric_code),
		grey_fabric_name: formatDisplayCell(row.grey_fabric_name),
		grey_fabric_level_name: formatDisplayCell(row.grey_fabric_level_name),
		grey_fabric_width_and_unit_name: formatDisplayCell(row.grey_fabric_width_and_unit_name),
		grey_fabric_gram_weight_and_unit_name: formatDisplayCell(row.grey_fabric_gram_weight_and_unit_name),
		component: formatDisplayCell(row.component),
		customer_name: formatDisplayCell(row.customer_name),
		supplier_name: formatDisplayCell(row.supplier_name),
		machine_number: formatDisplayCell(row.machine_number),
		needle_size: formatDisplayCell(row.needle_size),
		yarn_batch: formatDisplayCell(row.yarn_batch),
		raw_material_yarn_name: formatDisplayCell(row.raw_material_yarn_name),
		raw_material_batch_num: formatDisplayCell(row.raw_material_batch_num),
		raw_material_batch_brand: formatDisplayCell(row.raw_material_batch_brand),
		warehouse_name: formatDisplayCell(row.warehouse_name),
		receiver_name: formatDisplayCell(row.receiver_name),
		warehouse_remark: formatDisplayCell(row.warehouse_remark),
		dye_unit_use_order_no: formatDisplayCell(row.dye_unit_use_order_no),
		produce_order_no: formatDisplayCell(row.produce_order_no),
		source_code: formatDisplayCell(row.source_code),
		source_time: formatDisplayCell((row.source_time || '').slice(0, 10)),
		source_remark: formatDisplayCell(row.source_remark),
		book_roll_display: row.book_roll != null && row.book_roll !== '' ? formatRoll(row.book_roll) : '-',
		stock_roll_display: formatRoll(row.stock_roll),
		stock_weight_display: formatStockWeightWithUnit(row.stock_weight, unitName),
		stock_cost_display: row.stock_cost != null && row.stock_cost !== '' ? formatWeightKg(row.stock_cost) : '-',
		single_price_display: row.single_price != null && row.single_price !== '' ? formatWeightKg(row.single_price) : '-',
		buoyant_weight_price_display: row.buoyant_weight_price != null && row.buoyant_weight_price !== ''
			? formatWeightKg(row.buoyant_weight_price) : '-',
		creator_name: formatDisplayCell(row.creator_name),
		create_time: formatDisplayCell(row.create_time),
		update_user_name: formatDisplayCell(row.update_user_name),
		update_time: formatDisplayCell(row.update_time),
	};
}

export function sumStockTotals(list = []) {
	let roll = 0;
	let weight = 0;
	(list || []).forEach((item) => {
		roll += Number(item.stock_roll || 0);
		weight += Number(item.stock_weight || 0);
	});
	return {
		roll: formatRoll(roll),
		weight: formatWeightKg(weight),
		count: list.length,
	};
}

export function sumDetailTotals(list = []) {
	let roll = 0;
	let weight = 0;
	(list || []).forEach((item) => {
		roll += Number(item.num || 0);
		weight += Number(item.weight || 0);
	});
	return {
		roll: formatRoll(roll),
		weight: formatWeightKg(weight),
		count: list.length,
	};
}

export function mapWarehouseDetailRows(list = []) {
	return (list || []).map((item, index) => ({
		seq: index + 1,
		volume_number: item.volume_number || '-',
		roll: item.num != null && item.num !== '' ? formatRoll(item.num) : '-',
		weight: item.weight != null && item.weight !== '' ? formatWeightKg(item.weight) : '-',
		bar_code: item.bar_code || item.fabric_piece_code || '-',
		position: item.warehouse_bin_Name || '-',
		gray_fabric_color_name: item.gray_fabric_color_name || '-',
		supplier_name: item.supplier_name || '-',
		machine_number: item.machine_number || '-',
		days_of_age: item.days_of_age != null && item.days_of_age !== '' ? item.days_of_age : '-',
	}));
}

export function getWarehouseDetailTableWidth(columns = WAREHOUSE_DETAIL_COLUMNS) {
	const total = columns.reduce((sum, col) => sum + (col.width || 120), 0);
	return `${total}rpx`;
}

export function fetchAllWarehouseList(listFn, params = {}, pageSize = LIST_PAGE_SIZE) {
	return fetchAllOrderList(listFn, params, pageSize);
}

export function calcTableHeight(rowCount, options = {}) {
	const headerPx = options.headerPx || 44;
	const rowPx = options.rowPx || 44;
	const minPx = options.minPx || 200;
	const maxPx = options.maxPx || 520;
	const total = headerPx + rowCount * rowPx;
	return `${Math.min(Math.max(total, minPx), maxPx)}px`;
}
