<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 class="header-user-section">
                 
                    <el-dropdown ref="userDropdown" trigger="click" @command="handleCommand">
                        <div class="user-info">
                            <div class="user-avatar">{{ userAvatarChar }}</div>
                            <div class="user-details">
                                <div class="user-name">
                                    {{ userNickname || '言雨天' }}
                                    <i class="el-icon-arrow-down"></i>
                                </div>
                                <div class="user-phone">{{ userPhone || '13424098909' }}</div>
                            </div>
                        </div>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="changePassword">
                                <i class="el-icon-lock"></i>
                                修改密码
                            </el-dropdown-item>
                            <el-dropdown-item command="changePhone">
                                <i class="el-icon-mobile-phone"></i>
                                更换手机账号
                            </el-dropdown-item>
                            <el-dropdown-item command="logout">
                                <i class="el-icon-switch-button"></i>
                                退出
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </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 class="table-right">
                            <table class="financial-table">
                                <thead>
                                    <tr class="tou">
                                        <th colspan="2" class="ths" style="text-align: center;">项目</th>
                                        <th class="ths" style="text-align: center;">本年（期）金额</th>
                                        <th class="ths" style="text-align: center;">上年（期）金额</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="tou">
                                        <td colspan="2" style="text-align: center;">营业成本</td>
                                        <td>{{ tableData3[0].currentAmount || '0.00' }}</td>
                                        <td>{{ tableData3[0].lastAmount || '0.00' }}</td>
                                    </tr>
                                    <tr class="tou">
                                        <td rowspan="4" class="nested-label">其中</td>
                                        <td>销售费用</td>
                                        <td>{{ tableData3[1].currentAmount || '0.00' }}</td>
                                        <td>{{ tableData3[1].lastAmount || '0.00' }}</td>
                                    </tr>
                                    <tr class="tou">
                                        <td>管理费用</td>
                                        <td>{{ tableData3[2].currentAmount || '0.00' }}</td>
                                        <td>{{ tableData3[2].lastAmount || '0.00' }}</td>
                                    </tr>
                                    <tr class="tou">
                                        <td>研发费用</td>
                                        <td>{{ tableData3[3].currentAmount || '0.00' }}</td>
                                        <td>{{ tableData3[3].lastAmount || '0.00' }}</td>
                                    </tr>
                                    <tr class="tou">
                                        <td>财务费用</td>
                                        <td>{{ tableData3[4].currentAmount || '0.00' }}</td>
                                        <td>{{ tableData3[4].lastAmount || '0.00' }}</td>
                                    </tr>
                                </tbody>
                            </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>

        <!-- 修改密码对话框 -->
        <el-dialog
            title="修改密码"
            :visible.sync="passwordDialogVisible"
            width="60%"
            :close-on-click-modal="false"
            class="change-password-dialog">
            <div class="contents">
                <div class="container">
                    <table class="department-table">
                        <tr>
                            <td class="th1">原始密码 </td>
                            <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入内容" show-password></el-input>
                        </tr>
                        <tr>
                            <td class="th1">新的密码 </td>
                            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入内容" show-password></el-input>
                        </tr>
                    </table>
                    <div style="margin-top: 18px;">
                        密码要求：
                    </div>
                   <div style="margin-top:6px">
                      密码要求至少包含字母，符号或数字中的两项且长度超过8位，建议您经常修改密码，以保证账号更加安全。
                   </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" style="background-color: #5165f7;" @click="confirmChangePassword" >确定</el-button>
                <el-button @click="cancelChangePassword" >取消</el-button>
            </div>
        </el-dialog>
        
        <!-- 更换手机账号对话框 -->
        <el-dialog
            title="更换手机账号"
            :visible.sync="phoneDialogVisible"
            width="60%"
            :close-on-click-modal="false"
            class="change-phone-dialog">
            <div class="contents">
                <div class="container">
                    <table class="department-table">
                        <tr>
                            <td class="th1">原手机号 </td>
                            <el-input v-model="phoneForm.oldPhone" placeholder="请输入原手机号"></el-input>
                        </tr>
                        <tr>
                            <td class="th1">新手机号 </td>
                            <el-input v-model="phoneForm.newPhone" placeholder="请输入新手机号"></el-input>
                        </tr>
                    </table>
                    
                    <!-- 滑动验证 -->
                    <div class="verification-section" style="margin-top: 20px;">
                        <div 
                            class="slider-verification" 
                            @mousedown="startPhoneDrag"
                            @mousemove="onPhoneDrag"
                            @mouseup="endPhoneDrag"
                            @mouseleave="endPhoneDrag"
                        >
                            <div class="slider-track">
                                <div 
                                    class="slider-handle" 
                                    :class="{ 'verified': isPhoneVerified }" 
                                    :style="{ left: isPhoneVerified ? 'calc(100% - 50px)' : phoneSliderPosition + 'px' }"
                                >
                                    <i class="el-icon-right" v-if="!isPhoneVerified"></i>
                                    <i class="el-icon-check" v-if="isPhoneVerified"></i>
                                </div>
                                <span class="slider-text" :class="{ 'hidden': isPhoneVerified || phoneSliderPosition > 0 }">请拖动滑动验证</span>
                                <span class="slider-success" v-if="isPhoneVerified">验证通过</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 验证码输入 -->
                    <div style="margin-top: 16px;">
                        <el-input
                            v-model="phoneForm.verifyCode"
                            placeholder="请输入验证码"
                            style="width: 100%;border: 1px solid #dcdcdc"
                        >
                            <template slot="append">
                                <el-button @click="sendPhoneCode" :disabled="phoneCodeCountdown > 0">
                                    {{ phoneCodeCountdown > 0 ? `${phoneCodeCountdown}秒` : '获取验证码' }}
                                </el-button>
                            </template>
                        </el-input>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" style="background-color: #5165f7;" @click="confirmChangePhone" >确定</el-button>
                <el-button @click="cancelChangePhone" >取消</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import { Detailss } from '@/api/finance/operate/qiye'
import { show } from '@/api/homepage/corporateInformation'
import { removeToken, getEnterpriseLogo } from '@/utils/auth'
import { logout, updatePwd, changePhone, sendSmsCode, adminsendSmsCode, details } from '@/api/login/login'
export default {
    data() {
        return {
            enterpriseLogo: '', // 企业LOGO图片URL
            year: '', // 年度
            yuanright: 0, // 有效性：0-有效，1-无效
            uploadedImage: '', // 上传的图片URL
            passwordDialogVisible: false, // 修改密码对话框显示状态
            passwordForm: {
                oldPassword: '',
                newPassword: ''
            },
            phoneDialogVisible: false, // 更换手机账号对话框显示状态
            phoneForm: {
                oldPhone: '',
                newPhone: '',
                verifyCode: ''
            },
            phoneSliderPosition: 0, // 滑动验证位置
            isPhoneDragging: false, // 是否正在拖动
            isPhoneVerified: false, // 是否验证通过
            phoneCodeCountdown: 0, // 验证码倒计时
            tables: [
                {
                    name: '有效'
                },
                {
                    name: '无效'
                },
            ],
            shu: 0,
            active: 0,
            lastActiveKey: 'headerActiveIndex',
            tableData: [],
            // 营业收入表格数据
            tableData2: [{
                date: '营业收入',
                name: '',
                address: ''
            }, {
                date: '营业利润',
                name: '',
                address: ''
            }, {
                date: '利润总额',
                name: '',
                address: ''
            }, {
                date: '净利润',
                name: '',
                address: ''
            },
            {
                date: '综合收益总额',
                name: '',
                address: ''
            }],
            // 营业成本表格数据
            tableData3: [
                {
                    project: '营业成本',
                    currentAmount: '',
                    lastAmount: ''
                },
                {
                    project: '销售费用',
                    currentAmount: '',
                    lastAmount: ''
                },
                {
                    project: '管理费用',
                    currentAmount: '',
                    lastAmount: ''
                },
                {
                    project: '研发费用',
                    currentAmount: '',
                    lastAmount: ''
                },
                {
                    project: '财务费用',
                    currentAmount: '',
                    lastAmount: ''
                }
            ]
        }
    },

    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
                        }
                    }
                    
                    // 填充 arr1 数据（营业收入相关）
                    if (data.arr1) {
                        this.tableData2[0].name = this.formatCurrency(data.arr1.operating_revenue || '0') // 营业收入
                        this.tableData2[0].address = this.formatCurrency(data.arr1.last_operating_revenue || '0') // 营业收入（上年）
                        this.tableData2[1].name = this.formatCurrency(data.arr1.operating_profit || '0') // 营业利润
                        this.tableData2[1].address = this.formatCurrency(data.arr1.last_operating_profit || '0') // 营业利润（上年）
                        this.tableData2[2].name = this.formatCurrency(data.arr1.total_profit || '0') // 利润总额
                        this.tableData2[2].address = this.formatCurrency(data.arr1.last_total_profit || '0') // 利润总额（上年）
                        this.tableData2[3].name = this.formatCurrency(data.arr1.net_profit || '0') // 净利润
                        this.tableData2[3].address = this.formatCurrency(data.arr1.last_net_profit || '0') // 净利润（上年）
                        this.tableData2[4].name = this.formatCurrency(data.arr1.total_comprehensive_income || '0') // 综合收益总额
                        this.tableData2[4].address = this.formatCurrency(data.arr1.last_total_comprehensive_income || '0') // 综合收益总额（上年）
                    }
                    
                    // 填充 arr2 数据（营业成本相关）
                    if (data.arr2) {
                        this.tableData3[0].currentAmount = this.formatCurrency(data.arr2.business_cost || '0') // 营业成本
                        this.tableData3[0].lastAmount = this.formatCurrency(data.arr2.last_business_cost || '0') // 营业成本（上年）
                        this.tableData3[1].currentAmount = this.formatCurrency(data.arr2.sales_expenses || '0') // 销售费用
                        this.tableData3[1].lastAmount = this.formatCurrency(data.arr2.last_sales_expenses || '0') // 销售费用（上年）
                        this.tableData3[2].currentAmount = this.formatCurrency(data.arr2.administrative_expenses || '0') // 管理费用
                        this.tableData3[2].lastAmount = this.formatCurrency(data.arr2.last_administrative_expenses || '0') // 管理费用（上年）
                        this.tableData3[3].currentAmount = this.formatCurrency(data.arr2.rd_expenses || '0') // 研发费用
                        this.tableData3[3].lastAmount = this.formatCurrency(data.arr2.last_rd_expenses || '0') // 研发费用（上年）
                        this.tableData3[4].currentAmount = this.formatCurrency(data.arr2.financial_expenses || '0') // 财务费用
                        this.tableData3[4].lastAmount = this.formatCurrency(data.arr2.last_financial_expenses || '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') || '0'
            if (id) {
                this.$router.push({
                    path: '/qiyeEdit',
                    query: { id: id, activeTab: activeTab }
                })
            } else {
                this.$router.push({
                    path: '/qiyeEdit',
                    query: { activeTab: activeTab }
                })
            }
        },
        btnShang() {
            // 获取保存的 tab 索引，返回到对应的 tab
            const activeTab = this.$route.query.activeTab || localStorage.getItem('financeOperateActiveTab') || '0'
            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('下载失败，请稍后重试')
            }
        },
        handleCommand(command) {
            if (command === 'changePassword') {
                this.handleChangePassword()
            } else if (command === 'changePhone') {
                this.handleChangePhone()
            } else if (command === 'logout') {
                this.handleLogout()
            }
        },
        handleChangePassword() {
            // 重置表单
            this.passwordForm = {
                oldPassword: '',
                newPassword: ''
            }
            // 显示对话框
            this.passwordDialogVisible = true
        },
        async confirmChangePassword() {
            // 表单验证
            if (!this.passwordForm.oldPassword) {
                this.$message.warning('请输入原始密码')
                return
            }
            if (!this.passwordForm.newPassword) {
                this.$message.warning('请输入新密码')
                return
            }
            // 验证密码长度
            if (this.passwordForm.newPassword.length <= 8) {
                this.$message.warning('新密码长度必须超过8位')
                return
            }
            // 验证密码复杂度：至少包含字母、符号或数字中的两项
            const hasLetter = /[a-zA-Z]/.test(this.passwordForm.newPassword)
            const hasNumber = /[0-9]/.test(this.passwordForm.newPassword)
            const hasSymbol = /[^a-zA-Z0-9]/.test(this.passwordForm.newPassword)
            const complexityCount = [hasLetter, hasNumber, hasSymbol].filter(Boolean).length
            if (complexityCount < 2) {
                this.$message.warning('密码至少包含字母、符号或数字中的两项')
                return
            }
            
            // 调用修改密码接口
            try {
                const params = {
                    oldPwd: this.passwordForm.oldPassword,
                    newPwd: this.passwordForm.newPassword
                }
                const res = await updatePwd(params)
                if (res && res.code === 1) {
                    this.$message.success('密码修改成功')
                    this.passwordDialogVisible = false
                    // 重置表单
                    this.passwordForm = {
                        oldPassword: '',
                        newPassword: ''
                    }
                } else {
                    this.$message.error(res.msg || '密码修改失败')
                }
            } catch (error) {
                console.error('修改密码失败:', error)
                this.$message.error('密码修改失败，请稍后重试')
            }
        },
        cancelChangePassword() {
            this.passwordDialogVisible = false
            // 重置表单
            this.passwordForm = {
                oldPassword: '',
                newPassword: ''
            }
        },
        handleChangePhone() {
            // 重置表单
            this.phoneForm = {
                oldPhone: '',
                newPhone: '',
                verifyCode: ''
            }
            // 重置验证状态
            this.phoneSliderPosition = 0
            this.isPhoneDragging = false
            this.isPhoneVerified = false
            this.phoneCodeCountdown = 0
            // 显示对话框
            this.phoneDialogVisible = true
        },
        startPhoneDrag(e) {
            if (this.isPhoneVerified) return
            this.isPhoneDragging = true
            this.onPhoneDrag(e)
        },
        onPhoneDrag(e) {
            if (!this.isPhoneDragging || this.isPhoneVerified) return
            const slider = e.currentTarget
            const rect = slider.getBoundingClientRect()
            const x = e.clientX - rect.left
            const maxX = rect.width - 50
            this.phoneSliderPosition = Math.max(0, Math.min(x, maxX))
            
            // 如果拖到最右边，自动完成验证
            if (this.phoneSliderPosition >= maxX - 5) {
                this.isPhoneVerified = true
                this.phoneSliderPosition = maxX
                this.$message.success('验证通过')
                this.isPhoneDragging = false
            }
        },
        endPhoneDrag() {
            if (!this.isPhoneDragging) return
            this.isPhoneDragging = false
            // 如果没有完成验证，滑块回到起始位置
            if (!this.isPhoneVerified) {
                this.phoneSliderPosition = 0
            }
        },
        async sendPhoneCode() {
            if (this.phoneCodeCountdown > 0) return
            if (!this.isPhoneVerified) {
                this.$message.warning('请先完成滑动验证')
                return
            }
            if (!this.phoneForm.newPhone) {
                this.$message.warning('请输入新手机号')
                return
            }
            // 验证手机号格式
            const phoneReg = /^1[3-9]\d{9}$/
            if (!phoneReg.test(this.phoneForm.newPhone)) {
                this.$message.warning('请输入正确的新手机号')
                return
            }
            try {
                await adminsendSmsCode({ phone: this.phoneForm.newPhone })
                this.$message.success('验证码已发送')
                this.phoneCodeCountdown = 60
                const timer = setInterval(() => {
                    this.phoneCodeCountdown--
                    if (this.phoneCodeCountdown <= 0) {
                        clearInterval(timer)
                    }
                }, 1000)
            } catch (error) {
                console.error('发送验证码失败:', error)
            }
        },
        async confirmChangePhone() {
            // 表单验证
            if (!this.phoneForm.oldPhone) {
                this.$message.warning('请输入原手机号')
                return
            }
            if (!this.phoneForm.newPhone) {
                this.$message.warning('请输入新手机号')
                return
            }
            if (!this.isPhoneVerified) {
                this.$message.warning('请先完成滑动验证')
                return
            }
            if (!this.phoneForm.verifyCode) {
                this.$message.warning('请输入验证码')
                return
            }
            // 验证手机号格式
            const phoneReg = /^1[3-9]\d{9}$/
            if (!phoneReg.test(this.phoneForm.oldPhone)) {
                this.$message.warning('请输入正确的原手机号')
                return
            }
            if (!phoneReg.test(this.phoneForm.newPhone)) {
                this.$message.warning('请输入正确的新手机号')
                return
            }
            // 检查新旧手机号是否相同
            if (this.phoneForm.oldPhone === this.phoneForm.newPhone) {
                this.$message.warning('新手机号不能与原手机号相同')
                return
            }
            
            // 调用更换手机号接口
            try {
                const params = {
                    oldPhone: this.phoneForm.oldPhone,
                    newPhone: this.phoneForm.newPhone,
                    code: this.phoneForm.verifyCode
                }
                const res = await changePhone(params)
                if (res && res.code === 1) {
                    this.$message.success(res.msg || '手机号更换成功')
                    // 调用 details 接口获取用户信息
                    try {
                        const userId = localStorage.getItem('userId')
                        if (userId) {
                            const detailRes = await details(userId)
                            if (detailRes && detailRes.code === 1 && detailRes.data) {
                                // 更新手机号到 localStorage
                                if (detailRes.data.phone) {
                                    localStorage.setItem('userPhone', detailRes.data.phone)
                                }
                            }
                        }
                    } catch (error) {
                        console.error('获取用户详情失败:', error)
                    }
                    this.phoneDialogVisible = false
                    // 重置表单和验证状态
                    this.phoneForm = {
                        oldPhone: '',
                        newPhone: '',
                        verifyCode: ''
                    }
                    this.phoneSliderPosition = 0
                    this.isPhoneDragging = false
                    this.isPhoneVerified = false
                    this.phoneCodeCountdown = 0
                } else {
                    this.$message.error(res.msg || '手机号更换失败')
                }
            } catch (error) {
                console.error('更换手机号失败:', error)
            }
        },
        cancelChangePhone() {
            this.phoneDialogVisible = false
            // 重置表单和验证状态
            this.phoneForm = {
                oldPhone: '',
                newPhone: '',
                verifyCode: ''
            }
            this.phoneSliderPosition = 0
            this.isPhoneDragging = false
            this.isPhoneVerified = false
            this.phoneCodeCountdown = 0
        },
        async handleLogout() {
            this.$confirm('确认退出登录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    // 调用退出接口
                    await logout()
                    
                    // 清除登录状态
                    removeToken()
                    localStorage.removeItem('isLogin')
                    localStorage.removeItem('userId')
                    localStorage.removeItem('userNickname')
                    localStorage.removeItem('userPhone')
                    localStorage.removeItem('msgCount')
                    
                    // 跳转到登录页
                    this.$router.push('/login')
                    this.$message.success('已退出登录')
                } catch (error) {
                    console.error('退出登录失败:', error)
                    // 即使接口调用失败，也清除本地状态并跳转
                    removeToken()
                    localStorage.removeItem('isLogin')
                    localStorage.removeItem('userId')
                    localStorage.removeItem('userNickname')
                    localStorage.removeItem('userPhone')
                    localStorage.removeItem('msgCount')
                    this.$router.push('/login')
                    this.$message.success('已退出登录')
                }
            }).catch(() => {
                // 用户取消，不做任何操作
            })
        }

    }
}
</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;
    align-items: center;
    justify-content: center;
    padding: 20px;
    box-sizing: border-box;
    overflow: auto;
}

.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: 8.5px 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 {
    display: flex;
    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;
    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;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}
.enterprise-logo-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}
.headers-right{
    flex: 1;
    background: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 24px;
}

.header-user-section {
    display: flex;
    align-items: center;
    gap: 16px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    transition: all 0.3s;
}

.user-info:hover {
    opacity: 0.8;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #5165f7;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 500;
}

.user-details {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 4px;
}

.user-name .el-icon-arrow-down {
    font-size: 12px;
    color: #909399;
}

.user-phone {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
}

::v-deep .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    gap: 8px;
}

::v-deep .el-dropdown-menu__item i {
    font-size: 16px;
}

/* 修改密码对话框样式 */
.change-password-dialog ::v-deep .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #EDEFFE;
    background-color: #F7F7FA;
    text-align: center;
}

.change-password-dialog ::v-deep .el-dialog__title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    text-align: center;
}

.change-password-dialog ::v-deep .el-dialog__body {
    padding: 20px;
}

.password-form {
    padding: 10px 0;
}

.form-item {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    font-size: 14px;
    color: #303133;
    margin-bottom: 8px;
    font-weight: 400;
}

.form-item ::v-deep .el-input {
    width: 100%;
}

.form-item ::v-deep .el-input__inner {
    height: 40px;
    line-height: 40px;
}

.password-requirements {
    font-size: 12px;
    color: #909399;
    line-height: 1.6;
    margin-top: 10px;
    padding: 12px;
    background-color: #F5F7FA;
    border-radius: 4px;
}

.change-password-dialog ::v-deep .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #EDEFFE;
    text-align: right;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    justify-content: center;
}

/* 更换手机账号对话框样式 */
.change-phone-dialog ::v-deep .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #EDEFFE;
    background-color: #F7F7FA;
    text-align: center;
}

.change-phone-dialog ::v-deep .el-dialog__title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    text-align: center;
}

.change-phone-dialog ::v-deep .el-dialog__body {
    padding: 20px;
}

.department-table {
    width: 100%;
    border-collapse: collapse;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.department-table tr{
    border: 1px solid #DCE0FD;
    cursor: pointer;
}

.department-table th {
    color: #5a4a6a;
    font-weight: 600;
    text-align: left;
    padding: 16px 20px;
}

.department-table td {
    background-color: white;
    border-bottom: 1px solid #f0f0f0;
    color: #333;
    padding: 12px 20px;
    vertical-align: middle;
}

.department-table td:not(.th1) {
    padding: 12px 20px;
}

.department-table td ::v-deep .el-input {
    width: 100%;
}

.department-table tr:last-child td {
    border-bottom: none;
}

.th1{
    width: 120px;
    font-size: 13px;
    padding-left: 20px;
    padding-right: 8px;
    border-right: 1px solid #DCE0FD;
    background: #EDEFFE !important;
    border-bottom: 1px solid #DCE0FD !important;
}

.department-table tr:hover td {
    background-color: #f9f9f9;
    transition: background-color 0.2s;
}

.container {
    width: 72%;
    margin: 0 auto;
}

.change-password-dialog .contents,
.change-phone-dialog .contents {
    width: 90%;
    margin: 0 auto;
}

/* 滑动验证样式 */
.verification-section {
    margin-bottom: 16px;
}

.slider-verification {
    width: 90%;
    height: 48px;
    position: relative;
    cursor: grab;
    user-select: none;
}

.slider-verification:active {
    cursor: grabbing;
}

.slider-track {
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-left: 60px;
    overflow: hidden;
}

.slider-handle {
    position: absolute;
    left: 0;
    top: 0;
    width: 50px;
    height: 100%;
    background: #5165f7;
    border-radius: 8px 0 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
    transition: all 0.3s ease;
    z-index: 2;
    cursor: grab;
}

.slider-handle:active {
    cursor: grabbing;
}

.slider-handle.verified {
    background: #67c23a;
    border-radius: 8px;
    left: calc(100% - 50px) !important;
}

.slider-text {
    font-size: 14px;
    color: #909399;
    transition: opacity 0.3s;
    z-index: 1;
    white-space: nowrap;
}

.slider-text.hidden {
    opacity: 0;
}

.slider-success {
    position: absolute;
    right: 16px;
    font-size: 14px;
    color: #67c23a;
    font-weight: 500;
    z-index: 1;
}

.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>