<template>
    <div>
        <!-- 封面图 -->
        <div>
            <h5 style="margin: 0; margin-bottom: 16px; font-size: 14px">封面图</h5>

            <div style="display: flex">
                <div>
                    <UploadImg v-model:image-url="imgInfoDataStore.cover_image">
                        <template #tip>
                            <div style="width: 150px; text-align: center">（图片尺寸800x800）</div>
                        </template>
                    </UploadImg>
                </div>
                <!-- <div style="margin-left: 20px">
                    <UploadImg v-model:image-url="imgInfoDataStore.cover_image">
                        <template #tip>
                            <div style="width: 150px; text-align: center">（图片尺寸800x800）</div>
                        </template>
                    </UploadImg>
                </div> -->
            </div>
        </div>
        <el-divider />
        <!-- 属性 -->
        <div>
            <h5 style="margin-bottom: 16px; font-size: 14px">属性</h5>
            <div>
                <!-- 复选框组 -->
                <el-checkbox-group v-model="selectedAttrIds" @change="handleCheckboxChange">
                    <el-checkbox v-for="attr in attrList" :key="attr.id" :label="attr.id">
                        {{ attr.attr_name }}
                    </el-checkbox>
                </el-checkbox-group>
            </div>
        </div>
        <el-divider />
        <!-- 列表图片 -->
        <div>
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px">
                <h5 style="margin: 0; font-size: 14px">列表图信息</h5>
                <el-button type="primary" size="small" @click="addRow()">添加行</el-button>
            </div>
            <!-- 表格 -->
            <el-table :data="imgInfoDataStore.skus" border>
                <el-table-column label="SKU" prop="sku" width="240px">
                    <template #default="{ row }">
                        <el-input style="width: 200px" placeholder="请输入" v-model="row.sku"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="主图" prop="main_image" width="130px">
                    <template #default="{ row }">
                        <UploadImg height="104px" width="104px" v-model:image-url="row.main_image"> </UploadImg>
                    </template>
                </el-table-column>
                <el-table-column v-for="attrId in selectedAttrIds" :key="attrId" :label="findAttrById(attrId)?.attr_name">
                    <template #default="{ row }">
                        <el-form :model="row">
                            <el-form-item v-if="findAttrById(attrId)?.attr_type == 1" style="margin: 0">
                                <el-select v-model="findAttrObjInRow(row, attrId).attr_value" placeholder="请选择">
                                    <el-option
                                        v-for="prop in findAttrById(attrId)?.props"
                                        :key="prop.prop_value"
                                        :label="prop.prop_name"
                                        :value="prop.prop_value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item v-if="findAttrById(attrId)?.attr_type === 2" style="margin: 0">
                                <!-- 生成输入框 -->
                                <el-input v-model="findAttrObjInRow(row, attrId).attr_value" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column label="图片">
                    <template #default="{ row }">
                        <UploadImgs height="80px" width="80px" v-model:fileList="row.photo_album_clone"> </UploadImgs>
                    </template>
                </el-table-column>

                <!-- 删除行操作列 -->
                <el-table-column label="操作" style="display: flex; align-items: center" width="120px">
                    <template #default="{ $index }">
                        <el-button type="danger" @click="deleteRow($index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-divider />
        <!-- 视频 -->
        <div style="margin-bottom: 40px">
            <!-- 视频图片 -->
            <div>
                <h5 style="margin: 0; margin-bottom: 16px; font-size: 14px">视频图</h5>
                <UploadImg v-model:image-url="imgInfoDataStore.video_img"> </UploadImg>
            </div>
            <!-- 视频 -->
            <div>
                <h5 style="margin: 16px 0; font-size: 14px">视频文件</h5>
                <UploadVideo v-model:video-url="imgInfoDataStore.video_url"> </UploadVideo>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts" name="imgInfo">
import { ref, reactive, shallowRef, onMounted } from "vue";
import UploadImg from "@/components/Upload/UploadImg.vue";
import UploadImgs from "@/components/Upload/UploadImgs.vue";
import UploadVideo from "@/components/Upload/UploadVideo.vue";
interface IProps {
    imgInfoData: { [key: string]: any };
    attrList: any[];
}
const props = defineProps<IProps>();
const imgInfoDataRef = shallowRef(props.imgInfoData);
let imgInfoDataStore = reactive({ ...imgInfoDataRef.value });

// 存储选中的属性 ID
const selectedAttrIds = ref<any>([]);

// 根据 ID 查找属性
const findAttrById = (id: any) => {
    return props.attrList.find(attr => attr.id === id);
};

// 在 row 的 attrs 数组中查找对应 attrId 的对象
const findAttrObjInRow = (row: any, attrId: any) => {
    let obj = row.attrs.find((item: any) => item.attr_id === attrId.toString());
    if (!obj) {
        obj = { attr_id: attrId.toString(), attr_value: "" };
        row.attrs = [...row.attrs, obj]; // 避免直接修改原数组
    }
    return obj;
};

// 处理复选框变化事件
const handleCheckboxChange = () => {
    imgInfoDataStore.skus.forEach((row: any) => {
        const newAttrs: any = [];
        selectedAttrIds.value.forEach((attrId: any) => {
            const existingAttr = row.attrs.find((item: any) => item.attr_id === attrId.toString());
            if (existingAttr) {
                newAttrs.push({ ...existingAttr });
            } else {
                newAttrs.push({ attr_id: attrId.toString(), attr_value: "" });
            }
        });
        row.attrs = newAttrs;
    });
};

// 添加新行的方法
const addRow = () => {
    const newRow: any = {
        attrs: []
    };
    selectedAttrIds.value.forEach((attrId: any) => {
        newRow.attrs.push({ attr_id: attrId?.toString(), attr_value: "" });
    });

    imgInfoDataStore.skus.push({
        sku: "", //SKU
        main_image: "", //主图
        photo_album: [], //副图 这个是传给后端的
        photo_album_clone: [], //附图 这个是本地用的
        attrs: []
    });
};
// 删除行的方法
const deleteRow = (index: any) => {
    imgInfoDataStore.skus.splice(index, 1);
};

const echoData = () => {
    const newSkus: any[] = [];
    imgInfoDataStore.skus.forEach((backendRow: any) => {
        const newRow = {
            sku: backendRow.sku,
            main_image: backendRow.main_image,
            photo_album: backendRow.photo_album,
            photo_album_clone: backendRow.photo_album.map((url: any) => {
                const name = url.split("/").pop();
                return { name, url };
            }),
            attrs: []
        };

        backendRow.attrs.forEach((attr: any) => {
            const targetAttr = findAttrObjInRow(newRow, attr.attr_id);

            targetAttr.attr_value = attr.attr_value;
            if (!selectedAttrIds.value.includes(attr.attr_id)) {
                selectedAttrIds.value.push(attr.attr_id);
            }
        });

        newSkus.push(newRow);
    });

    imgInfoDataStore.skus = newSkus;
    handleCheckboxChange();
};
const callEchoDataIfHasValue = () => {
    if (Object.keys(imgInfoDataStore).length > 0) {
        echoData();
    }
};
onMounted(() => {
    callEchoDataIfHasValue();
});
watch(
    () => props.imgInfoData,
    newValue => {
        imgInfoDataRef.value = newValue;
        Object.keys(imgInfoDataStore).forEach(key => delete imgInfoDataStore[key]);
        Object.assign(imgInfoDataStore, newValue);
        callEchoDataIfHasValue();
    },
    { deep: true }
);

defineExpose({
    data: imgInfoDataStore
});
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
