<template>
    <div class="container">
        <!-- 顶部信息 -->
        <div class="containertop">
            <div class="topleft">
                <img src="../../../assets/images/detailsicon/1.png" alt="">
                <span>建筑信息</span>
            </div>
            <div class="topright">
                <el-button type="primary" size="medium" plain v-if="action === 'fill' || !action"
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="addBuildingTag">
                    <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="buildings.length !== 0 && (action === 'fill' || !action)"
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;"
                    @click="handleEdit(selectedBuilding)">
                    <img src="../../../assets/images/detailsicon/icon-bj@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"
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleImport">
                    <i class="el-icon-download" style="width: 0.6rem; height: 0.6rem; margin-right: 4px;"></i>
                    导入
                </el-button>
                <el-button type="primary" size="medium" plain v-if="action === 'fill' || !action"
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleExport">
                    <img src="../../../assets/images/detailsicon/icon-dc@2x.png" alt="导出"
                        style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
                    导出
                </el-button>
            </div>
        </div>
        <!-- 栋数（楼栋名称） -->
        <div class="tagdiv">
            <div v-if="buildings.length === 0" class="no-data"
                style="width: 100%; display: flex;align-items: center;justify-content: center;color: gray;">
                暂无数据
            </div>
            <div class="tagitem" v-for="building in buildings" :key="building.id" @click="selectBuilding(building)"
                :class="[getTagItemClass(building), { 'active-tag': selectedBuilding && selectedBuilding.id === building.id }]">
                <img src="@/assets/images/detailsicon/icon-楼栋@2x.png" alt="">
                <span>{{ building.name }}</span>
                <img src="@/assets/images/detailsicon/icon-gb@2x.png" v-if="action === 'fill' || !action" alt=""
                    @click.stop="handleDelete(building.id)">
            </div>
        </div>
        <!-- 内容区 -->
        <div class="content" v-if="buildings.length > 0">
            <div class="descriptionsdiv">
                <el-descriptions class="margin-top" :column="4" border>
                    <el-descriptions-item>
                        <template slot="label">是否为重要楼栋</template>
                        {{ getTextForBoolean(selectedBuilding.sfwzyld) }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">层数</template>
                        {{ selectedBuilding.floor }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">总建筑高度（米）</template>
                        {{ selectedBuilding.totalBuildingHeight }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">首层高度（平方米）</template>
                        {{ selectedBuilding.scgd }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">2至4层层高（米）：</template>
                        {{ selectedBuilding.twoAndFourCg }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">4层以上层高(米)：</template>
                        {{ selectedBuilding.fourYscg }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">首层地面荷载(吨/)：</template>
                        {{ selectedBuilding.scdmhz }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">二至三层楼面荷载(吨/平方米)：</template>
                        {{ selectedBuilding.twoAndThreeLmhz }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">标准层面积(千平方米)：</template>
                        {{ selectedBuilding.bzcmj }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">柱距：</template>
                        {{ selectedBuilding.zj }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">是否有吊装口：</template>
                        {{ getTextForBoolean(selectedBuilding.sfydzk) }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">是否有汽车盘道：</template>
                        {{ getTextForBoolean(selectedBuilding.sfyqcpd) }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">四层及以上楼面荷载(吨/平方米)：</template>
                        {{ selectedBuilding.fourYslmhz }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </div>
        <!-- 新增楼栋弹窗 -->
        <el-dialog title="新增楼栋" :visible.sync="dialogVisible" width="68%">
            <el-form :model="buildingForm" :rules="rules" ref="buildingFormRef" label-width="260px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="楼栋名称：" prop="name">
                            <el-input v-model="buildingForm.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否为重要楼栋：" prop="sfwzyld">
                            <el-select v-model="buildingForm.sfwzyld" placeholder="请选择" style="width: 22.5rem;">
                                <el-option v-for="dict in dict.type.isno" :key="dict.value" :label="dict.label"
                                    :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="首层高度（米）：" prop="scgd">
                            <el-input v-model="buildingForm.scgd"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="层数：" prop="floor">
                            <el-input v-model="buildingForm.floor"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="4层以上层高（米）：" prop="fourYscg">
                            <el-input v-model="buildingForm.fourYscg"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="柱距：" prop="zj">
                            <el-input v-model="buildingForm.zj"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="2至4层层高（米）：" porp="twoAndFourCg">
                            <el-input v-model="buildingForm.twoAndFourCg"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="总建筑高度（米）：" prop="totalBuildingHeight">
                            <el-input v-model="buildingForm.totalBuildingHeight"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="首层地面荷载（吨/平方米）：" prop="scdmhz">
                            <el-input v-model="buildingForm.scdmhz"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="二至三层楼面荷载（吨/平方米）：" prop="twoAndThreeLmhz">
                            <el-input v-model="buildingForm.twoAndThreeLmhz"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="标准层面积（千平方米）：" prop="bzcmj">
                            <el-input v-model="buildingForm.bzcmj"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否有汽车盘道：" prop="sfyqcpd">
                            <el-select v-model="buildingForm.sfyqcpd" placeholder="请选择" style="width: 22.5rem;">
                                <el-option v-for="dict in dict.type.isno" :key="dict.value" :label="dict.label"
                                    :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="是否有吊装口：" prop="sfydzk">
                            <el-select v-model="buildingForm.sfydzk" placeholder="请选择" style="width: 22.5rem;">
                                <el-option v-for="dict in dict.type.isno" :key="dict.value" :label="dict.label"
                                    :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="四层及以上楼面荷载（吨/平方米）：" prop="fourYslmhz">
                            <el-input v-model="buildingForm.fourYslmhz"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAddBuilding">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getjzxxinformationByxmId, addjzxx, updatejzxx, deletejzxx } from '@/api/ManageApi/index';

export default {
    dicts: ['isno'],
    props: {
        size: {
            type: String,
            default: ''
        },
        xmId: {
            type: [Number, String],
            required: true
        },
        action: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            buildings: [],
            selectedBuilding: null,
            buildingForm: {
                bzcmj: 0,
                createBy: '',
                createId: 0,
                createTime: '',
                floor: 0,
                fourYscg: 0,
                fourYslmhz: 0,
                id: 0,
                name: '',
                scdmhz: 0,
                scgd: 0,
                sfwzyld: 2,
                sfydzk: 2,
                sfyqcpd: 2,
                totalBuildingHeight: 0,
                twoAndFourCg: 0,
                twoAndThreeLmhz: 0,
                updateBy: '',
                updateId: 0,
                updateTime: '',
                xmId: 0,
                zj: 0
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "建筑信息导入",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/gysl/buildingInformation/importProjectBuilding",
            },
            rules: {
                name: [
                    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
                ],
                sfwzyld: [
                    { required: true, message: '请选择是否为重要楼栋', trigger: 'change' }
                ],
                floor: [
                    { required: true, message: '请输入层数', trigger: 'blur' },
                ],
                totalBuildingHeight: [
                    { required: true, message: '请输入总建筑高度（米）', trigger: 'blur' },
                ],
                scgd: [
                    { required: true, message: '请输入首层高度（米）', trigger: 'blur' },
                ],
                twoAndFourCg: [
                    { required: true, message: '请输入2至4层层高（米）', trigger: 'blur' },
                ],
                scdmhz: [
                    { required: true, message: '请输入首层地面荷载（吨/平方米）', trigger: 'blur' },
                ],
                bzcmj: [
                    { required: true, message: '请输入标准层面积（千平方米）', trigger: 'blur' },
                ]
            }
        };
    },
    created() {
        this.fetchBuildings();
    },
    methods: {
        /** 导出 */
        /** 导出 */
        handleExport() {
            this.download(
                "/gysl/basicInformation/exportInfo",
                {
                    idList: this.xmId
                },
                `建筑信息${new Date().getTime()}.xlsx`
            );
        },
        // 导入操作
        handleImport() {
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                "/gysl/buildingInformation/importTemplate",
                {},
                `楼栋导入模板${new Date().getTime()}.xlsx`
            );
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                response.msg +
                "</div>",
                "导入结果",
                { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        //翻译1和2
        getTextForBoolean(value) {
            return value === 1 ? '是' : '否';
        },
        //颜色变化方法
        getTagItemClass(building) {
            return {
                'important-building': building.sfwzyld === 1,
            };
        },
        // 添加建筑信息
        addBuildingTag() {
            this.dialogVisible = true;
            this.buildingForm = {
                bzcmj: '',
                createBy: '',
                createId: '',
                createTime: '',
                floor: '',
                fourYscg: '',
                fourYslmhz: '',
                id: '',
                name: '',
                scdmhz: '',
                scgd: '',
                sfwzyld: 2,
                sfydzk: 2,
                sfyqcpd: 2,
                totalBuildingHeight: '',
                twoAndFourCg: '',
                twoAndThreeLmhz: '',
                updateBy: '',
                updateId: '',
                updateTime: '',
                xmId: this.xmId,
                zj: ''
            };
        },
        fetchBuildings() {
            console.log('Fetching data for xmId:', this.xmId);
            getjzxxinformationByxmId({ xmId: this.xmId })
                .then(response => {
                    console.log('API response:', response);
                    if (response.code === 200 && response.data) {
                        this.buildings = Object.values(response.data); // 将对象转换为数组
                        console.log('Buildings data after assignment:', this.buildings);

                        // 默认选中第一个楼栋
                        if (this.buildings.length > 0) {
                            this.selectedBuilding = this.buildings[0];
                        }
                    } else {
                        console.error('数据格式不正确:', response);
                    }
                })
        },

        selectBuilding(building) {
            this.selectedBuilding = building; // 直接使用传入的building对象
        },
        handleAddBuilding() {
            const api = this.buildingForm.id ? updatejzxx : addjzxx; // 根据是否有ID判断是新增还是更新
            const form = {
                ...this.buildingForm
            };
            api(form)
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success(form.id ? '更新成功' : '新增成功');
                        this.dialogVisible = false;
                        this.fetchBuildings(); // 刷新楼栋列表
                    } else {
                        this.$message.error(form.id ? '更新失败' : '新增失败');
                    }
                })
                .catch(error => {
                    console.error(form.id ? '更新失败:' : '新增失败:', error);
                    this.$message.error(form.id ? '更新失败' : '新增失败');
                });
        },
        handleDelete(id) {
            console.log('Deleting building with ID:', id); // 调试信息

            this.$confirm('你确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deletejzxx([id]) // 传递一个包含ID的数组
                    .then(response => {
                        if (response.code === 200) {
                            this.$message.success('删除成功');
                            this.fetchBuildings(); // 刷新楼栋列表
                        } else {
                            this.$message.error('删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除失败:', error);
                        this.$message.error('删除失败');
                    });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        handleEdit(building) {
            this.dialogVisible = true;
            this.buildingForm = { ...building }; // 填充表单数据
        }
    }
};
</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;
}

.content {
    padding: 1rem;
    display: flex;
}

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

.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: 0.88rem;
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 500;
    font-size: 0.88rem;
    color: #3D424C;
    line-height: 0.88rem;
    text-align: right;
    font-style: normal;
    text-transform: none;
}

.descriptionsdiv {
    width: 100%;
    margin-left: 1rem;
    height: auto;
}

.tagdiv {
    padding: 1rem 2rem 1rem 2rem;
    display: flex;
}

.tagdiv img {
    width: 1.4rem;
    height: 1.5rem;
}

.tagdiv span {
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 400;
    font-size: 0.88rem;
    color: #808080;
    line-height: 0.88rem;
    text-align: right;
    font-style: normal;
    text-transform: none;
}

.tagitem {
    width: 6.25rem;
    height: 2rem;
    background: #FAFAFA;
    border-radius: 2.13rem 2.13rem 2.13rem 2.13rem;
    display: flex;
    justify-content: space-around;
    align-items: center;
    cursor: pointer;
}

.tagitem {
    width: 6.25rem;
    height: 2rem;
    background: #FAFAFA;
    border-radius: 2.13rem 2.13rem 2.13rem 2.13rem;
    display: flex;
    justify-content: space-around;
    align-items: center;
    cursor: pointer;
    border: 1px solid transparent;
    /* 添加透明边框保持布局稳定 */
    transition: all 0.3s ease;
    /* 添加过渡效果 */
}

.tagitem.active-tag {
    border: 1px solid #2B62F1;
    /* 选中时的蓝色边框 */
    box-shadow: 0 0 0 2px rgba(43, 98, 241, 0.2);
    /* 可选的外发光效果 */
}

.tagitem:hover {
    background: #f0f0f0;
    /* 鼠标悬停时的背景色变化 */
}

.important-building {
    background-color: rgba(43, 98, 241, 0.1);
}

.important-building {
    background-color: rgba(43, 98, 241, 0.1);
}
</style>