<template>
    <div class="app-container">
        <!-- 商品基本信息 -->
        <div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
            <el-form ref="productRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="商品分类" prop="categoryId">
                    <el-select
                        v-model="form.categoryId"
                        placeholder="请选择商品分类"
                        style="width: 100%"
                        filterable
                        :remote-method="remoteMethod"
                    >
                        <el-option
                            v-for="value in productCategoryList"
                            :label="value.categoryName"
                            :value="value.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="form.productName" placeholder="请输入商品名称" />
                </el-form-item>
                <!-- <el-form-item label="副标题" prop="subTitle">
                    <el-input v-model="form.subTitle" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->
                <el-form-item label="主图URL" prop="mainImage">
                    <image-upload v-model="form.mainImage" :limit="1" />
                </el-form-item>
                <el-form-item label="商品相册" prop="imageGallery">
                    <image-upload v-model="form.imageGallery" :limit="5" />
                </el-form-item>

                <!-- SKU管理 -->
                <div class="sku-management">
                    <div class="sku-header flex justify-between items-center margin-bottom-20">
                        <h3 class="text-16 font-600">商品规格(SKU)</h3>
                        <el-button type="primary" @click="handleAddSku" size="small">
                            <i class="el-icon-plus"></i>
                            添加SKU
                        </el-button>
                    </div>

                    <!-- SKU列表表格 -->
                    <div
                        v-if="form.productSkuList && form.productSkuList.length > 0"
                        class="sku-table-wrapper"
                    >
                        <el-table :data="form.productSkuList" border size="small" class="sku-table">
                            <el-table-column type="index" width="50" label="序号" align="center" />
                            <el-table-column prop="skuCode" label="SKU编码" min-width="120">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.skuCode"
                                        placeholder="SKU编码"
                                        size="small"
                                        @change="validateSkuCode(row, $index)"
                                        :class="{ 'error-border': row.skuError }"
                                    />
                                    <div v-if="row.skuError" class="field-error">
                                        {{ row.skuError }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="specText" label="规格文本" min-width="120">
                                <template #default="{ row }">
                                    <el-input
                                        v-model="row.specText"
                                        placeholder="如：红色/128G"
                                        size="small"
                                        :class="{ 'error-border': row.specTextError }"
                                        @blur="validateSpecText(row)"
                                    />
                                    <div v-if="row.specTextError" class="field-error">
                                        {{ row.specTextError }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="销售价" width="180" align="left">
                                <template #default="{ row }">
                                    <el-input
                                        v-model.number="row.price"
                                        type="number"
                                        min="0"
                                        step="0.01"
                                        placeholder="价格"
                                        size="small"
                                        :class="{ 'error-border': row.priceError }"
                                        @blur="validatePrice(row)"
                                        @change="updatePriceRange"
                                    >
                                        <template #append>元</template>
                                    </el-input>
                                    <div v-if="row.priceError" class="field-error">
                                        {{ row.priceError }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="originalPrice"
                                label="原价"
                                width="180"
                                align="left"
                            >
                                <template #default="{ row }">
                                    <el-input
                                        v-model.number="row.originalPrice"
                                        type="number"
                                        min="0"
                                        step="0.01"
                                        placeholder="原价"
                                        size="small"
                                        :class="{ 'error-border': row.originalPriceError }"
                                        @blur="validateOriginalPrice(row)"
                                    >
                                        <template #append>元</template>
                                    </el-input>
                                    <div v-if="row.originalPriceError" class="field-error">
                                        {{ row.originalPriceError }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="stockQuantity"
                                label="库存"
                                width="120"
                                align="left"
                            >
                                <template #default="{ row }">
                                    <el-input
                                        v-model.number="row.stockQuantity"
                                        type="number"
                                        min="0"
                                        placeholder="库存"
                                        size="small"
                                        :class="{ 'error-border': row.stockQuantityError }"
                                        @blur="validateStockQuantity(row)"
                                    />
                                    <div v-if="row.stockQuantityError" class="field-error">
                                        {{ row.stockQuantityError }}
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column
                                prop="isDefault"
                                label="默认"
                                width="80"
                                align="center"
                            >
                                <template #default="{ row, $index }">
                                    <el-radio
                                        v-model="form.defaultSkuIndex"
                                        :label="$index"
                                        @change="setDefaultSku($index)"
                                    >
                                        {{ row.isDefault === 1 ? '是' : '否' }}
                                    </el-radio>
                                </template>
                            </el-table-column>
                            <el-table-column prop="isEnable" label="状态" width="80" align="center">
                                <template #default="{ row }">
                                    <el-switch
                                        v-model="row.isEnable"
                                        :active-value="1"
                                        :inactive-value="0"
                                        active-color="#13ce66"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100" align="center" fixed="right">
                                <template #default="{ row, $index }">
                                    <el-button
                                        type="text"
                                        size="small"
                                        style="color: #f56c6c"
                                        @click="handleRemoveSku($index)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- SKU统计信息 -->
                        <div class="sku-summary margin-top-20">
                            <el-space>
                                <el-tag type="info">
                                    SKU数量: {{ form.productSkuList?.length || 0 }}
                                </el-tag>
                                <el-tag type="primary">库存总量: {{ totalStock }}</el-tag>
                                <el-tag type="success">
                                    价格区间: ￥{{ form.minPrice || 0 }} - ￥{{
                                        form.maxPrice || 0
                                    }}
                                </el-tag>
                                <el-tag :type="hasDuplicateSku ? 'danger' : 'success'">
                                    {{ hasDuplicateSku ? '有重复SKU编码' : 'SKU编码无重复' }}
                                </el-tag>
                                <el-tag :type="hasSkuValidationError ? 'danger' : 'success'">
                                    {{ hasSkuValidationError ? '存在验证错误' : 'SKU信息完整' }}
                                </el-tag>
                            </el-space>
                        </div>
                    </div>

                    <!-- 无SKU提示 -->
                    <div v-else class="empty-sku">
                        <el-empty description="暂无SKU，请点击上方按钮添加" :image-size="60" />
                    </div>
                </div>

                <!-- <el-form-item label="商品单位" prop="unit" style="margin-top: 20px">
                    <el-input v-model="form.unit" placeholder="请输入商品单位" />
                </el-form-item>
                <el-form-item label="重量(kg)" prop="weight">
                    <el-input
                        v-model.number="form.weight"
                        type="number"
                        placeholder="请输入重量(kg)"
                    />
                </el-form-item> -->
                <el-form-item label="排序" prop="sortOrder">
                    <el-input
                        v-model.number="form.sortOrder"
                        type="number"
                        placeholder="请输入排序"
                    />
                </el-form-item>
                <el-form-item label="总销量" prop="salesCount">
                    <el-input
                        v-model.number="form.salesCount"
                        type="number"
                        placeholder="请输入总销量"
                    />
                </el-form-item>
                <el-form-item label="浏览数" prop="viewCount">
                    <el-input
                        v-model.number="form.viewCount"
                        type="number"
                        placeholder="请输入浏览数"
                    />
                </el-form-item>
                <el-form-item label="收藏数" prop="likeCount">
                    <el-input
                        v-model.number="form.likeCount"
                        type="number"
                        placeholder="请输入收藏数"
                    />
                </el-form-item>
                <el-form-item label="最低价格" prop="minPrice">
                    <el-input
                        v-model.number="form.minPrice"
                        type="number"
                        placeholder="请输入最低价格"
                        :disabled="true"
                    />
                </el-form-item>
                <el-form-item label="最高价格" prop="maxPrice">
                    <el-input
                        v-model.number="form.maxPrice"
                        type="number"
                        placeholder="请输入最高价格"
                        :disabled="true"
                    />
                </el-form-item>
                <el-form-item label="商品描述">
                    <Editor v-model="form.description" :min-height="192" />
                </el-form-item>
            </el-form>

            <!-- 操作按钮 -->
            <div class="dialog-footer text-center">
                <el-button type="primary" @click="submitForm" :loading="submitLoading">
                    保存商品
                </el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </div>
    </div>
</template>

<script setup name="ProductDetailWithSku">
import { useRoute, useRouter } from 'vue-router';
import { getProduct, addProduct, updateProduct } from '@/api/service/product';
import { listProductCategory } from '@/api/service/productCategory';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

// 提交加载状态
const submitLoading = ref(false);
const productCategoryList = ref([]);

// 商品数据
const data = reactive({
    form: {
        id: null,
        categoryId: null,
        spuCode: null,
        productName: null,
        subTitle: null,
        mainImage: null,
        imageGallery: null,
        description: null,
        unit: null,
        weight: null,
        status: 1, // 默认启用
        isHot: 0,
        isRecommend: 0,
        sortOrder: 0,
        salesCount: 0,
        viewCount: 0,
        likeCount: 0,
        minPrice: 0,
        maxPrice: 0,
        productSkuList: [], // 新增SKU列表字段
        defaultSkuIndex: -1, // 默认SKU索引
    },
    rules: {
        categoryId: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
        productName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
        mainImage: [{ required: true, message: '主图URL不能为空', trigger: 'blur' }],
        unit: [{ required: true, message: '商品单位不能为空', trigger: 'blur' }],
        productSkuList: [
            {
                validator: (rule, value, callback) => {
                    if (!value || value.length === 0) {
                        callback(new Error('请至少添加一个SKU'));
                    } else if (data.hasDuplicateSku) {
                        callback(new Error('存在重复的SKU编码，请检查'));
                    } else if (data.hasSkuValidationError) {
                        callback(new Error('SKU信息填写不完整或有误，请检查'));
                    } else {
                        callback();
                    }
                },
                trigger: 'blur',
            },
        ],
    },
});

const { form, rules } = toRefs(data);

// 计算属性
const totalStock = computed(() => {
    if (!form.value.productSkuList) return 0;
    return form.value.productSkuList.reduce((sum, sku) => {
        return sum + (Number(sku.stockQuantity) || 0);
    }, 0);
});

const hasDuplicateSku = computed(() => {
    if (!form.value.productSkuList) return false;
    const skuCodes = form.value.productSkuList.map(sku => sku.skuCode?.trim()).filter(code => code);
    return new Set(skuCodes).size !== skuCodes.length;
});

const hasSkuValidationError = computed(() => {
    if (!form.value.productSkuList) return false;
    return form.value.productSkuList.some(
        sku =>
            sku.skuError ||
            sku.specTextError ||
            sku.priceError ||
            sku.originalPriceError ||
            sku.stockQuantityError
    );
});

// 初始化SKU数据
const initSkuData = () => {
    return {
        id: null,
        productId: null,
        skuCode: '',
        specData: '',
        specText: '',
        price: 0,
        originalPrice: 0,
        stockQuantity: 0,
        warningStock: 0,
        salesVolume: 0,
        skuImage: '',
        barcode: '',
        isDefault: 0,
        isEnable: 1,
        // 错误信息字段
        skuError: '',
        specTextError: '',
        priceError: '',
        originalPriceError: '',
        stockQuantityError: '',
    };
};

// 添加SKU
const handleAddSku = () => {
    if (!form.value.productSkuList) {
        form.value.productSkuList = [];
    }

    const newSku = initSkuData();
    form.value.productSkuList.push(newSku);

    // 如果是第一个SKU，设置为默认
    if (form.value.productSkuList.length === 1) {
        setDefaultSku(0);
    }

    // 更新价格区间
    updatePriceRange();
};

// 生成SKU编码
const generateSkuCode = () => {
    const spuCode = form.value.spuCode || 'SPU';
    const timestamp = new Date().getTime().toString().slice(-6);
    const random = Math.random().toString(36).substr(2, 4).toUpperCase();
    return `${spuCode}_${timestamp}${random}`;
};

// 删除SKU
const handleRemoveSku = index => {
    proxy.$modal.confirm('确定要删除这个SKU吗？').then(() => {
        form.value.productSkuList.splice(index, 1);

        // 如果删除的是默认SKU，重置默认索引
        if (form.value.defaultSkuIndex === index) {
            form.value.defaultSkuIndex = -1;
            if (form.value.productSkuList.length > 0) {
                setDefaultSku(0);
            }
        } else if (form.value.defaultSkuIndex > index) {
            form.value.defaultSkuIndex--;
        }

        updatePriceRange();
    });
};

// 设置默认SKU
const setDefaultSku = index => {
    form.value.defaultSkuIndex = index;
    form.value.productSkuList.forEach((sku, i) => {
        sku.isDefault = i === index ? 1 : 0;
    });
};

// 验证SKU编码
const validateSkuCode = (row, index) => {
    // 清除之前的错误
    row.skuError = '';

    // if (!row.skuCode || row.skuCode.trim() === '') {
    //     row.skuError = 'SKU编码不能为空';
    //     return false;
    // }

    // 检查重复
    const duplicateIndex = form.value.productSkuList.findIndex(
        (sku, i) => i !== index && sku.skuCode === row.skuCode
    );

    if (duplicateIndex !== -1) {
        row.skuError = 'SKU编码已存在';
        return false;
    }

    return true;
};

// 验证规格文本
const validateSpecText = row => {
    // 清除之前的错误
    row.specTextError = '';

    if (!row.specText || row.specText.trim() === '') {
        row.specTextError = '规格文本不能为空';
        return false;
    }

    return true;
};

// 验证销售价格
const validatePrice = row => {
    // 清除之前的错误
    row.priceError = '';

    if (row.price === null || row.price === undefined || row.price === '') {
        row.priceError = '销售价不能为空';
        return false;
    }

    const price = Number(row.price);
    if (isNaN(price)) {
        row.priceError = '请输入有效的数字';
        return false;
    }

    if (price < 0) {
        row.priceError = '价格不能为负数';
        return false;
    }

    if (price === 0) {
        row.priceError = '价格不能为0';
        return false;
    }

    return true;
};

// 验证原价
const validateOriginalPrice = row => {
    // 清除之前的错误
    row.originalPriceError = '';

    if (row.originalPrice === null || row.originalPrice === undefined || row.originalPrice === '') {
        row.originalPriceError = '原价不能为空';
        return false;
    }

    const originalPrice = Number(row.originalPrice);
    if (isNaN(originalPrice)) {
        row.originalPriceError = '请输入有效的数字';
        return false;
    }

    if (originalPrice < 0) {
        row.originalPriceError = '原价不能为负数';
        return false;
    }

    return true;
};

// 验证库存
const validateStockQuantity = row => {
    // 清除之前的错误
    row.stockQuantityError = '';

    if (row.stockQuantity === null || row.stockQuantity === undefined || row.stockQuantity === '') {
        row.stockQuantityError = '库存不能为空';
        return false;
    }

    const stockQuantity = Number(row.stockQuantity);
    if (isNaN(stockQuantity)) {
        row.stockQuantityError = '请输入有效的数字';
        return false;
    }

    if (stockQuantity < 0) {
        row.stockQuantityError = '库存不能为负数';
        return false;
    }

    // 检查是否为整数
    if (!Number.isInteger(stockQuantity)) {
        row.stockQuantityError = '库存必须为整数';
        return false;
    }

    return true;
};

// 验证所有SKU字段
const validateAllSkuFields = () => {
    if (!form.value.productSkuList) return false;

    let isValid = true;
    form.value.productSkuList.forEach((sku, index) => {
        validateSkuCode(sku, index);
        validateSpecText(sku);
        validatePrice(sku);
        validateOriginalPrice(sku);
        validateStockQuantity(sku);

        // 检查是否有任何错误
        if (
            sku.skuError ||
            sku.specTextError ||
            sku.priceError ||
            sku.originalPriceError ||
            sku.stockQuantityError
        ) {
            isValid = false;
        }
    });

    return isValid;
};

// 格式化规格数据
const formatSpecData = row => {
    if (!row.specData) return;

    try {
        // 如果是JSON字符串，尝试解析
        if (row.specData.trim().startsWith('{')) {
            const specObj = JSON.parse(row.specData);
            // 生成规格文本
            row.specText = Object.values(specObj).join('/');
        }
    } catch (e) {
        console.warn('规格数据格式错误:', e);
    }
};

// 更新价格区间
const updatePriceRange = () => {
    if (!form.value.productSkuList || form.value.productSkuList.length === 0) {
        form.value.minPrice = 0;
        form.value.maxPrice = 0;
        return;
    }

    const prices = form.value.productSkuList
        .filter(sku => sku.isEnable === 1)
        .map(sku => Number(sku.price) || 0)
        .filter(price => price > 0);

    if (prices.length === 0) {
        form.value.minPrice = 0;
        form.value.maxPrice = 0;
        return;
    }

    form.value.minPrice = Math.min(...prices);
    form.value.maxPrice = Math.max(...prices);
};

// 监听SKU列表变化
watch(
    () => form.value.productSkuList,
    () => {
        updatePriceRange();
    },
    { deep: true }
);

// 获取商品详情
const getProductDetail = async () => {
    if (route.query.productId) {
        try {
            const response = await getProduct(route.query.productId);
            const productData = response.data;

            // 处理SKU数据
            if (productData.productSkuList && productData.productSkuList.length > 0) {
                // 找到默认SKU的索引
                const defaultIndex = productData.productSkuList.findIndex(
                    sku => sku.isDefault === 1
                );
                productData.defaultSkuIndex = defaultIndex;

                // 初始化错误字段
                productData.productSkuList.forEach(sku => {
                    sku.skuError = '';
                    sku.specTextError = '';
                    sku.priceError = '';
                    sku.originalPriceError = '';
                    sku.stockQuantityError = '';
                });
            } else {
                productData.productSkuList = [];
                productData.defaultSkuIndex = -1;
            }

            form.value = productData;
        } catch (error) {
            console.error('获取商品详情失败:', error);
            proxy.$modal.msgError('获取商品信息失败');
        }
    } else {
        // 新增商品时初始化一个默认SKU
        handleAddSku();
    }
};

// 准备提交的数据
const prepareSubmitData = () => {
    const submitData = { ...form.value };

    // 移除前端使用的字段
    delete submitData.defaultSkuIndex;

    // 确保SKU列表中的productId正确
    if (submitData.productSkuList) {
        submitData.productSkuList.forEach(sku => {
            if (!sku.id) {
                delete sku.id; // 新增的SKU不应该有id
            }
            // 设置productId
            sku.productId = submitData.id;
            // 移除错误信息字段
            delete sku.skuError;
            delete sku.specTextError;
            delete sku.priceError;
            delete sku.originalPriceError;
            delete sku.stockQuantityError;
        });
    }

    return submitData;
};

// 提交表单
const submitForm = async () => {
    try {
        // 先验证所有SKU字段
        const isSkuValid = validateAllSkuFields();
        if (!isSkuValid) {
            proxy.$modal.msgWarning('请检查SKU信息填写是否完整');
            return;
        }

        if (hasDuplicateSku.value) {
            proxy.$modal.msgWarning('存在重复的SKU编码，请检查');
            return;
        }

        // 验证商品表单
        await proxy.$refs.productRef.validate();

        if (!form.value.productSkuList || form.value.productSkuList.length === 0) {
            proxy.$modal.msgWarning('请至少添加一个SKU');
            return;
        }

        submitLoading.value = true;

        const submitData = prepareSubmitData();

        let response;
        if (submitData.id) {
            response = await updateProduct(submitData);
            proxy.$modal.msgSuccess('修改成功');
        } else {
            response = await addProduct(submitData);
            proxy.$modal.msgSuccess('新增成功');
        }

        // 处理响应
        if (response.code === 200) {
            // 保存成功后可以跳转或关闭页面
            setTimeout(() => {
                proxy.$tab.closePage();
            }, 1500);
        }
    } catch (error) {
        console.error('保存失败:', error);
        proxy.$modal.msgError(error.message || '保存失败');
    } finally {
        submitLoading.value = false;
    }
};

// 取消
const cancel = () => {
    proxy.$modal.confirm('确定要取消吗？未保存的数据将会丢失。').then(() => {
        proxy.$tab.closePage();
    });
};

const remoteMethod = query => {
    if (query) {
        getProductList(query.toLowerCase());
    } else {
    }
};

/** 查询商品分类列表 */
function getList(name) {
    listProductCategory(proxy.CloneData({ pageNum: 1, pageSize: 100, productName: name })).then(
        response => {
            productCategoryList.value = response.rows;
        }
    );
}

// 初始化加载
onMounted(() => {
    getList();
    getProductDetail();
});
</script>

<style scoped>
.flex {
    display: flex;
}
.justify-between {
    justify-content: space-between;
}
.items-center {
    align-items: center;
}
.text-16 {
    font-size: 16px;
}
.font-600 {
    font-weight: 600;
}
.text-center {
    text-align: center;
}
.margin-top-20 {
    margin-top: 20px;
}
.margin-bottom-20 {
    margin-bottom: 20px;
}

.sku-management {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    background: #fafafa;
}

.sku-header {
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.sku-table-wrapper {
    margin-top: 20px;
}

.sku-table {
    width: 100%;
    margin-bottom: 20px;
}

.sku-table :deep(.el-table__cell) {
    padding: 8px 0;
}

.sku-table :deep(.el-input) {
    width: 100%;
}

.sku-table :deep(.error-border) {
    border-color: #f56c6c;
}

.sku-table :deep(.error-border:focus) {
    border-color: #f56c6c;
    box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

.field-error {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
    line-height: 1.2;
    min-height: 16px;
}

.sku-summary {
    padding: 10px 0;
    border-top: 1px dashed #ebeef5;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
}

.empty-sku {
    padding: 40px 0;
    text-align: center;
    color: #909399;
    background: #fff;
    border-radius: 4px;
    border: 1px dashed #dcdfe6;
}

.dialog-footer {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}
</style>
