<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>
            </div>
        </div>

        <div class="contents">
            <div class="content-left">
                <div class="content-lefts">
                    <div class="leftss">
                        <div class="leftss-header">
                            <div>立项预算编辑</div>
                            <div >
                               
                                <el-button @click="btnEdint" size="small" style="background-color: #5165f7;color:white;">保存成功</el-button>
                                <el-button size="small"  plain @click="btnClose">取消</el-button>
                            </div>
                        </div>
                        <div class="table-area">
                            <div class="table-header">
                                <div>
                                   <span class="times"> 立项预算明细｜ </span>
                                </div>
                                <div>
                                   <span class="times"> <el-button type="primary" size="mini" style="background-color: #5165f7;" @click="showAddDialog">添加</el-button> </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="content-table">
                       
                        <el-table
                            :data="budgetList"
                            border
                            :header-cell-style="{ background: '#EDEFFE', color: '#363636' }"
                            style="width: 100%">
                            <el-table-column
                             type="index"
                             align="center"
                            label="序号"
                            width="80"
                            :index="getBudgetIndex">
                            </el-table-column>
                            <el-table-column
                            prop="budget_item"
                            label="预算项"
                            width="380"
                            align="center">
                            </el-table-column>
                            <el-table-column
                             align="center"
                            prop="budget_amount"
                            label="预算金额(元)"
                                width="160">
                            <template slot-scope="scope">
                              {{ formatAmount(scope.row.budget_amount) }}
                            </template>
                            </el-table-column>
                            <el-table-column
                             align="center"
                            prop="cost_control_amount"
                                width="160"
                            label="成本控制额(元)">
                            <template slot-scope="scope">
                              {{ formatAmount(scope.row.cost_control_amount) }}
                            </template>
                            </el-table-column>
                            <el-table-column
                            align="center"
                           prop="remark"
                           label="备注">
                           </el-table-column>
                            <el-table-column
                            align="center"
                            label="操作"
                            width="100">
                            <template slot-scope="scope">
                                <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: #F56C6C;">删除</el-button>
                        
                            </template>
                            </el-table-column>
                        </el-table>
                                            
                      
                      
                        
                    </div>

                </div>

            </div>
           
        </div>

        <!-- 添加/编辑预算项对话框 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="addDialogVisible"
            width="500px"
            :before-close="closeAddDialog">
            <el-form :model="formData" label-width="120px">
                <el-form-item label="预算项名称" required>
                    <el-input v-model="formData.budget_item" style="border: 1px solid #dcdcdc;" placeholder="请输入预算项名称，如：外协费、设备材料费"></el-input>
                </el-form-item>
                <el-form-item label="预算金额(元)" required>
                    <el-input v-model="formData.budget_amount" type="number" style="border: 1px solid #dcdcdc;" placeholder="请输入预算金额"></el-input>
                </el-form-item>
                <el-form-item label="成本控制额(元)">
                    <el-input v-model="formData.cost_control_amount" type="number" style="border: 1px solid #dcdcdc;" placeholder="请输入成本控制额"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="formData.remark" type="textarea" :rows="3"  placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeAddDialog">取消</el-button>
                <el-button type="primary" @click="confirmAdd" style="background-color: #5165f7;">确定</el-button>
            </div>
        </el-dialog>

        <!-- 保存成功弹框 -->
        <el-dialog
            :visible.sync="saveSuccessDialog"
            width="400px"
            :show-close="false"
            center
            :destroy-on-close="true"
            :append-to-body="true">
            <div class="success-dialog-content">
                <img src="@/assets/succes.png" alt="成功" class="success-icon" />
                <div class="success-title">提交保存成功</div>
                <div class="success-message">您的信息已提交成功，请耐心等待审核结果</div>
                <el-button type="primary" @click="closeSuccessDialog" style="background-color: #5165f7; margin-top: 20px;">知道了</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import { save, deletes } from '@/api/projectmanagement/lixiangyusuan'
import { getEnterpriseLogo } from '@/utils/auth'
export default {
    data() {
        return {
            enterpriseLogo: '', // 企业LOGO
            projectId: '', // 项目ID
            budgetList: [], // 预算列表
            addDialogVisible: false, // 添加对话框显示状态
            dialogTitle: '添加预算项', // 对话框标题
            formData: {
                id: '',
                budget_item: '',
                budget_amount: '',
                cost_control_amount: '',
                remark: ''
            },
            saveSuccessDialog: false, // 保存成功弹框
            active: 0,
            listDate: [
                {
                    name: '资料附件'
                },
            ],
            value1: "",
            yuanright: 0,
            tables: [
                {
                    name: '有效'
                },
                {
                    name: '无效'
                },
            ],
            shu: 0,
            lastActiveKey: 'headerActiveIndex',
            tableData: [],
            tableData2: []
        }
    },

    created() {
        this.loadEnterpriseLogo()
        // 从路由参数获取项目ID
        this.projectId = this.$route.query.project_id || this.$route.query.id || ''
        console.log('立项预算编辑页面 - 路由参数:', this.$route.query)
        console.log('立项预算编辑页面，项目ID:', this.projectId)
        
        // 如果还是没有获取到ID，尝试从localStorage或其他地方获取
        if (!this.projectId) {
            console.warn('未从路由参数获取到项目ID，尝试其他方式')
            // 可以尝试从sessionStorage或其他地方获取
        }
    },

    watch: {
        // 监听路由变化，确保ID能正确获取
        '$route'(to, from) {
            if (to.query.project_id || to.query.id) {
                this.projectId = to.query.project_id || to.query.id || ''
                console.log('路由变化，更新项目ID:', this.projectId)
            }
        }
    },

    methods: {
        // 加载企业LOGO
        loadEnterpriseLogo() {
            const logo = getEnterpriseLogo()
            if (logo) {
                // 如果是完整URL，直接使用
                if (logo.startsWith('http://') || logo.startsWith('https://')) {
                    this.enterpriseLogo = logo
                } else {
                    // 如果是相对路径，拼接基础URL
                    const baseUrl = process.env.VUE_APP_BASE_API || ''
                    this.enterpriseLogo = baseUrl + logo
                }
            } else {
                console.warn('未获取到企业LOGO')
            }
        },
        //取消
        closeguan() {
            this.$router.go(-1)
        },
        btnNmae(e) {
            this.active = e
        },
        //切换时效性
        btnYuan(e) {
            this.yuanright = e
        },
        //取消
        btnClose(){
            this.$router.go(-1)
        },
        // 显示添加对话框
        showAddDialog() {
            this.dialogTitle = '添加预算项'
            this.formData = {
                id: '',
                budget_item: '',
                budget_amount: '',
                cost_control_amount: '',
                remark: ''
            }
            this.addDialogVisible = true
        },
        // 关闭添加对话框
        closeAddDialog() {
            this.addDialogVisible = false
            this.formData = {
                id: '',
                budget_item: '',
                budget_amount: '',
                cost_control_amount: '',
                remark: ''
            }
        },
        // 确认添加
        confirmAdd() {
            // 验证必填字段
            if (!this.formData.budget_item) {
                this.$message.warning('请输入预算项名称')
                return
            }
            if (!this.formData.budget_amount) {
                this.$message.warning('请输入预算金额')
                return
            }
            
            // 如果是编辑模式（有id），更新列表中的项
            if (this.formData.id) {
                const index = this.budgetList.findIndex(item => item.id === this.formData.id)
                if (index > -1) {
                    this.$set(this.budgetList, index, { ...this.formData })
                }
            } else {
                // 添加新项
                const newItem = {
                    id: Date.now(), // 临时ID
                    budget_item: this.formData.budget_item,
                    budget_amount: this.formData.budget_amount,
                    cost_control_amount: this.formData.cost_control_amount || '',
                    remark: this.formData.remark || ''
                }
                this.budgetList.push(newItem)
            }
            
            this.closeAddDialog()
            this.$message.success(this.formData.id ? '修改成功' : '添加成功')
        },
        // 删除
        handleDelete(row) {
            const index = this.budgetList.findIndex(item => item.id === row.id)
            if (index > -1) {
                this.budgetList.splice(index, 1)
                this.$message.success('删除成功')
            }
        },
        // 保存成功
        async btnEdint() {
            // 再次尝试获取项目ID
            if (!this.projectId) {
                this.projectId = this.$route.query.project_id || this.$route.query.id || ''
            }
            
            console.log('保存时检查项目ID:', this.projectId, '路由参数:', this.$route.query)
            
            if (!this.projectId) {
                this.$message.warning('缺少项目ID，无法保存。请从项目详情页进入编辑页面。')
                return
            }
            
            if (this.budgetList.length === 0) {
                this.$message.warning('请至少添加一条预算项')
                return
            }
            
            try {
                // 构建保存数据，按照接口要求的格式
                const saveData = {
                    project_id: Number(this.projectId),
                    project_budget: this.budgetList.map(item => {
                        const budgetItem = {
                            budget_item: item.budget_item || '',
                            budget_amount: item.budget_amount || '',
                            cost_control_amount: item.cost_control_amount || '',
                            remark: item.remark || ''
                        }
                        
                        // 如果是编辑模式（有真实ID且不是临时ID），添加id字段
                        if (item.id && typeof item.id === 'number' && item.id <= 1000000) {
                            budgetItem.id = item.id
                        }
                        
                        return budgetItem
                    })
                }
                
                console.log('保存预算数据:', saveData)
                
                // 批量保存
                const res = await save(saveData)
                
                if (res && res.code === 1) {
                    // 保存成功，显示成功弹框
                    this.saveSuccessDialog = true
                } else {
                    this.$message.error(res?.msg || '保存失败，请稍后重试')
                }
            } catch (error) {
                console.error('保存失败:', error)
                this.$message.error('保存失败，请稍后重试')
            }
        },
        // 关闭成功弹框
        closeSuccessDialog() {
            this.saveSuccessDialog = false
            setTimeout(() => {
                this.$router.go(-1)
            }, 100)
        },
        // 获取序号
        getBudgetIndex(index) {
            return index + 1
        },
        // 格式化金额
        formatAmount(amount) {
            if (!amount && amount !== 0) return '-'
            const num = parseFloat(amount)
            if (isNaN(num)) return '-'
            return num.toFixed(2)
        }
    }
}
</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>
.area-name {
    margin-left: 30px;
    cursor: pointer;
}

.active {

    
    height: 48px;
}

.header-area {
    display: flex;
    position: relative;
    left: -30px;
}

.rightss3 {
    border-right: none;
    border-left: none;
}

.table-name {
    margin-left: 20px;
}

.rightss2 {
    background: #EDEFFE;
}

.rightss1 {
    border-left: none !important;
    border-right: none !important;

}

.rightss {
    height: 100%;
    border: 1px solid #DCE0FD;
    width: 48%;
    border-top: none;

}

.content-areas2 {
    position: relative;
    top: 1px;

}

.contents-right {
    flex: 1;
    border: 1px solid #DCE0FD;
    line-height: 50px;
    font-size: 14px;
    color: #363636;
    display: flex
}

.contents-left {
    width: 30%;
    border: 1px solid #DCE0FD;
    background: #EDEFFE;
    ;
    line-height: 50px;
    font-size: 14px;
    color: #363636;

}

.content-areas {
    display: flex;
    height: 50px;
    flex-wrap: wrap;
}
.content-areas22 {
    display: flex;

    flex-wrap: wrap;
}
.tab-area {
    margin-top: 24px;
}

.namess {
    color: #5B5E72;
    font-size: 13px;
    margin-left: 12px;
}

.names {
    font-size: 14px;
    color: #363636;
}

:deep .el-tooltip__popper.is-dark {
    color: #F04B4B !important;
}

.right-area {
    width: 90%;
    margin: 0 auto;
    height: 80vh;
    background: #f8f8f8;
}

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

.rights-names {
    margin-left: 32px;
    cursor: pointer;
    color: #5165f7;
}

/* 选中"有效"时的样式 */
.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: -64px;
    text-align: center;
    display: flex
;
    justify-content: center;;
}
.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: contain;
    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;
}




.patent-container {
    max-width: 1000px;
    margin: 0 auto;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
}

.patent-header {
    background: linear-gradient(135deg, #6a5acd, #8a7dff);
    color: white;
    padding: 20px 30px;
    text-align: center;
}

.patent-header h1 {
    font-size: 24px;
    margin-bottom: 10px;
    font-weight: 600;
}

.patent-header p {
    opacity: 0.9;
    font-size: 14px;
}

.search-box {
    padding: 15px 30px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #eaeaea;
}

.search-box input {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.search-box input:focus {
    outline: none;
    border-color: #8a7dff;
    box-shadow: 0 0 0 2px rgba(138, 125, 255, 0.2);
}

.patent-table {
    width: 100%;
    border-collapse: collapse;
}

.patent-table th {
    background-color: #f0e6ff;
    color: #5a4fcf;
    padding: 12px 15px;
    text-align: left;
    font-weight: 600;
    border-bottom: 1px solid #ddd;
}

.patent-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s;
}

.patent-table tr:hover td {
    background-color: #f9f7ff;
}

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

.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.status-paid {
    background-color: #e8f5e9;
    color: #2e7d32;
}

.patent-footer {
    padding: 15px 30px;
    text-align: center;
    color: #777;
    font-size: 14px;
    border-top: 1px solid #eaeaea;
    background-color: #fafafa;
}

/* 保存成功弹框样式 */
.success-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

.success-icon {
    margin-bottom: 16px;
}

.success-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
}

.success-message {
    font-size: 14px;
    color: #666;
    text-align: center;
}
</style>