<template>
    <div class="container">
        <!-- 顶部操作栏 -->
        <div class="containertop">
            <div class="topleft">
                <img src="../../../assets/images/detailsicon/1.png" alt="">
                <span>项目图例</span>
            </div>
            <div class="topright" v-if="action === 'fill' || !action || action === 'okay'">
                <el-button type="primary" size="medium" plain
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleAdd">
                    <img src="../../../assets/images/detailsicon/icon-xz@2x.png" alt="新增"
                        style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
                    新增
                </el-button>
                <el-button type="primary" size="medium" plain v-if="action === 'fill' || !action || action === 'okay'"
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleEdit">
                    <img src="../../../assets/images/detailsicon/icon-xz@2x.png" alt="编辑"
                        style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
                    编辑
                </el-button>
            </div>
        </div>
        
        <!-- 编辑/新增对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
            <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
                <el-form-item label="类型" prop="imgType">
                    <el-select 
                    v-model="form.imgType" placeholder="请选择类型" @change="handleTypeChange">
                    <el-option v-for="dict in dict.type.tplx" :key="dict.value" :label="dict.label"
                            :value="parseInt(dict.value)">
                     </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图片上传" prop="img">
                    <ImageUpload 
                    v-model="form.img" 
                    :file-list="currentTypeFileList" 
                    :multiple="true" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
        </el-dialog>

        <!-- 图片展示 -->
        <div class="longbox">
            <div class="main-content">
                <template v-if="legendsData && legendsData.length > 0">
                    <div v-for="(legend, index) in legendsData" :key="index"
                        style="display: flex;flex-direction: column;gap: 1rem;">
                        <!-- 类型1轮播图 -->
                        <div v-if="legend.type1 && legend.type1.images && legend.type1.images.length > 0">
                            <div class="fixed-carousel-container">
                                <el-carousel height="12.44rem" indicator-position="outside" class="fixed-carousel">
                                    <el-carousel-item v-for="(img, imgIndex) in legend.type1.images"
                                        :key="'type1-' + imgIndex">
                                        <div class="carousel-item-wrapper">
                                            <img :src="baseUrl + img" :alt="'外部图片' + imgIndex" class="fixed-carousel-image">
                                            <div class="classify">外部</div>
                                        </div>
                                    </el-carousel-item>
                                </el-carousel>
                            </div>
                        </div>
                            
                        <!-- 类型2轮播图 -->
                        <div v-if="legend.type2 && legend.type2.images && legend.type2.images.length > 0">
                            <div class="fixed-carousel-container">
                                <el-carousel height="12.44rem" indicator-position="outside" class="fixed-carousel">
                                    <el-carousel-item v-for="(img, imgIndex) in legend.type2.images"
                                        :key="'type2-' + imgIndex">
                                        <div class="carousel-item-wrapper">
                                            <img :src="baseUrl + img" :alt="'内部图片' + imgIndex" class="fixed-carousel-image">
                                            <div class="classify">内部</div>
                                        </div>
                                    </el-carousel-item>
                                </el-carousel>
                            </div>
                        </div>
                    </div>
                </template>
                <div v-else class="no-data">
                    暂无图例数据
                </div>
            </div>
            <div>
                <Projectpicturetwo />
            </div>
        </div>
    </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload';
import { addxmtl, getxmtlPageByxmId } from '@/api/ManageApi/index';
import Projectpicturetwo from '@/views/components/ProjectDetails/Projectpicturetwo.vue';

export default {
    components: { ImageUpload, Projectpicturetwo },
    dicts: ['tplx'],
    props: {
        xmId: {
            type: Number,
            required: true
        },
        action: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            baseUrl: process.env.VUE_APP_BASE_API,
            dialogVisible: false,
            dialogTitle: '新增图例',
            legendsData: [],
            currentTypeFileList: [],
            form: {
                imgType: 1,
                img: [],
                xmId: this.xmId
            },
            rules: {
                imgType: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                img: [
                    { required: true, message: '请上传图片', trigger: 'blur' }
                ]
            }
        };
    },
    created() {
        this.fetchLegendsData();
    },
    methods: {
        // 获取图例数据
        async fetchLegendsData() {
            try {
                if (!this.xmId) {
                    this.$message.error('项目ID不能为空');
                    return;
                }

                const response = await getxmtlPageByxmId({
                    xmId: this.xmId,
                    pageNum: 1,
                    pageSize: 10
                });

                if (response.code === 200) {
                    this.legendsData = response.data || [];
                } else {}
            } catch (error) {}
        },

        updateCurrentTypeFileList() {
            if (!this.legendsData || this.legendsData.length === 0) {
                this.currentTypeFileList = [];
                return;
            }

            const firstLegend = this.legendsData[0];

            //轮播图
            let images = [];
            if (this.form.imgType === 1 && firstLegend.type1) {
                images = firstLegend.type1.images || [];
            } else if (this.form.imgType === 2 && firstLegend.type2) {
                images = firstLegend.type2.images || [];
            }

            //分割图片路径
            this.currentTypeFileList = images.map(url => ({
                url: url,
                name: url.split('/').pop(),
                status: 'success'
            }));

            this.form.img = [...images];
        },

        handleTypeChange() {
            this.updateCurrentTypeFileList();
        },

        handleAdd() {
            this.dialogTitle = '新增图例';
            this.form = {
                imgType: 1,
                img: [],
                xmId: this.xmId
            };
            this.dialogVisible = true;
            this.$nextTick(() => {
                if (this.$refs.formRef) {
                    this.$refs.formRef.clearValidate();
                }
                this.updateCurrentTypeFileList();
            });
        },

        handleEdit() {
            this.dialogTitle = '编辑图例';
            this.form = {
                imgType: 1,
                img: [],
                xmId: this.xmId
            };
            this.dialogVisible = true;
            this.$nextTick(() => {
                if (this.$refs.formRef) {
                    this.$refs.formRef.clearValidate();
                }
                this.updateCurrentTypeFileList();
            });
        },

        handleSubmit() {
            this.$refs.formRef.validate(valid => {
                if (valid) {
                    this.submitForm();
                }
            });
        },

        async submitForm() {
            const loading = this.$loading({
                lock: true,
                text: '提交中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            try {
                if (!this.xmId) {
                    this.$message.error('项目ID不能为空');
                    return;
                }

                const submitData = {
                    ...this.form,
                    imgType: parseInt(this.form.imgType),
                    xmId: this.xmId
                };

                const response = await addxmtl(submitData);
                if (response.code === 200) {
                    this.$message.success(this.dialogTitle === '新增图例' ? '新增成功' : '更新成功');
                    this.dialogVisible = false;
                    await this.fetchLegendsData();
                    this.$emit('refresh');
                } else {
                    this.$message.error(response.msg || '操作失败');
                }
            } catch (error) {} finally {
                loading.close();
            }
        }
    }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
    background-color: #FFFFFF;
    box-shadow: 0rem 0.13rem 0.63rem 0rem rgba(177, 177, 177, 0.1);
    border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
    gap: 1rem;
    overflow: auto;
}

.topleft {
    width: 8rem;
    height: 2rem;
    display: flex;
    gap: 0.4rem;
    align-items: center;
}

.topleft img {
    width: 0.81rem;
    height: 0.81rem;
}

.topleft span {
    width: auto;
    height: 1rem;
    font-family: aliregular;
    font-weight: 500;
    font-size: 1rem;
    color: #3D424C;
    line-height: 1rem;
    text-align: right;
    font-style: normal;
    text-transform: none;
}

.containertop {
    height: auto;
    display: flex;
    justify-content: space-between;
    padding: .5rem;
    border-bottom: 1px solid #E5E5E5;
}

.main-content {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
    padding: 1rem;
    width: 35rem;
}

.type-title {
    margin: 1rem 0 0.5rem;
    font-size: 1rem;
    color: #333;
}

/* 默认轮播图样式 */
.block {
    padding: 0 20px;
}

.el-carousel {
    border-radius: 4px;
}

.carousel-content {
    position: relative;
    height: 100%;
    width: 100%;
}

.carousel-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.classify {
    width: 2.81rem;
    height: 1.38rem;
    background-color: rgba(43, 98, 241, 0.8);
    border-radius: 0.69rem;
    color: white;
    position: absolute;
    bottom: 1rem;
    left: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: .7rem;
    z-index: 98;
}

.no-data {
    text-align: center;
    padding: 2rem;
    color: #999;
}

/* 轮播图指示器样式 */
.el-carousel__indicator {
    padding: 8px 4px;
}

.el-carousel__button {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #c0c4cc;
}

.el-carousel__indicator.is-active .el-carousel__button {
    background-color: #2B62F1;
}

/* 轮播图箭头样式 */
.el-carousel__arrow {
    background-color: rgba(43, 98, 241, 0.3);
    color: #2B62F1;
}

.el-carousel__arrow:hover {
    background-color: rgba(43, 98, 241, 0.5);
}

/* 固定尺寸轮播图样式 */
.fixed-carousel-container {
    width: 21.75rem;
    height: 12.44rem;
    margin: 0 auto;
    position: relative;
}

.fixed-carousel {
    width: 21.75rem;
    height: 12.44rem;
    border-radius: 0.5rem;
    overflow: hidden;
    box-shadow: 0 0.13rem 0.63rem rgba(177, 177, 177, 0.1);
}

.fixed-carousel-image {
    width: 21.75rem;
    height: 12.44rem;
    object-fit: cover;
    display: block;
}

/* 调整指示器位置 */
.el-carousel__indicators {
    bottom: -1.5rem;
}

.longbox {
    display: flex;
    align-items: center;
}
</style>