<template>
    <div>
        <div class="headers">
            <div class="headers-left">
                <div class="imgs">
                    <img v-if="enterpriseLogo" :src="enterpriseLogo" alt="企业LOGO" class="enterprise-logo-img" />
                </div>
                <div class="img-right">
                    <div class="name-title">微育科技</div>
                    <div class="right-name">数智科创 · 通达未来 </div>
                </div>
            </div>
            <div class="headers-right">
                <div class="rights">
                    <div class="rights-names" @click="btnShang">

                        <span>上一级 &lt; </span> <span style="color:#3333;">企业资产负债表信息</span>
                    </div>

                </div>
            </div>
        </div>
        <div class="contents">
            <div class="content-left">
                <div class="content-lefts">
                    <div class="leftss">
                        <div class="leftss-header">
                            <div>{{ year || '2024' }}年 - 企业资产负债表信息（元）</div>
                            <div @click="btnEdint"> <el-button size="small"
                                    style="background-color: #5165f7;color:white;">编辑</el-button>
                            </div>
                        </div>
                        <div class="table-area">
                            <div class="table-header">
                                <div>
                                    <div class="shu"></div><span class="times"> {{ year || '2024' }}年 - 企业资产负债表信息（元）</span>
                                </div>
                                <div style="display: flex;">
                                    <div class="youxiaos">
                                        <el-tooltip class="item" effect="dark"
                                            content="注意！设置“无效”，设置无效后改内容仅保留展但不做应用，默认有效" placement="top-start">
                                            <span> <!-- 单个根元素 -->
                                                <i class="el-icon-info" style="margin-right: 5px;"></i>
                                                <span class="youxiao">有效性设置</span>
                                            </span>
                                        </el-tooltip>

                                    </div>
                                    <div class="yuan">
                                        <div class="yuan-left" v-for="(item, index) in tables" :key="index" :class="{
                                            'yuanright': yuanright === index,
                                            'left-radius': yuanright === 0 && index === 0,
                                            'right-radius': yuanright === 1 && index === 1
                                        }" @click="btnYuan(index)">
                                            {{ item.name }}
                                        </div>


                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="content-table">
                        <div class="table-left">
                            <el-table :data="tableData2" border style="width: 97%">
                                <el-table-column prop="date" label="项目" align="center">
                                    <template #default="{ row }">
                                        <span style="font-weight: bold;">
                                            {{ row.date }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="年（期）末余额" align="center">
                                </el-table-column>
                                <el-table-column prop="address" label="年（期）初余额" align="center">
                                </el-table-column>
                            </el-table>
                        </div>
                     
                    </div>
                </div>
            </div>
            <div class="content-right">

                <div class="leftss-header right-header">
                    <div>企业资产负债表</div>
                    <div> <el-button size="small" style="color:#5165f7;" @click="handleDownload" :disabled="!uploadedImage">
                            <i class="el-icon-download"></i>下载</el-button>
                    </div>
                </div>
                <div class="right-area">
                    <img v-if="uploadedImage" :src="uploadedImage" alt="企业资产负债表" class="uploaded-image" />
                    <div v-else class="no-image-tip">暂无图片</div>
                </div>

            </div>
        </div>

    </div>
</template>
<script>
import { show } from '@/api/homepage/corporateInformation'
import { getEnterpriseLogo } from '@/utils/auth'
import { images } from '@/api/public'
import { save, Detailss } from '@/api/finance/operate/zichang'
export default {
    data() {
        return {
            enterpriseLogo: '', // 企业LOGO图片URL
            year: '', // 年度
            yuanright: 0,
            uploadedImage: '', // 上传的图片URL
            tables: [
                {
                    name: '有效'
                },
                {
                    name: '无效'
                },
            ],
            shu: 0,
            active: 0,
            lastActiveKey: 'headerActiveIndex',
            tableData: [
                {
                    date: "其中",
                    name: "",
                    address: "",
                    children: [
                        { date: "营业利润", name: "10000", address: "8000" },
                        { date: "利润总额", name: "9500", address: "7500" },
                        { date: "净利润", name: "8500", address: "7000" },
                        { date: "综合收益总额", name: "9000", address: "6500" },
                    ],
                },
                { date: "其他项目", name: "5000", address: "4000" },
            ],

            tableData2: [{
                date: '资产总计',
                name: '',
                address: ''
            }, {
                date: '负债合计',
                name: '',
                address: ''
            }, {
                date: '所有者权益合计 (净资产)',
                name: '',
                address: ''
            }]
        }
    },

    created() {
        // 从localStorage加载企业LOGO
        this.loadEnterpriseLogo()
        // 从路由参数获取 id
        const id = this.$route.query.id
        if (id) {
            this.fetchDetail(id)
        }
    },

    watch: {

    },

    methods: {
        // 从localStorage加载企业LOGO
        loadEnterpriseLogo() {
            const logo = getEnterpriseLogo()
            if (logo) {
                this.enterpriseLogo = logo
            }
        },
        // 获取企业LOGO（保留作为备用方法，如果localStorage没有则调用API）
        async fetchEnterpriseLogo() {
            // 先尝试从localStorage读取
            const logo = getEnterpriseLogo()
            if (logo) {
                this.enterpriseLogo = logo
                return
            }
            
            try {
                const res = await show()
                if (res && res.data) {
                    // 数据结构可能是对象（键是数字字符串）或数组
                    let dataToProcess = res.data
                    
                    // 如果是数组，转换为对象格式以便统一处理
                    if (Array.isArray(res.data)) {
                        dataToProcess = {}
                        res.data.forEach((item, index) => {
                            const parentId = item.parent_id !== undefined ? item.parent_id : index
                            dataToProcess[String(parentId)] = item
                        })
                    }
                    
                    // 查找 parent_id: 0 的基本信息（图片数据）
                    if (dataToProcess['0'] && dataToProcess['0'].list && Array.isArray(dataToProcess['0'].list)) {
                        dataToProcess['0'].list.forEach(imgItem => {
                            if (imgItem.name === 'logo' && imgItem.value) {
                                // 如果 value 是完整 URL，直接使用
                                if (imgItem.value.startsWith('http://') || imgItem.value.startsWith('https://')) {
                                    this.enterpriseLogo = imgItem.value
                                } else if (imgItem.host) {
                                    // 如果有 host，组合完整的 URL
                                    const host = imgItem.host.endsWith('/') ? imgItem.host : imgItem.host + '/'
                                    const path = imgItem.value.startsWith('/') ? imgItem.value.slice(1) : imgItem.value
                                    this.enterpriseLogo = host + path
                                } else {
                                    this.enterpriseLogo = imgItem.value
                                }
                            }
                        })
                    }
                }
            } catch (error) {
                console.error('获取企业LOGO失败:', error)
                // 获取失败时不显示错误提示，保持默认样式
            }
        },
        // 获取详情数据
        async fetchDetail(id) {
            try {
                const res = await Detailss(id)
                if (res && res.code === 1 && res.data) {
                    const data = res.data
                    
                    // 设置年度
                    this.year = data.year || ''
                    
                    // 设置有效性：status 1是有效，0是无效
                    this.yuanright = data.status === 1 ? 0 : 1
                    
                    // 设置上传的图片
                    if (data.file) {
                        // 如果 file 是完整 URL，直接使用
                        if (data.file.startsWith('http://') || data.file.startsWith('https://')) {
                            this.uploadedImage = data.file
                        } else {
                            // 如果不是完整 URL，可能需要拼接 host
                            this.uploadedImage = data.file
                        }
                    }
                    
                    // 填充资产负债表数据
                    // 资产总计
                    if (data.asset_end !== undefined) {
                        this.tableData2[0].name = this.formatCurrency(data.asset_end || '0') // 年末资产合计
                    }
                    if (data.asset_begin !== undefined) {
                        this.tableData2[0].address = this.formatCurrency(data.asset_begin || '0') // 年初资产合计
                    }
                    
                    // 负债合计
                    if (data.liability_end !== undefined) {
                        this.tableData2[1].name = this.formatCurrency(data.liability_end || '0') // 年末负债合计
                    }
                    if (data.liability_begin !== undefined) {
                        this.tableData2[1].address = this.formatCurrency(data.liability_begin || '0') // 年初负债合计
                    }
                    
                    // 所有者权益合计
                    if (data.equity_end !== undefined) {
                        this.tableData2[2].name = this.formatCurrency(data.equity_end || '0') // 年末所有者权益合计
                    }
                    if (data.equity_begin !== undefined) {
                        this.tableData2[2].address = this.formatCurrency(data.equity_begin || '0') // 年初所有者权益合计
                    }
                }
            } catch (error) {
                console.error('获取详情失败:', error)
                this.$message.error('获取详情失败，请稍后重试')
            }
        },
        // 格式化金额显示（用于详情页面显示）
        formatCurrency(value) {
            if (value === null || value === undefined || value === '') {
                return '0.00'
            }
            const numValue = Number(value)
            if (isNaN(numValue)) {
                return '0.00'
            }
            return numValue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        },
        //切换时效性
        btnYuan(e) {
            this.yuanright = e
        },
        //编辑跳转
        btnEdint() {
            // 传递 id 和 activeTab 到编辑页面
            const id = this.$route.query.id
            const activeTab = this.$route.query.activeTab || localStorage.getItem('financeOperateActiveTab') || '1'
            if (id) {
                this.$router.push({
                    path: '/zichangEdit',
                    query: { id: id, activeTab: activeTab }
                })
            } else {
                this.$router.push({
                    path: '/zichangEdit',
                    query: { activeTab: activeTab }
                })
            }
        },
        btnShang() {
            // 获取保存的 tab 索引，返回到对应的 tab
            const activeTab = this.$route.query.activeTab || localStorage.getItem('financeOperateActiveTab') || '1'
            this.$router.push({
                name: 'operate',
                query: { activeTab: activeTab }
            })
        },
        // 下载图片
        async handleDownload() {
            if (!this.uploadedImage) {
                this.$message.warning('暂无图片可下载')
                return
            }
            
            try {
                // 创建一个临时的 a 标签用于下载
                const link = document.createElement('a')
                link.href = this.uploadedImage
                link.download = `企业资产负债表_${this.year || '资产负债表'}.jpg` // 设置下载文件名
                link.target = '_blank'
                
                // 如果是跨域图片，需要使用 fetch 获取 blob
                if (this.uploadedImage.startsWith('http://') || this.uploadedImage.startsWith('https://')) {
                    try {
                        const response = await fetch(this.uploadedImage)
                        const blob = await response.blob()
                        const blobUrl = URL.createObjectURL(blob)
                        
                        link.href = blobUrl
                        document.body.appendChild(link)
                        link.click()
                        document.body.removeChild(link)
                        
                        // 释放 URL 对象
                        setTimeout(() => {
                            URL.revokeObjectURL(blobUrl)
                        }, 100)
                    } catch (error) {
                        console.error('下载失败:', error)
                        // 如果 fetch 失败，尝试直接打开新窗口
                        window.open(this.uploadedImage, '_blank')
                        this.$message.warning('下载失败，已在新窗口打开图片，请右键保存')
                    }
                } else {
                    // 同域图片，直接下载
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                }
                
                this.$message.success('下载成功')
            } catch (error) {
                console.error('下载失败:', error)
                this.$message.error('下载失败，请稍后重试')
            }
        }

    }
}
</script>
<style>
.el-tooltip__popper.is-dark {
    color: #F04B4B !important;
    background: #FCF1EB !important;
}

.el-tooltip__popper .popper__arrow {
    border-top-color: #FCF1EB !important;
    /* 上方箭头 */
}

.el-tooltip__popper .popper__arrow::after {
    border-top-color: #FCF1EB !important;
}

/* 其他方向的箭头（按需添加） */
.el-tooltip__popper[x-placement^='bottom'] .popper__arrow {
    border-bottom-color: #FCF1EB !important;
}

.el-tooltip__popper[x-placement^='left'] .popper__arrow {
    border-left-color: #FCF1EB !important;
}

.el-tooltip__popper[x-placement^='right'] .popper__arrow {
    border-right-color: #FCF1EB !important;
}
</style>
<style scoped>
:deep .el-tooltip__popper.is-dark {
    color: #F04B4B !important;
}

.right-area {
    width: 90%;
    margin: 0 auto;
    height: 80vh;
    background: #f8f8f8;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: auto;
    padding: 20px;
}

.uploaded-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.no-image-tip {
    color: #909399;
    font-size: 14px;
    text-align: center;
}

.right-header {
    width: 90%;
    margin: 0 auto;
}

.ths {
    text-align: center;
    background: #DCE0FD !important;
    color: #363636;
}

.tou {
    height: 30px;
    line-height: 30px;
    color: #606266;
    text-align: center;
}

.financial-table {
    width: 100%;
    border-collapse: collapse;
    font-family: Arial, sans-serif;
    font-size: 14px;
}

.financial-table th,
.financial-table td {
    border: 1px solid #ddd;
    padding: 8px 7px;
    text-align: center;
}

.financial-table th {
    background-color: #f5f5f5;
    font-weight: bold;
}

.financial-table .nested-label {
   
    text-align: center;
    vertical-align: middle;
    font-weight: bold;
}

.table-right {
    flex: 1;
}

.table-left {
    flex: 1;
}

.content-table {
    
    width: 90%;
    margin: 0 auto;
    margin-top: 14px;
}

/* 默认情况（有效）左边圆角 */
.left-radius {
    border-bottom-left-radius: 16px !important;
    border-top-left-radius: 16px !important;
}

/* 无效情况右边圆角 */
.right-radius {
    border-bottom-right-radius: 16px !important;
    border-top-right-radius: 16px !important;
}

.yuan-left {
    flex: 1;
    text-align: center;
    line-height: 30px;
    background: #f8f8f8;
    /* border-bottom-left-radius: 16px;
    border-top-left-radius: 16px; */
    cursor: pointer;
}

.yuanright {
    flex: 1;
    background: #5165f7;
    color: white;

    /* border-bottom-right-radius: 16px;
    border-top-right-radius: 16px;  */
    text-align: center;
    line-height: 30px;
    cursor: pointer;

}

.youxiaos {
    position: relative;
    top: 6px;
    left: -12px;
    cursor: pointer;
}

/* 修改.yuan的样式，移除外层圆角 */
.yuan {
    width: 100px;
    height: 30px;
    background: white;
    display: flex;
    font-size: 14px;
    overflow: hidden;
    /* 关键：确保内部div的圆角效果不被截断 */
}

/* 默认状态下两个按钮的外侧圆角 */
.yuan-left:first-child {
    border-top-left-radius: 16px;
    border-bottom-left-radius: 16px;
}

.yuan-left:last-child {
    border-top-right-radius: 16px;
    border-bottom-right-radius: 16px;
}

/* 选中状态样式 */
.yuanright {
    background: #5165f7;
    color: white;
}

/* 选中"有效"时的样式 */
.yuan-left.left-radius {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
}

/* 选中"无效"时的样式 */
.yuan-left.right-radius {
    border-top-left-radius: 0 !important;
    border-bottom-left-radius: 0 !important;
}


.times {
    position: relative;
    top: 3px;
}

.youxiao {
    color: #5B5D76;
    font-size: 13px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    margin-top: 14px;
}

.table-area {
    margin-top: 12px;
    font-size: 15px;
}

.leftss-header {
    display: flex;
    height: 60px;
    line-height: 60px;
    border-bottom: 1px solid #3333;
    font-weight: bold;
    justify-content: space-between;
}

.leftss {
    width: 90%;
    margin: 0 auto;
}

.content-lefts {
    background: white;
    height: 100%;
    width: 100%;
}

.content-left {
    flex: 1;
    padding-right: 12px;
    height: 100%;
}

.content-right {
    width: 600px;
    height: 100%;
    background: white;
}

.contents {
    width: 100%;
    height: 92vh;
    background: #f8f8f8;
    display: flex;
    margin-top: 6px;
    /* flex-wrap: wrap */
}


.shu {
    width: 3px;
    height: 18px;
    background: #5165f7;
    position: relative;
    display: inline-block;
    top: 7px;
}

::v-deep .el-table thead {
    background-color: #DCE0FD !important;
    color: #363636 !important;
    font-weight: bold;
}

::v-deep .el-table__header th {
    background-color: #DCE0FD !important;
    color: #363636 !important;
    font-weight: bold;
}


.active{
    color: #5165f7 !important;
}
.rights-names{
    margin-left: 32px;
    cursor: pointer;
}
.rights{
    width: 96%;
    height: 100%;
    margin: 0 auto;
    line-height: 94px;
    display: flex;
    position: relative;
    left: -27px;
}
.name-title{
    position: relative;
    top: -6px;
    font-weight: bold;
}
.right-name{
    font-size: 12px;
}
.img-right{
    font-size: 14px;
    position: relative;
    top: 40px;
    height: 40px;
    margin-left: 12px;
}
.imgs{
    width: 45px;
    height: 46px;
    background: #5165f7;
    border-radius: 6px;
    position: relative;
    top: 26px;
    margin-left: 24px;
    overflow: hidden;
}

.enterprise-logo-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}
.headers-right{
    flex: 1;
    background: white;
  
}
.headers-left{
    width: 222px;
    height: 100%;
    display: flex;
    background: white;
    border-right: 1px solid #EDEFFE;
}
.headers{
  width: 100%;
    height: 90px;
    display: flex
;
    border-bottom: 1px solid #EDEFFE;
}
</style>