<template>
    <div :style="'padding:10px;background:#f7f7f7;min-height:'+tableHeight+'px;'">
        <div style="margin: 0 auto;width:1120px;">
            <el-row :gutter="24">
                <el-col :span="12">
                    <div class="box" style="min-height:180px">
                        <div >
                            <!-- <div class="lableTxt">总成本基线</div> -->
                            <label class="lableTxt">总成本基线<el-link v-if="permissions.projectCorrection" @click="correctBase" style="float:right;"><i class="el-icon-edit"  ></i></el-link></label>
                            <div class="lableCon" v-for="item in projectBaseCostData" :key="item.id">
                                <div><span class="gray_label">{{item.baseName}}:</span></div>
                                <div><span style="padding-right:20px;float:right;">￥{{item.baseAmount==null?'-':item.baseAmount | numberToCurrency}}</span></div>
                            </div>
                            <div style="height:24px">
                            <el-link style="float:right;margin-right:10px" @click="addCostAdd" size="small" v-if="permissions.projectAllocate" type="primary">下拨成本预算</el-link>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="box" style="min-height:180px;">
                        <label class="lableTxt">当前成本基线</label>
                            <div class="lableCon" v-for="item in nowBaseList" :key="item.id">
                                <div><span class="gray_label">{{item.baseName}}:</span></div>
                                <div><span style="padding-right:20px;float:right;">￥{{item.baseAmount==null?'-':item.baseAmount | numberToCurrency}}</span></div>
                            </div>
                            <div style="height:24px">
                            <!-- <el-link style="float:right;margin-right:10px" @click="addCostAdd" size="small" v-if="permissions.projectAllocate" type="primary">下拨成本预算</el-link> -->
                            </div>
                    </div>
                </el-col>
                <el-col :span="24"></el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="24">
                    <div class="box">
                        <el-table :data="addList" :loading="ListLoading" :default-sort="{prop:'indate',order:'descending'}">
                            <el-table-column v-for="item in addListColumns" :key="item.id" :label="item.name" align="right" header-align="center">
                                <template slot-scope="scope">
                                    <span>￥{{itemListFilter(scope.row.addItemList,item.id) | numberToCurrency}}</span>
                                    <!-- <span style="margin-right:30px">{{itemListFilter(scope.row.addItemList,item.id) == false ? '￥' + (itemListFilter(scope.row.addItemList,item.id) | numberToCurrency) : '-'}}</span> -->
                                    <!-- <span style="margin-right:30px">{{itemListFilter(scope.row.addItemList,item.id) == false ? '-' : '￥' + itemListFilter(scope.row.addItemList,item.id) | numberToCurrency}}</span> -->
                                </template>
                            </el-table-column>
                            <el-table-column label="下拨时间" prop="indate" align="center"></el-table-column>
                            <el-table-column label="操作人员" prop="userName" align="center"></el-table-column>
                            <el-table-column label="备注" prop="remark" align="left" header-align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column label="" align="center">
                                <template slot-scope="scope">
                                    <el-button size="small" @click="revert(scope.row.id)" v-if="scope.$index == 0">撤销</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>
        </div>


        <el-dialog title="下拨成本预算" v-if="addCostAddDialog" :visible.sync="addCostAddDialog" :close-on-click-modal="false" width="600px">
            <el-form>
                <el-form-item v-for="item in modBaseCostData" :key="item.id" :label="item.baseName" label-width="200px">
                    <el-input :id="'nowBaseCost'+index" v-model="item.baseAmount" placeholder="请输入" clearable @keyup.native="restrictNumber('nowBaseCost'+index)"></el-input>
                </el-form-item>
                <el-form-item label="备注" label-width="200px">
                    <el-input v-model="remark"  placeholder="请输入下拨备注" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <!-- <el-button @click="test">test</el-button> -->
                <el-button @click.native="addCostAddDialog = false">取消</el-button>
                <el-button type="primary" @click="addCostAddSure" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
        <el-dialog title="校正成本基线" v-if="correctBaseDialog" :visible.sync="correctBaseDialog" :close-on-click-modal="false" width="600px">
            <el-form>
                <el-form-item v-for="item in correctBaseCostData" :key="item.id" :label="item.baseName" label-width="200px">
                    <el-input :id="'baseCost'+index" v-model="item.baseAmount" placeholder="请输入" clearable @keyup.native="restrictNumber('baseCost'+index)"></el-input>
                </el-form-item>
                <el-form-item label="备注" label-width="200px">
                    <el-input v-model="remark"  placeholder="请输入校正原因" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <!-- <el-button @click="test">test</el-button> -->
                <el-button @click.native="correctBaseDialog = false">取消</el-button>
                <el-button type="primary" @click="correctBaseSure" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import util from "../../common/js/util";
    export default {
        data() {
            return {
                user: JSON.parse(sessionStorage.getItem('user')),
                permissions: JSON.parse(sessionStorage.getItem("permissions")),
                curProjectId: null,
                addLoading: false,
                projectBaseCostData: [],
                modBaseCostData: [],
                correctBaseCostData: [],
                remark: '',
                addCostAddDialog: false,
                addListColumns:[],
                ListLoading: false,
                nowBaseList: [],
                correctBaseDialog: false,
                projectContractAmount: null
            };
        },
        filters: {
            numberToCurrency(value) {
                console.log('info numberToCurrency='+value);
                if (!value || value=='-') return '0.00'
                value = value.toFixed(2)
                const intPart = Math.trunc(value)
                const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
                let floatPart = '.00'
                const valueArray = value.toString().split('.')
                if (valueArray.length === 2) { // 有小数部分
                floatPart = valueArray[1].toString() // 取得小数部分
                return intPartFormat + '.' + floatPart
                }
                return intPartFormat + floatPart
            }
        },
        methods: {
            restrictNumber(targetId) {
                let inpu = document.getElementById(targetId);
                inpu.value = inpu.value.replace(/[^\d.]/g, "");  //仅保留数字和"."
                inpu.value = inpu.value.replace(/\.{2,}/g, "."); //两个连续的"."仅保留第一个"."
                inpu.value = inpu.value.replace(".", "$#*").replace(/\./g,'').replace('$#*','.');//去除其他"."
                inpu.value = inpu.value.replace(/^(\d+)\.(\d\d).*$/, '$1.$2');;//限制只能输入两个小数
                if (inpu.value.indexOf(".") < 0 && inpu.value != "") { //首位是0的话去掉
                    inpu.value = parseFloat(inpu.value);
                }
            },
            test(item){
                // let list = [
                //     {id: 5, name: 'zs'},
                //     {id: 6, name: 'ls'},
                //     {id: 7, name: 'ww'}
                // ]
                // let lid = 5
                // let item = this.itemListFilter(list,lid)
                console.log('test',this.addListColumns);
            },
            itemListFilter(emList,eId){
                let emItem = emList.filter((em)=>{
                    return em.baseId == eId
                })
                if(emItem.length == 0){
                    return 0
                }else{
                    return emItem[0].baseAmount
                }
                
            },
            getProjectBaseData(projectId) {
                this.http.post('/project-basecost/get',{
                    projectId: projectId
                },res => {
                    if (res.code == "ok") {
                        this.projectBaseCostData = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 撤销操作
            revert(eId){
                this.http.post('/project-addcost-record/revert',{
                    id: eId
                },res => {
                    if(res.code == 'ok'){
                        this.$message({
                            message: '撤销成功',
                            type: 'success'
                        })
                        this.getAddList()
                        this.getNowBase()
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            correctBase(){
                // 校正成本基线
                this.correctBaseCostData = JSON.parse(JSON.stringify(this.projectBaseCostData))
                this.correctBaseDialog = true
            },
            addCostAdd(){
                this.modBaseCostData = JSON.parse(JSON.stringify(this.projectBaseCostData))
                for (let i = 0; i < this.modBaseCostData.length; i++) {
                    this.modBaseCostData[i].baseAmount = 0
                }
                this.addCostAddDialog = true
            },
            addCostAddSure(){
                this.addLoading = true
                let itemList = []
                for(let i=0; i<this.modBaseCostData.length; i++){
                    // let itemListItem = {
                    //     baseId: this.modBaseCostData[i].baseId,
                    //     baseName: this.modBaseCostData[i].baseName,
                    //     baseAmount: this.modBaseCostData[i].baseAmount
                    // }
                    itemList.push({
                        baseId: this.modBaseCostData[i].baseId,
                        baseName: this.modBaseCostData[i].baseName,
                        baseAmount: this.modBaseCostData[i].baseAmount
                    })
                }
                this.http.post('/project-addcost-record/add',{
                    projectId: this.curProjectId,
                    userId: this.user.id,
                    userName: this.user.name,
                    itemList: JSON.stringify(itemList),
                    remark: this.remark
                },res => {
                    if(res.code == 'ok'){
                        this.addLoading = false
                        this.addCostAddDialog = false
                        this.$message({
                            message: '下拨成功',
                            type: 'success'
                        })
                        this.remark = ''
                        this.getAddList()
                        this.getNowBase()
                    }else {
                        this.addLoading = false
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.addLoading = false
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            correctBaseSure(){
                //如果没有做修改，不提交数据
                var hasChangeData = false;
                for (var i=0;i<this.correctBaseCostData.length; i++) {
                    var item = this.correctBaseCostData[i];
                    var oldAmount = this.projectBaseCostData.filter(p=>p.id == item.id)[0].baseAmount;
                    if (item.baseAmount != oldAmount) {
                        hasChangeData = true;
                        break;
                    }
                }
                if (!hasChangeData) {
                    this.correctBaseDialog = false;
                    return;
                }
                this.http.post('/project/adjustBase', {
                    id: this.curProjectId,
                    contractAmount: this.projectContractAmount,
                    baseCostData:JSON.stringify(this.correctBaseCostData),
                    remark: this.remark
                },
                res => {
                    if (res.code == "ok") {
                        this.correctBaseDialog = false;
                        this.$message({
                            message: '校正成功',
                            type: "success"
                        });
                        this.remark = ''
                        this.getProjectBaseData(this.curProjectId)
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            getNowBase(){
                this.http.post('/project-currentcost/get',{
                    companyId: this.user.companyId,
                    projectId: this.curProjectId
                },res => {
                    if(res.code == 'ok'){
                        this.nowBaseList = res.data
                        
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            getAddList(){
                this.ListLoading = true
                this.http.post('/project-addcost-record/getAddList',{
                    companyId: this.user.companyId,
                    projectId: this.curProjectId
                },res => {
                    if(res.code == 'ok'){
                        this.ListLoading = false
                        this.addList = res.data.recordList
                        this.addListColumns = res.data.columns
                        console.log('getaddlist',res.data);
                    }else {
                        this.ListLoading = false
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.ListLoading = false
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            getProjectInfo() {
                this.http.post('/project/detail', {
                    id: this.curProjectId
                },
                res => {
                    if (res.code == "ok") {
                        this.projectContractAmount = res.data.contractAmount;
                        console.log('res.data',res.data);
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 160;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 160;
            };
        },
        mounted() {
            this.curProjectId = parseInt(this.$route.params.id);
            // var _this = this;
            // var that = this
            console.log("mounted",this.$route.params)
            // window.addEventListener("resize", function() {
            //     // _this.profitChart.resize();
            //     // that.profitChart.resize(); 
            // });
            this.getProjectBaseData(this.curProjectId)
            this.getAddList()
            this.getNowBase()
            this.getProjectInfo()
        }
    };
</script>
<style scoped>
.box {
    background:#fff;
    border: 1px solid #eeeeee;
    border-radius:5px;
    padding:10px;
    margin-top:10px;
    overflow-x: auto;
}
.el-row {
    margin-top:10px;
}
.lableTxt {
    color:#666;
}
.lableCon{
    margin: 20px 10px;
}
.lableCon div:nth-child(1){
    width: 50%;
    float: left;
}
.lableCon div:nth-child(2){
    width: 25%;
    display: inline-block;
}
.gray_label {
    color: #999;
}
</style>