<template>
	<el-dialog v-model="dialogVisible" :title="`SKU管理 - ${assetName}`" width="1200px" :close-on-click-modal="false" @close="onClose">
		<!-- 搜索区域 -->
		<div class="sku-search mb15">
			<el-button type="primary" @click="onOpenAddSku">
				<el-icon><ele-Plus /></el-icon>
				添加SKU
			</el-button>
			<el-input v-model="queryParams.keyword" placeholder="请输入SKU名称" clearable style="width: 180px; margin-left: 10px" />
			<el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 100px; margin-left: 10px">
				<el-option label="激活" :value="1" />
				<el-option label="未激活" :value="0" />
			</el-select>
			<el-button type="primary" style="margin-left: 10px" @click="getSkuList">
				<el-icon><ele-Search /></el-icon>
				搜索
			</el-button>
			<el-button @click="onResetQuery">重置</el-button>
		</div>

		<!-- SKU 列表 -->
		<el-table :data="tableData" v-loading="loading" border style="width: 100%">
			<el-table-column prop="skuName" label="SKU名称" min-width="120" show-overflow-tooltip />
			<el-table-column prop="specValues" label="规格属性" min-width="140">
				<template #default="scope">
					<span v-if="scope.row.specValues && Array.isArray(scope.row.specValues) && scope.row.specValues.length > 0">
						<el-tag v-for="(item, idx) in scope.row.specValues" :key="idx" size="small" style="margin-right: 4px">
							{{ item.name }}: {{ item.options?.[0]?.label || (Array.isArray(item.value) ? item.value[0] : item.value) }}
						</el-tag>
					</span>
					<span
						v-else-if="
							scope.row.specValues &&
							typeof scope.row.specValues === 'object' &&
							!Array.isArray(scope.row.specValues) &&
							Object.keys(scope.row.specValues).length > 0
						"
					>
						<el-tag v-for="(value, key) in scope.row.specValues" :key="key" size="small" style="margin-right: 4px"> {{ key }}: {{ value }} </el-tag>
					</span>
					<span v-else>-</span>
				</template>
			</el-table-column>
			<el-table-column prop="specsUnit" label="规格单位" width="80" align="center">
				<template #default="scope">
					{{ scope.row.specsUnit?.value || getSpecsUnitLabel(scope.row.specsUnit) || '-' }}
				</template>
			</el-table-column>
			<el-table-column prop="specsCount" label="规格数量" width="80" align="center">
				<template #default="scope">
					{{ scope.row.specsCount || '-' }}
				</template>
			</el-table-column>
			<el-table-column prop="price" label="价格" width="90" align="center">
				<template #default="scope"> ¥{{ (scope.row.price / 100).toFixed(2) }} </template>
			</el-table-column>
			<el-table-column prop="stock" label="库存数量" width="100" align="center">
				<template #default="scope">
					{{ scope.row.unlimitedStock ? '无限' : scope.row.stock }}
				</template>
			</el-table-column>
			<el-table-column prop="status" label="状态" width="80" align="center">
				<template #default="scope">
					<el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
						{{ scope.row.status === 1 ? '激活' : '未激活' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="sort" label="排序" width="60" align="center" />
			<el-table-column prop="createdAt" label="创建时间" width="100" align="center">
				<template #default="scope">
					<el-tooltip :content="scope.row.createdAt" placement="top">
						<span>{{ formatShortTime(scope.row.createdAt) }}</span>
					</el-tooltip>
				</template>
			</el-table-column>
			<el-table-column prop="updatedAt" label="修改时间" width="100" align="center">
				<template #default="scope">
					<el-tooltip :content="scope.row.updatedAt" placement="top">
						<span>{{ formatShortTime(scope.row.updatedAt) }}</span>
					</el-tooltip>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="220" align="center">
				<template #default="scope">
					<el-button size="small" text type="primary" @click="onEditSku(scope.row)">编辑</el-button>
					<el-button v-if="!scope.row.unlimitedStock" size="small" text type="success" @click="onGenerateStock(scope.row)">生成库存</el-button>
					<el-button size="small" text type="info" @click="onViewLog(scope.row)">日志</el-button>
					<el-button size="small" text type="danger" @click="onDeleteSku(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="mt15" style="text-align: right">
			<el-pagination
				v-model:current-page="queryParams.pageNum"
				v-model:page-size="queryParams.pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:total="total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="onSizeChange"
				@current-change="onCurrentChange"
			/>
		</div>

		<!-- 添加/编辑 SKU 弹窗 -->
		<el-dialog v-model="skuFormVisible" :title="isEditSku ? '编辑SKU' : '添加SKU'" width="500px" :close-on-click-modal="false" append-to-body>
			<el-form ref="skuFormRef" :model="skuForm" :rules="skuRules" label-width="80px" v-loading="editLoading">
				<el-form-item label="资产名称">
					<el-input v-model="assetName" disabled />
				</el-form-item>
				<el-form-item label="SKU名称" prop="skuName">
					<el-input v-model="skuForm.skuName" placeholder="请输入SKU名称" />
				</el-form-item>
				<el-form-item label="规格数量" prop="specsCount">
					<el-input-number v-model="skuForm.specsCount" :min="1" controls-position="right" />
				</el-form-item>
				<el-form-item label="规格单位" prop="specsUnit">
					<el-select v-model="skuForm.specsUnit" placeholder="请选择规格单位" style="width: 150px" clearable>
						<el-option v-for="opt in specsUnitOptions" :key="opt.key" :label="opt.value" :value="opt.key" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="assetSpecAttrs.length > 0">
					<div class="spec-values-container">
						<div v-for="attr in assetSpecAttrs" :key="attr.name" class="spec-item">
							<span class="spec-label">{{ attr.name }}：</span>
							<el-select
								v-if="attr.options && attr.options.length > 0"
								v-model="specValuesMap[attr.name]"
								placeholder="请选择"
								style="width: 120px"
								filterable
								allow-create
								clearable
							>
								<el-option v-for="opt in attr.options" :key="opt.value" :label="opt.label" :value="opt.value" />
							</el-select>
							<el-input v-else v-model="specValuesMap[attr.name]" placeholder="请输入" style="width: 120px" />
						</div>
					</div>
				</el-form-item>
				<el-form-item label="价格" prop="price">
					<el-input-number v-model="skuForm.price" :min="0" :precision="2" :step="0.01" controls-position="right" />
					<span style="margin-left: 8px">元</span>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="skuForm.status">
						<el-radio :value="1">激活</el-radio>
						<el-radio :value="0">未激活</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="排序">
					<el-input-number v-model="skuForm.sort" :min="0" controls-position="right" />
					<span style="margin-left: 8px; color: #909399; font-size: 12px">数值越小越靠前</span>
				</el-form-item>
				<el-form-item label="图片" prop="imageUrl" required>
					<el-upload class="sku-image-uploader" :show-file-list="false" :http-request="handleSkuImageUpload" accept="image/*">
						<img v-if="skuImagePreview" :src="skuImagePreview" class="sku-image" />
						<el-icon v-else class="sku-image-uploader-icon"><ele-Plus /></el-icon>
					</el-upload>
					<el-button v-if="skuImagePreview" type="danger" text size="small" style="margin-left: 10px" @click="removeSkuImage">删除</el-button>
				</el-form-item>
				<!-- <el-form-item label="描述">
					<el-input v-model="skuForm.description" type="textarea" :rows="3" placeholder="请输入SKU描述" />
				</el-form-item> -->
			</el-form>
			<template #footer>
				<el-button @click="skuFormVisible = false">取消</el-button>
				<el-button type="primary" :loading="submitLoading" @click="onSubmitSku">确认</el-button>
			</template>
		</el-dialog>

		<!-- 生成库存弹窗 -->
		<el-dialog v-model="stockFormVisible" title="生成库存" width="450px" :close-on-click-modal="false" append-to-body>
			<el-form ref="stockFormRef" :model="stockForm" :rules="getStockFormRules()" label-width="100px" v-loading="stockFormLoading">
				<el-form-item label="SKU名称">
					<el-input :model-value="currentSkuName" disabled />
				</el-form-item>
				<template v-for="field in stockFormFields" :key="field.name">
					<el-form-item :label="field.label" :prop="field.name">
						<!-- 数字类型 -->
						<el-input-number
							v-if="field.type === 'number'"
							v-model="stockForm[field.name]"
							:min="field.min"
							:max="field.max"
							:controls="!field.maxLength"
							controls-position="right"
							style="width: 200px"
						/>
						<!-- 日期类型 -->
						<el-date-picker
							v-else-if="field.type === 'date'"
							v-model="stockForm[field.name]"
							type="date"
							placeholder="请选择日期"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							style="width: 200px"
						/>
						<!-- 文本类型 -->
						<el-input v-else v-model="stockForm[field.name]" :maxlength="field.maxLength" placeholder="请输入" style="width: 200px" />
					</el-form-item>
				</template>
			</el-form>
			<template #footer>
				<el-button @click="stockFormVisible = false">取消</el-button>
				<el-button type="primary" :loading="stockSubmitLoading" @click="onSubmitStock">确认</el-button>
			</template>
		</el-dialog>
	</el-dialog>
	<OperationLogDialog ref="operationLogRef" />
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import {
	listAssetSkus,
	createAssetSku,
	updateAssetSku,
	deleteAssetSku,
	getAssetSku,
	getAsset,
	uploadAssetImage,
	getSpecsUnitOptions,
	getStockFormFields,
	stockOperation,
} from '/@/api/assets/asset';
import { createFormDiff } from '/@/utils/diffUtils';
import OperationLogDialog from '../../component/operationLogDialog.vue';
import type { UploadRequestOptions, UploadUserFile } from 'element-plus';

interface SpecValueItem {
	key: string;
	value: string;
}

interface AssetSpecAttr {
	name: string;
	options?: { value: string; label: string }[];
	dictType?: string;
}

// 库存表单字段接口
interface StockFormField {
	name: string;
	label: string;
	type: string;
	required?: boolean;
	min?: number;
	max?: number;
	maxLength?: number;
	default?: string | number;
}

const dialogVisible = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const editLoading = ref(false);
const skuFormVisible = ref(false);
const isEditSku = ref(false);
const editSkuId = ref('');
const operationLogRef = ref();

// 库存弹窗相关
const stockFormVisible = ref(false);
const stockFormLoading = ref(false);
const stockSubmitLoading = ref(false);
const stockFormFields = ref<StockFormField[]>([]);
const stockFormRef = ref<FormInstance>();
const stockForm = reactive<Record<string, any>>({});
const currentSkuId = ref('');
const currentSkuName = ref('');

const assetId = ref('');
const assetName = ref('');
const assetType = ref('');
const unlimitedStock = ref(false); // 资产是否无限库存
const assetSpecAttrs = ref<AssetSpecAttr[]>([]);
const fileAddressPrefix = ref('');
const skuImagePreview = ref('');
const specsUnitOptions = ref<{ key: string; value: string }[]>([]);
const tableData = ref<any[]>([]);
const total = ref(0);

const queryParams = reactive({
	keyword: '',
	status: undefined as number | undefined,
	pageNum: 1,
	pageSize: 10,
});

const skuFormRef = ref<FormInstance>();
const skuForm = reactive({
	skuName: '',
	price: 0,
	stock: 0,
	unlimitedStock: false,
	status: 1,
	sort: 0,
	imageUrl: '',
	description: '',
	specsUnit: '',
	specsCount: 1,
});

const specValuesList = ref<SpecValueItem[]>([{ key: '', value: '' }]);
const specValuesMap = reactive<Record<string, string>>({});
// 使用通用工具函数保存原始数据，用于最小化传参
const skuFormDiff = createFormDiff<Record<string, any>>();
const specValuesMapDiff = createFormDiff<Record<string, string>>();

const skuRules: FormRules = {
	skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
	specsUnit: [{ required: true, message: '请选择规格单位', trigger: 'change' }],
	specsCount: [
		{ required: true, message: '请输入规格数量', trigger: 'blur' },
		{ type: 'number', min: 1, message: '规格数量必须大于0', trigger: 'blur' },
	],
	price: [
		{ required: true, message: '请输入价格', trigger: 'blur' },
		{ type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' },
	],
	stock: [
		{ required: true, message: '请输入库存数量', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				if (skuForm.unlimitedStock) {
					callback();
				} else if (value === 0 || value === undefined || value === null) {
					callback(new Error('库存数量必须大于0'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	imageUrl: [{ required: true, message: '请上传SKU图片', trigger: 'change' }],
};

// 打开弹窗
const openDialog = (row: { id: string; name: string; type?: string; unlimitedStock?: boolean }) => {
	assetId.value = row.id;
	assetName.value = row.name;
	assetType.value = row.type || '';
	unlimitedStock.value = row.unlimitedStock || false;
	dialogVisible.value = true;
	resetQuery();
	getSkuList();
	fetchAssetSpecAttrs();
	fetchSpecsUnitOptions();
};

// 获取规格单位选项
const fetchSpecsUnitOptions = () => {
	if (!assetType.value) return;
	getSpecsUnitOptions(assetType.value)
		.then((res: any) => {
			specsUnitOptions.value = res.data?.options || [];
		})
		.catch(() => {
			specsUnitOptions.value = [];
		});
};

// 根据规格单位 key 获取对应的 label
const getSpecsUnitLabel = (key: string) => {
	if (!key) return '';
	const option = specsUnitOptions.value.find((opt) => opt.key === key);
	return option?.value || key;
};

// 格式化时间为短格式（只显示日期）
const formatShortTime = (time: string) => {
	if (!time) return '-';
	// 只取日期部分 YYYY-MM-DD
	return time.substring(0, 10);
};

// 获取资产规格属性（只获取多选类型）
const fetchAssetSpecAttrs = () => {
	getAsset(assetId.value)
		.then((res: any) => {
			const data = res.data || {};
			// 设置图片前缀
			fileAddressPrefix.value = data.fileAddressPrefix || data.imgAddressPrefix || '';
			// 从资产详情中获取规格属性列表
			if (data.specAttrs && Array.isArray(data.specAttrs)) {
				assetSpecAttrs.value = data.specAttrs;
			} else if (data.metadata && Array.isArray(data.metadata)) {
				// 只获取 multi_select 类型的属性
				assetSpecAttrs.value = data.metadata
					.filter((item: any) => item.type === 'multi_select')
					.map((item: any) => ({
						name: item.name,
						options: item.options?.map((opt: any) => ({ value: opt.value, label: opt.label || opt.value })) || [],
						dictType: item.dictType || '',
					}));
			} else {
				assetSpecAttrs.value = [];
			}
		})
		.catch(() => {
			assetSpecAttrs.value = [];
		});
};

// 获取 SKU 列表
const getSkuList = () => {
	loading.value = true;
	listAssetSkus({
		assetId: assetId.value,
		...queryParams,
	})
		.then((res: any) => {
			tableData.value = res.data?.list ?? [];
			total.value = res.data?.total ?? 0;
		})
		.catch(() => {
			tableData.value = [];
			total.value = 0;
		})
		.finally(() => {
			loading.value = false;
		});
};

// 重置查询
const resetQuery = () => {
	queryParams.keyword = '';
	queryParams.status = undefined;
	queryParams.pageNum = 1;
};

const onResetQuery = () => {
	resetQuery();
	getSkuList();
};

// 分页
const onSizeChange = (size: number) => {
	queryParams.pageSize = size;
	queryParams.pageNum = 1;
	getSkuList();
};

const onCurrentChange = (pageNum: number) => {
	queryParams.pageNum = pageNum;
	getSkuList();
};

// 打开添加 SKU 弹窗
const onOpenAddSku = () => {
	isEditSku.value = false;
	resetSkuForm();
	skuFormVisible.value = true;
};

// 编辑 SKU
const onEditSku = async (row: any) => {
	isEditSku.value = true;
	editSkuId.value = row.id || '';
	resetSkuForm();
	skuFormVisible.value = true;
	editLoading.value = true;

	try {
		const res: any = await getAssetSku(row.id);
		const data = res.data || {};
		skuForm.skuName = data.skuName || '';
		skuForm.price = (data.price || 0) / 100;
		skuForm.stock = data.stock || 0;
		skuForm.unlimitedStock = data.unlimitedStock || false;
		skuForm.status = data.status ?? 1;
		skuForm.sort = data.sort || 0;
		skuForm.imageUrl = data.imageUrl || '';
		skuForm.description = data.description || '';
		// specsUnit 可能是对象格式 { key, value } 或字符串
		if (data.specsUnit && typeof data.specsUnit === 'object') {
			skuForm.specsUnit = data.specsUnit.key || '';
		} else {
			skuForm.specsUnit = data.specsUnit || '';
		}
		skuForm.specsCount = data.specsCount || 1;
		// 使用工具函数保存原始数据用于最小化传参
		skuFormDiff.saveOriginal({
			skuName: skuForm.skuName,
			price: skuForm.price,
			stock: skuForm.stock,
			unlimitedStock: skuForm.unlimitedStock,
			status: skuForm.status,
			sort: skuForm.sort,
			imageUrl: skuForm.imageUrl,
			description: skuForm.description,
			specsUnit: skuForm.specsUnit,
			specsCount: skuForm.specsCount,
		});
		// 图片预览回显
		if (data.imageUrl) {
			skuImagePreview.value = formatImageUrl(data.imageUrl);
		}

		// 处理规格属性（支持新格式数组和旧格式对象）
		if (data.specValues) {
			if (Array.isArray(data.specValues)) {
				// 新格式：与 metadata 相同的数组格式
				data.specValues.forEach((item: any) => {
					if (item.name) {
						// value 可能是数组或字符串
						const val = Array.isArray(item.value) ? item.value[0] : item.value;
						specValuesMap[item.name] = String(val || '');
					}
				});
				specValuesList.value = data.specValues.map((item: any) => ({
					key: item.name,
					value: String(Array.isArray(item.value) ? item.value[0] : item.value || ''),
				}));
			} else if (typeof data.specValues === 'object' && Object.keys(data.specValues).length > 0) {
				// 旧格式：对象格式 { key: value }
				specValuesList.value = Object.entries(data.specValues).map(([key, value]) => ({
					key,
					value: String(value),
				}));
				Object.entries(data.specValues).forEach(([key, value]) => {
					specValuesMap[key] = String(value);
				});
			} else {
				specValuesList.value = [{ key: '', value: '' }];
			}
		} else {
			specValuesList.value = [{ key: '', value: '' }];
		}
		// 保存原始规格属性数据
		specValuesMapDiff.saveOriginal({ ...specValuesMap });
	} catch (error) {
		skuFormVisible.value = false;
	} finally {
		editLoading.value = false;
	}
};

// 查看日志
const onViewLog = (row: any) => {
	operationLogRef.value?.openDialog(row.id);
};

// 删除 SKU
const onDeleteSku = (row: any) => {
	ElMessageBox.confirm(`确定要删除SKU "${row.skuName}" 吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteAssetSku(row.id).then(() => {
				ElMessage.success('删除成功');
				getSkuList();
			});
		})
		.catch(() => {});
};

// 生成库存
const onGenerateStock = async (row: any) => {
	currentSkuId.value = row.id;
	currentSkuName.value = row.skuName;
	stockFormVisible.value = true;
	stockFormLoading.value = true;

	// 重置表单
	Object.keys(stockForm).forEach((key) => delete stockForm[key]);

	try {
		const res = await getStockFormFields(row.id);
		stockFormFields.value = res.data.fields || [];

		// 设置默认值，根据字段类型转换
		stockFormFields.value.forEach((field) => {
			if (field.default !== undefined) {
				// 如果是数字类型，确保默认值也是数字
				if (field.type === 'number') {
					stockForm[field.name] = Number(field.default);
				} else {
					stockForm[field.name] = field.default;
				}
			} else if (field.type === 'number') {
				stockForm[field.name] = field.min || 0;
			} else {
				stockForm[field.name] = '';
			}
		});
	} catch (error) {
		ElMessage.error('获取库存表单字段失败');
		stockFormVisible.value = false;
	} finally {
		stockFormLoading.value = false;
	}
};

// 提交库存操作
const onSubmitStock = async () => {
	const form = stockFormRef.value;
	if (!form) return;

	form.validate(async (valid: boolean) => {
		if (valid) {
			stockSubmitLoading.value = true;
			try {
				// 根据字段类型转换数据
				const submitData: Record<string, any> = {
					assetSkuId: currentSkuId.value,
				};
				stockFormFields.value.forEach((field) => {
					const value = stockForm[field.name];
					if (field.type === 'number' && value !== undefined && value !== '') {
						submitData[field.name] = Number(value);
					} else if (value !== undefined && value !== '') {
						submitData[field.name] = value;
					}
				});

				await stockOperation(submitData as any);
				ElMessage.success('库存生成成功');
				stockFormVisible.value = false;
				getSkuList();
			} catch (error) {
				ElMessage.error('库存操作失败');
			} finally {
				stockSubmitLoading.value = false;
			}
		}
	});
};

// 生成库存表单验证规则
const getStockFormRules = () => {
	const rules: Record<string, any[]> = {};
	stockFormFields.value.forEach((field) => {
		const fieldRules: any[] = [];
		if (field.required) {
			fieldRules.push({ required: true, message: `${field.label}不能为空`, trigger: 'blur' });
		}
		if (field.type === 'number') {
			// 数字类型的最小值和最大值验证
			if (field.min !== undefined) {
				fieldRules.push({ type: 'number', min: field.min, message: `${field.label}最小值为${field.min}`, trigger: 'blur' });
			}
			if (field.max !== undefined) {
				fieldRules.push({ type: 'number', max: field.max, message: `${field.label}最大值为${field.max}`, trigger: 'blur' });
			}
			// 数字位数验证
			if (field.maxLength) {
				fieldRules.push({
					validator: (_rule: any, value: any, callback: any) => {
						if (value !== undefined && value !== null && value !== '') {
							const strValue = String(value);
							if (strValue.length > field.maxLength!) {
								callback(new Error(`${field.label}不能超过${field.maxLength}位`));
							} else {
								callback();
							}
						} else {
							callback();
						}
					},
					trigger: 'blur',
				});
			}
		} else if (field.maxLength) {
			// 字符串类型的最大长度验证
			fieldRules.push({ max: field.maxLength, message: `${field.label}最大长度为${field.maxLength}`, trigger: 'blur' });
		}
		if (fieldRules.length > 0) {
			rules[field.name] = fieldRules;
		}
	});
	return rules;
};

// 重置 SKU 表单
const resetSkuForm = () => {
	skuForm.skuName = '';
	skuForm.price = 0;
	skuForm.stock = 0;
	skuForm.unlimitedStock = false;
	skuForm.status = 1;
	skuForm.sort = 0;
	skuForm.imageUrl = '';
	skuForm.description = '';
	skuForm.specsUnit = '';
	skuForm.specsCount = 1;
	specValuesList.value = [{ key: '', value: '' }];
	// 清空 specValuesMap
	Object.keys(specValuesMap).forEach((key) => delete specValuesMap[key]);
	skuImagePreview.value = '';
	skuFormRef.value?.clearValidate();
};

// 格式化图片 URL
const formatImageUrl = (url?: string) => {
	if (!url) return '';
	if (/^https?:\/\//i.test(url)) return url;
	if (/^blob:/i.test(url)) return url;
	return `${fileAddressPrefix.value || ''}${url}`;
};

// 上传图片
const uploadImage = async (file: File): Promise<string> => {
	const res: any = await uploadAssetImage(file);

	if (res.fileAddressPrefix) {
		fileAddressPrefix.value = res.fileAddressPrefix;
	} else if (res.data && typeof res.data === 'object' && res.data.fileAddressPrefix) {
		fileAddressPrefix.value = res.data.fileAddressPrefix;
	}

	if (res.fileURL) return res.fileURL;
	if (res.data && typeof res.data === 'object') {
		if (res.data.fileURL) return res.data.fileURL;
		if (res.data.url) return res.data.url;
	}
	if (typeof res.data === 'string') return res.data;
	return '';
};

// 处理 SKU 图片上传
const handleSkuImageUpload = async (options: UploadRequestOptions) => {
	try {
		const url = await uploadImage(options.file);
		if (url) {
			skuForm.imageUrl = url;
			skuImagePreview.value = formatImageUrl(url);
			skuFormRef.value?.validateField('imageUrl');
		}
	} catch (error) {
		ElMessage.error('图片上传失败');
	}
};

// 删除 SKU 图片
const removeSkuImage = () => {
	skuForm.imageUrl = '';
	skuImagePreview.value = '';
	skuFormRef.value?.validateField('imageUrl');
};

// 获取属性的可选值
const getAttrOptions = (key: string): { value: string; label: string }[] => {
	if (!key) return [];
	const attr = assetSpecAttrs.value.find((a) => a.name === key);
	return attr?.options || [];
};

// 属性名称变更时清空属性值
const onSpecKeyChange = (index: number) => {
	specValuesList.value[index].value = '';
};

// 添加规格属性
const addSpecValue = () => {
	specValuesList.value.push({ key: '', value: '' });
};

// 删除规格属性
const removeSpecValue = (index: number) => {
	specValuesList.value.splice(index, 1);
};

// 提交 SKU
const onSubmitSku = async () => {
	const form = skuFormRef.value;
	if (!form) return;

	await form.validate(async (valid) => {
		if (!valid) return;

		// 校验规格属性必填
		if (assetSpecAttrs.value.length > 0) {
			for (const attr of assetSpecAttrs.value) {
				if (!specValuesMap[attr.name] || specValuesMap[attr.name].trim() === '') {
					ElMessage.warning(`请填写规格属性：${attr.name}`);
					return;
				}
			}
		}

		submitLoading.value = true;

		// 构建规格属性数组（与 metadata 格式相同）
		const specValues: any[] = [];
		assetSpecAttrs.value.forEach((attr) => {
			const selectedValue = specValuesMap[attr.name];
			if (selectedValue) {
				// 构建与 metadata 相同的数据结构
				const specItem: any = {
					name: attr.name,
					type: 'multi_select',
					value: [selectedValue],
				};
				// 添加 dictType
				if (attr.dictType) {
					specItem.dictType = attr.dictType;
				}
				// 添加 options（只包含选中的值，格式与 metadata 一致）
				if (attr.options && attr.options.length > 0) {
					// 从 options 中找到选中值对应的完整选项
					const selectedOpt = attr.options.find((opt) => opt.value === selectedValue || opt.label === selectedValue);
					if (selectedOpt) {
						specItem.options = [{ value: selectedOpt.value, label: selectedOpt.label }];
					} else {
						specItem.options = [{ value: selectedValue, label: selectedValue }];
					}
				}
				specValues.push(specItem);
			}
		});

		// 构建 specsUnit 对象格式
		let specsUnitObj: { key: string; value: string } | undefined = undefined;
		if (skuForm.specsUnit) {
			const unitOption = specsUnitOptions.value.find((opt) => opt.key === skuForm.specsUnit);
			specsUnitObj = {
				key: skuForm.specsUnit,
				value: unitOption?.value || skuForm.specsUnit,
			};
		}

		try {
			if (isEditSku.value) {
				// 编辑模式：使用工具函数获取修改过的字段
				const currentFormData = {
					skuName: skuForm.skuName,
					price: skuForm.price,
					stock: skuForm.stock,
					unlimitedStock: skuForm.unlimitedStock,
					status: skuForm.status,
					sort: skuForm.sort,
					imageUrl: skuForm.imageUrl,
					description: skuForm.description,
					specsUnit: skuForm.specsUnit,
					specsCount: skuForm.specsCount,
				};

				const changedFields = skuFormDiff.getChanges(currentFormData, {
					alwaysInclude: ['id'],
					transformers: {
						price: (val) => Math.round(val * 100),
						specsUnit: () => specsUnitObj,
						imageUrl: (val) => val || undefined,
					},
				});

				// 添加 id
				const changedData: Record<string, any> = { id: editSkuId.value, ...changedFields };

				// 比较规格属性
				if (specValuesMapDiff.hasChanges(specValuesMap) && specValues.length > 0) {
					changedData.specValues = specValues;
				}

				await updateAssetSku(changedData as any);
			} else {
				// 新增模式：传递所有字段
				const data = {
					assetId: assetId.value,
					assetName: assetName.value,
					skuName: skuForm.skuName,
					imageUrl: skuForm.imageUrl || undefined,
					specValues: specValues.length > 0 ? specValues : undefined,
					price: Math.round(skuForm.price * 100),
					unlimitedStock: skuForm.unlimitedStock,
					stock: skuForm.stock,
					sort: skuForm.sort,
					status: skuForm.status,
					description: skuForm.description,
					specsUnit: specsUnitObj,
					specsCount: skuForm.specsCount || undefined,
				};
				await createAssetSku(data);
			}
			ElMessage.success(isEditSku.value ? '编辑成功' : '添加成功');
			skuFormVisible.value = false;
			getSkuList();
		} catch (error) {
			// 错误已由拦截器处理
		} finally {
			submitLoading.value = false;
		}
	});
};

// 关闭弹窗
const onClose = () => {
	tableData.value = [];
	total.value = 0;
	resetQuery();
};

defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.sku-search {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}

.spec-values-container {
	.spec-item {
		display: flex;
		align-items: center;
		margin-bottom: 8px;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.spec-label {
		min-width: 60px;
		color: #606266;
		font-size: 14px;
	}
}

.sku-image-uploader {
	:deep(.el-upload) {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 100px;
		height: 100px;
		display: flex;
		align-items: center;
		justify-content: center;

		&:hover {
			border-color: var(--el-color-primary);
		}
	}
}

.sku-image-uploader-icon {
	font-size: 28px;
	color: #8c939d;
}

.sku-image {
	width: 100px;
	height: 100px;
	object-fit: cover;
}
</style>
