<template>
    <div :style="'padding:10px;background:#f7f7f7;min-height:'+tableHeight+'px;'">
        <div style="margin: 0 auto;width:1000px;">
            <el-row :gutter="24">
                <el-col :span="12">
                    <div class="box" ref="allBox">
                        <div >
                            <!-- <div class="lableTxt">总成本基线</div> -->
                            <label class="lableTxt">{{ $t('totalcostbaseline') }}<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="float:right;">￥{{item.baseAmount | numberToCurrency}}</span></div>
                                <div>
                                    <span style="float:right;">{{ $t('restcanbedialed') }} <span :style="item.baseAmount * 0.9 < baseCostFilter(item.baseId) ? 'color:red;' : ''">￥{{(item.baseAmount - baseCostFilter(item.baseId)) | numberToCurrency}}</span></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">{{ $t('allocatethecostbudget') }}</el-link>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="box" ref="nowBox" :style="'height:' + nowBaseHeight + 'px;'">
                        <label class="lableTxt">{{ $t('currentcostbaseline') }}</label>
                            <div class="lableCon" v-for="item in nowBaseList" :key="item.id">
                                <div><span class="gray_label">{{item.baseName}}:</span></div>
                                <div><span style="float:right;">￥{{item.baseAmount==null?'-':item.baseAmount | numberToCurrency}}</span></div>
                                <div class="nowBase_div3">
                                    <span style="float:right;">{{ $t('yi') }}<span>￥{{item.realCost | numberToCurrency}}</span></span>
                                </div>
                                <div class="nowBase_div4">
                                    <span style="float:right;">{{ $t('yu') }}<span :style="item.baseAmount * 0.9 < item.realCost ? 'color:red;' : ''">￥{{(item.baseAmount - item.realCost) | numberToCurrency}}</span></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" min-width="150">
                                <template slot-scope="scope">
                                    <span style="margin-right: 40px;">￥{{itemListFilter(scope.row.addItemList,item.id) | numberToCurrency}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('xiabo')" prop="indate" align="center" min-width="200"></el-table-column>
                            <el-table-column :label="$t('caozuo')" prop="userName" align="center" min-width="120">
                                <template slot-scope="scope">
                                    <div>
                                        <span v-if="user.userNameNeedTranslate != 1">
                                            {{scope.row.userName}}
                                        </span>
                                        <span v-if="user.userNameNeedTranslate == 1">
                                            <TranslationOpenDataText type='userName' :openid='scope.row.userName'></TranslationOpenDataText>
                                        </span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('bei-zhu')" prop="remark" align="left" header-align="left" show-overflow-tooltip min-width="200"></el-table-column>
                            <el-table-column label="" align="center" fixed="right" v-if="permissions.projectAllocate">
                                <template slot-scope="scope">
                                    <el-button size="small" @click="revert(scope.row.id)" v-if="scope.$index == 0">{{ $t('btn.undo') }}</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="24">
                    <div class="box">
                        <div class="box_head">
                            日期区间：
                            <el-date-picker
                            v-model="dateSelect"
                            type="daterange"
                            size="small"
                            range-separator="-"
                            :start-placeholder="$t('interval')"
                            :end-placeholder="$t('interval')"
                            value-format="yyyy-MM-dd"
                            clearable
                            @change="hiddens()">
                        </el-date-picker>
                        </div>

                        <div class="boxBoxMax">
                            <div class="boxBoxMax_con">
                                <el-card class="box-card">
                                    <div slot="header" class="clearfix">
                                        工时成本
                                    </div>
                                    <div class="text item boxBoxMax_con_one">
                                        <span>工时合计</span> {{ chengbenData.workingTime }} h 
                                    </div>
                                    <div class="text item">
                                        <span style="letter-spacing: 26px;">成本</span>￥ {{ chengbenData.cost }} 
                                    </div>
                                </el-card>
                            </div>
                            <div class="boxBoxMax_con" v-if="user.company.packageExpense">
                                <el-card class="box-card">
                                    <div slot="header" class="clearfix">
                                        费用报销成本
                                    </div>
                                    <div class="text item boxBoxMax_con_two">
                                       <span>报销合计 </span>￥ {{ chengbenData.expense }} 
                                    </div>
                                </el-card>
                            </div>
                        </div>
                        
                    </div>
                </el-col>
            </el-row>
        </div>


        <el-dialog :title="$t('allocatethecostbudget')" v-if="addCostAddDialog" :visible.sync="addCostAddDialog" :close-on-click-modal="false" width="600px">
            <el-form>
                <el-form-item v-for="item,index in modBaseCostData" :key="item.id" :label="item.baseName" label-width="150px">
                    <el-input :id="'nowBaseCost'+index" v-model="item.baseAmount" :placeholder="$t('peaseenterthe')" clearable @keyup.native="restrictNumber('nowBaseCost'+index)" style="width:350px"></el-input>
                </el-form-item>
                <el-form-item :label="$t('bei-zhu')" label-width="150px">
                    <el-input v-model="remark"  :placeholder="$t('peaseenterthe')" style="width:350px"></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">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="addCostAddSure" :loading="addLoading">{{ $t('btn.submit') }}</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="$t('jiaoyan')" v-if="correctBaseDialog" :visible.sync="correctBaseDialog" :close-on-click-modal="false" width="600px">
            <el-form>
                <el-form-item v-for="item,index in correctBaseCostData" :key="item.id" :label="item.baseName" label-width="150px">
                    <el-input :id="'baseCost'+index" v-model="item.baseAmount" :placeholder="$t('peaseenterthe')" clearable @keyup.native="restrictNumber('baseCost'+index)" style="width:350px"></el-input>
                </el-form-item>
                <el-form-item :label="$t('bei-zhu')" label-width="150px">
                    <el-input v-model="remark"  :placeholder="$t('reasoforcorrection')" style="width:350px"></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">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="correctBaseSure" :loading="addLoading">{{ $t('btn.submit') }}</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,
                nowBaseHeight: '',
                dateSelect: [],
                chengbenData: {}
            };
        },
        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: {
            hiddens() {
                this.getTimeCostAndExpenseByProject()
            },
            getTimeCostAndExpenseByProject() {
                this.http.post('/project/timeCostAndExpenseByProject',{
                    startDate: this.dateSelect[0],
                    endDate: this.dateSelect[1],
                    projectId: this.curProjectId
                },res => {
                    if(res.code == 'ok'){
                        this.chengbenData = res.data
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            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);
                }
                if (inpu.value == '') {
                    inpu.value = 0;
                }
            },
            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);
            },
            baseCostFilter(eId){
                let emItem = this.nowBaseList.filter((em)=>{
                    return em.baseId == eId
                })
                if(emItem.length == 0){
                    return 0
                }else{
                    return emItem[0].baseAmount
                }
            },
            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: this.$t('Revocationofsuccess'),
                            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 = []
                let isAll0 = true
                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
                    // }
                    if(this.modBaseCostData[i].baseAmount != 0){
                        isAll0 = false
                    }
                    itemList.push({
                        baseId: this.modBaseCostData[i].baseId,
                        baseName: this.modBaseCostData[i].baseName,
                        baseAmount: this.modBaseCostData[i].baseAmount
                    })
                }
                if(isAll0){
                    this.$message({
                        message: this.$t('saoyixiang'),
                        type: 'warning'
                    })
                    this.addLoading = false
                    return
                }
                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: this.$t('xiabochenggong'),
                            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: this.$t('jiaozheng'),
                            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
                        // if(res.data.length == 0){
                        this.getBoxHeight()
                            // let allboxh = this.$refs.allBox.scrollHeight - 20
                            // console.log('getnowbase',allboxh);
                            // this.nowBaseHeight =  allboxh
                        // }
                    }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"
                    });
                });
            },

            refreshPage(){
                this.curProjectId = parseInt(this.$route.params.id);
            this.getProjectBaseData(this.curProjectId)
            this.getAddList()
            this.getNowBase()
            this.getProjectInfo()
            },
            getBoxHeight(){
                let allboxh = this.$refs.allBox.scrollHeight - 20
                this.nowBaseHeight =  allboxh
            }
        },
        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")
            // window.addEventListener("resize", function() {
            //     // _this.profitChart.resize();
            //     // that.profitChart.resize(); 
            // });
            this.getProjectBaseData(this.curProjectId)
            this.getAddList()
            this.getNowBase()
            this.getProjectInfo()
            this.getTimeCostAndExpenseByProject()
        }
    };
</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;
    height: 20px;
}
.lableCon div:nth-child(1){
    width: 30%;
    float: left;
}
.lableCon div:nth-child(2){
    width: 20%;
    float: left;
}
.lableCon div:nth-child(3){
    width: 50%;
    float: left;
    font-size: 13px;
    color: #999;
    line-height: 20px;
}
.lableCon .nowBase_div3{
    width: 25% !important;
    float: left;
    font-size: 13px;
    color: #999;
    line-height: 20px;
}
.lableCon .nowBase_div4{
    width: 25%;
    float: left;
    font-size: 13px;
    color: #999;
    line-height: 20px;
}
.gray_label {
    color: #999;
}
.box_head {
    margin: 20px 20px 20px 0px;
    color: #333;
}
.boxBoxMax {
    display: flex;
    justify-content: space-between;
}
.boxBoxMax_con {
    width: 48%;
    /* margin-right: 30px; */
    color: #333;
}
.boxBoxMax_con_one {
    margin-bottom: 8px;
}
.boxBoxMax_con_two {
    margin-bottom: 25px;
}
.boxBoxMax_con span{
    color: #999;
    display: inline-block;
    width: 80px;
}
</style>