<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item label="财务核算成本 | 月份选择" style="margin-top:5px;">
                <el-date-picker size="small" v-model="date" :editable="false" format="yyyy-MM" value-format="yyyy-MM" @change="changeMonth" :clearable="false" type="month" placeholder="选择月份"></el-date-picker>
            </el-form-item>
            <el-radio-group v-model="radio" @change="switchList" style="margin-left:160px;margin-top:5px;">
                <el-radio-button label="全部人员" >全部人员({{allFinanceList.length}})</el-radio-button>
                <el-radio-button label="无项目工时人员">无项目工时人员({{noReportUserList.length}})</el-radio-button>
            </el-radio-group>
            <el-form-item v-if="user.role == 1 || user.role == 2 || user.role == 4" style="margin-left:5px;margin-top:5px;">
                <el-link type="primary" :underline="false" @click="showSettingDialog()" >分摊比例设置</el-link>
            </el-form-item>

            <el-form-item style="float:right;" v-if="user.role == 1 || user.role == 2 || user.role == 4">
                <el-link type="primary" :underline="false" @click="getTemplate()" >财务模板下载</el-link>
            </el-form-item>
            <!-- <el-form-item style="float:right;">
                <el-upload ref="upload" action="#" :limit="1" :http-request="importFinance" :show-file-list="false">
                        <el-link type="primary" :underline="false" >财务数据上传</el-link>
                    </el-upload>
            </el-form-item> -->
            <el-form-item style="float:right;" v-if="user.role == 1 || user.role == 2 || user.role == 4">
                <el-link type="primary" :underline="false" @click="importDialog = true;isUploading=false;">财务数据上传</el-link>
            </el-form-item>
            <el-form-item style="float:right;" v-if="user.role == 1 || user.role == 2 || user.role == 4">
                <el-link type="primary" :underline="false" @click="showItemDialog">自定义薪资项</el-link>
            </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="list" highlight-current-row v-loading="listLoading" 
        show-summary=true
        ref="table"
        :height="300" style="width: 100%;">
            <el-table-column prop="name" label="姓名" sortable width="150"></el-table-column>
            <el-table-column prop="monthCost" label="工资"  width="150"></el-table-column>
            <el-table-column prop="bonus" label="奖金" ></el-table-column>
            <el-table-column prop="allowance" label="津贴" ></el-table-column>
            <el-table-column prop="insuranceOld" label="养老保险" ></el-table-column>
            <el-table-column prop="insuranceMedical" label="医疗保险" ></el-table-column>
            <el-table-column prop="insuranceLosejob" label="失业保险" ></el-table-column>
            <el-table-column prop="insuranceInjury" label="工伤保险" ></el-table-column>
            <el-table-column prop="houseFund" label="住房公积金" ></el-table-column>
            <!-- <el-table-column prop="others" label="其他" ></el-table-column> -->
            <el-table-column :label="item.fieldName" v-for="(item, index) in customCols" :key="item.id" :prop="index==0?'customField1':(index==1?'customField2':(index==2?'customField3':''))">
                <template slot-scope="scope">
                    {{index==0?scope.row.customField1:(index==1?scope.row.customField2:(index==2?scope.row.customField3:''))}}
                </template>
            </el-table-column>
            <el-table-column prop="totalCost" label="总成本" ></el-table-column>
        </el-table>
        
        <el-form :inline="true" >
            <el-form-item >
                <!-- <el-checkbox style="margin-left:10px;" v-model="assignNoProUser" @click="assignToProject">均摊无项目人员成本</el-checkbox> -->
                <!-- <el-button type="primary" :underline="false" size="small" @click="assignNoProUser=false;assignToProject();" style="margin-left:10px;">分摊已填工时人员成本</el-button>
                <el-button type="primary" :underline="false" size="small" @click="assignNoProUser=true;assignToProject();" style="margin-left:10px;">分摊全部人员成本</el-button> -->
                <el-radio-group v-model="costListRadio" @change="switchCostList" style="margin-left:5px;margin-top:5px;">
                    <el-radio-button label="1" >分摊已填工时人员成本</el-radio-button>
                    <el-radio-button label="2">分摊全部人员成本</el-radio-button>
                </el-radio-group>

            </el-form-item>

            <el-form-item style="float:right;">
                <el-link type="primary" :underline="false" @click="exportData">导出成本数据</el-link>
            </el-form-item>
            
            <!-- <el-form-item style="float:right;margin-right:30px;" v-if="hasNoProjectUsers">
                <el-link type="primary" :underline="false" @click="showNoProjectUsers">查看无项目数据</el-link>
            </el-form-item> -->
        </el-form>
        <div id="container" style="height:300px"></div>
        <!--新增界面-->
        <el-dialog :title="title" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass="customWidth" width="600px">
            <el-form ref="form1" :model="addForm" :rules="rules" label-width="100px">
                <el-form-item label="项目编号" >
                    <el-input v-model="addForm.code" placeholder="请输入项目编号" clearable></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入项目名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="全部参与者">
                    <el-select v-model="addForm.userId" multiple filterable placeholder="请选择参与者" style="width:100%;" @change="changeParticipator">
                        <el-option v-for="item in users" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="主要负责人" >
                    <el-select v-model="addForm.inchargerId" :disabled="addForm.userId.length==0" filterable placeholder="请选择负责人" style="width:100%;" @change="changeIncharger">
                        <el-option v-for="item in participator" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitInsert" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--用户详细信息弹出框-->
        <el-dialog title="查看详情" v-if="userDetailVisible" :visible.sync="userDetailVisible" :close-on-click-modal="false" customClass="customWidth" width="400px">
            <div class="line"><span>姓名</span><span>{{userDetail.name}}</span></div>
            <div class="line"><span>手机号码</span><span>{{userDetail.phone}}</span></div>
            <div class="line"><span>部门</span><span>{{userDetail.departmentName}}</span></div>
            <div class="line"><span>成本</span><span>{{userDetail.cost}}元/小时</span></div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="userDetailVisible = false" >确定</el-button>
            </div>
        </el-dialog>
         
         <!--导入时的设置界面 -->
         <el-dialog title="财务数据导入" v-if="importDialog" :visible.sync="importDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <el-form ref="form3" :model="importParam" >
                <el-form-item label="导入月份" >
                    <div style="color:orange;">{{date}}</div>
                </el-form-item>
                <el-form-item prop="syncHistoryReport"  >
                    <el-checkbox label="重新计算该月已填日报成本" v-model="importParam.syncHistoryReport"></el-checkbox>
                </el-form-item>
                <el-form-item prop="syncUserCost"  >
                    <el-checkbox label="同步到组织架构中员工月薪成本" v-model="importParam.syncUserCost" ></el-checkbox>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-upload ref="upload" action="#" :limit="1" :http-request="importFinance" :show-file-list="false" >
                        <el-button type="primary" style="width:100%;" :loading="isUploading" >选择文件并开始导入</el-button>
                    </el-upload>
            </div>
        </el-dialog>

        <!--无项目人员列表-->
        <!-- <el-dialog title="无项目人员列表" v-if="showNPDialog" :visible.sync="showNPDialog" :close-on-click-modal="false" customClass="customWidth" width="1200px">
            <el-table :data="npUserList" highlight-current-row v-loading="listLoading" 
            show-summary=true
            ref="table"
            :height="400" style="width: 100%;">
            <el-table-column prop="name" label="姓名" sortable width="150"></el-table-column>
            <el-table-column prop="monthCost" label="工资"  width="150"></el-table-column>
            <el-table-column prop="bonus" label="奖金" ></el-table-column>
            <el-table-column prop="allowance" label="津贴" ></el-table-column>
            <el-table-column prop="insuranceOld" label="养老保险" ></el-table-column>
            <el-table-column prop="insuranceMedical" label="医疗保险" ></el-table-column>
            <el-table-column prop="insuranceLosejob" label="失业保险" ></el-table-column>
            <el-table-column prop="insuranceInjury" label="工伤保险" ></el-table-column>
            <el-table-column prop="houseFund" label="住房公积金" ></el-table-column>
             <el-table-column prop="others" label="其他" ></el-table-column> 
            <el-table-column :label="item.fieldName" v-for="(item, index) in customCols" :key="item.id" :prop="index==0?'customField1':(index==1?'customField2':(index==2?'customField3':''))">
                <template slot-scope="scope">
                    {{index==0?scope.row.customField1:(index==1?scope.row.customField2:(index==2?scope.row.customField3:''))}}
                </template>
            </el-table-column>
            <el-table-column prop="totalCost" label="总成本" ></el-table-column>
        </el-table>
            <div slot="footer" class="dialog-footer">
                <div style="float:left;color:#ff9900;">*以上人员当月尚无投入的项目，请提醒他们填写日报。</div>
                <el-button type="primary" @click="showNPDialog = false" >关闭</el-button>
            </div>
        </el-dialog> -->

        <el-dialog title="自定义薪资项" show-header="false" v-if="itemDialog" :visible.sync="itemDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <div style="margin-left:30px;">
            <span style="color:#999;">薪资表包含以下数据</span>
            <p>工资</p>
            <p>奖金</p>
            <p>津贴</p>
            <p>养老保险</p>
            <p>医疗保险</p>
            <p>失业保险</p>
            <p>工伤保险</p>
            <p>住房公积金</p>
            <p><el-input v-model="customFieldList.field1" placeholder="请输入自定义薪资项1名称" style="width:200px;" maxlength="8"></el-input></p>
            <p><el-input v-model="customFieldList.field2" placeholder="请输入自定义薪资项2名称" style="width:200px;" maxlength="8"></el-input></p>
            <p><el-input v-model="customFieldList.field3" placeholder="请输入自定义薪资项3名称" style="width:200px;" maxlength="8"></el-input></p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="itemDialog = false" >关闭</el-button>
                <el-button type="primary" @click="saveItems()" >保存</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="date+'月 无项目工时人员分摊比例设置'" show-header="false" v-if="settingDialog" :visible.sync="settingDialog" 
        :close-on-click-modal="false" customClass="customWidth" width="1200px">
            <div>
                <div>
                    <el-button :disabled="multipleSelection.length==0" @click="setPercent(true, null)">批量设置比例</el-button>
                    <el-button :disabled="projectCols.length==0 || userCostSettingList.length == 0" @click="getLastMonthSetting">使用上月比例设置</el-button>
                    <el-button @click="showSelectProjectDialog">管理待分摊项目</el-button>
                </div>
                <el-table :data="userCostSettingList" highlight-current-row v-loading="costSettingLoading" 
                     ref="settingTable"  @selection-change="handleSelectionChange" 
                    :height="400" style="width: 100%;">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="name" label="姓名" sortable width="90" fixed="left"></el-table-column>
                    
                    <el-table-column :label="item.projectName" v-for="(item) in projectCols" width="180" size="small"
                        :key="item.id" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row[item.projectId]}}</span>%
                        </template>
                    </el-table-column>
                    <el-table-column label="设置比例"  width="80" fixed="right">
                        <template slot-scope="scope">
                            <el-button size="small" @click="setPercent(false,scope.row)">设置</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="settingDialog = false" >关闭</el-button>
                <el-button type="primary" @click="saveMonthSetting()" >保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="待分摊项目选择" show-header="false" v-if="projectsDialog" :visible.sync="projectsDialog" 
            :close-on-click-modal="false" customClass="customWidth" width="1000px">
            <el-select v-model="chosenProjects" multiple filterable clearable style="width:100%">
                <el-option v-for="item in allProjectList" :label="item.projectName" :key="item.id" :value="item.id"></el-option>
            </el-select>
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="projectsDialog = false" >关闭</el-button>
                <el-button type="primary" @click="saveProjectSetting()" >确定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="设置员工成本各项目占比" show-header="false" v-if="setPercentDialog" :visible.sync="setPercentDialog" 
            :close-on-click-modal="false" customClass="customWidth" width="600px" >
            <div style="margin:0px 10px 10px 10px;">
                <span>选择员工</span>
                <el-select v-model="chosenNoReportUserIds" multiple filterable clearable style="width:330px;" collapse-tags>
                        <el-option v-for="item in noReportUserList" :label="item.name" :key="item.id" :value="item.userId"></el-option>
                    </el-select>
                    <el-button @click="averageCost" >自动分摊</el-button>
            </div>
            <el-divider ></el-divider>
            <!--项目列表 -->
            <el-form v-model="curPercentVal" label-width="365px" style="margin-top:10px;">
                <div class="nameList">
                    <el-form-item v-for="item in projectCols" :label="item.projectName" :key="item.projectId" >
                        占比: <el-input v-model="curPercentVal[item.projectId]" style="width:100px;" @input="updatePercentValue"></el-input>&nbsp;%
                    </el-form-item>
                </div>
                <el-form-item >
                    总比例: {{totalPercent}}&nbsp;%
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="setPercentDialog = false" >关闭</el-button>
                <el-button type="primary" @click="setPercentSetting()" >确定</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<style scoped>
.line {
    padding:10px;
}
.line span{
    font-size:18px;
}
.line span:nth-child(even){
    float:right;
}
</style>
<script>
    import util from "../../common/js/util";

    export default {
        data() {
            return {
                costListRadio: 0,
                costSettingLoading: false,
                chosenNoReportUserIds:[],
                curPercentVal:{},
                setPercentDialog: false,
                chosenProjects:[],
                projectsDialog: false,
                projectCols:[],
                allProjectList:[],
                multipleSelection:[],
                userCostSettingList: [],
                settingDialog: false,
                radio:"全部人员",
                noReportUserList:[],
                allFinanceList:[],
                assignNoProUser: false,
                customFieldList:{field1:null, field2: null, field3: null},
                itemDialog: false,
                customCols:[],
                // showNPDialog: false,
                npUserList:[],
                hasNoProjectUsers: false,
                isUploading:false,
                importDialog: false,
                importParam:{syncUserCost:true, syncHistoryReport:true},
                user: JSON.parse(sessionStorage.getItem("user")),
                userDetailVisible: false,
                userDetail:{},
                date: null,
                tableHeight: 0,
                listLoading: false,
                list: [],

                addLoading: false,
                
                myChart: null,
                params: null,
                totalPercent:0,
            };
        },
        methods: {
            switchCostList() {
                //已填日报的人员成本
                if (this.costListRadio == 1) {
                    this.assignNoProUser=false;
                    this.assignToProject();
                } else if (this.costListRadio == 2) {
                    //全部人员成本
                    this.assignNoProUser=true;
                    this.assignToProject();
                }
            },
            getLastMonthSetting() {
                this.costSettingLoading = true;
                var dataArr = this.date.split('-');
                var year = dataArr[0];
                var month = dataArr[1];
                if (parseInt(month) == 1) {
                    year = parseInt(year) -1;
                    month = 12;
                } else {
                    month = parseInt(month) -1;
                    if (month < 10) {
                        month = '0'+month;
                    }
                }
                var lastMonth = year + '-' + month;
                this.http.post('/project-percentage/getMonthSetting', {ymonth: lastMonth},
                    res => {
                        this.costSettingLoading = false;
                        if (res.code == "ok") {
                            this.projectCols = res.data.financeProjects;
                            this.allProjectList = res.data.allProjectList;
                            this.userCostSettingList = res.data.userCostSetting;
                            //上次如果没有配置过,需要初始化
                            for (var i=0;i<this.noReportUserList.length; i++) {
                                var rUser = this.noReportUserList[i];
                                //检查当前列表中的无项目人员是否在之前的里面存在，如果不在需要加上去
                                if (this.userCostSettingList.filter(c=>c.id == rUser.userId).length == 0) {
                                    var item = {name: rUser.name, id: rUser.userId};
                                    this.projectCols.forEach(p=>{
                                        item[p.projectId] = 0;
                                    });
                                    this.userCostSettingList.push(item);
                                }
                            }
                            this.$nextTick(()=>{
                                this.$refs.settingTable.doLayout();
                            })
                        } });
            },
            //获取当月的无项目工时人员的分配比例设置
            getMonthSetting() {
                this.costSettingLoading = true;
                this.http.post('/project-percentage/getMonthSetting', {ymonth: this.date},
                    res => {
                        this.costSettingLoading = false;
                        if (res.code == "ok") {
                            this.projectCols = res.data.financeProjects;
                            this.allProjectList = res.data.allProjectList;
                            this.userCostSettingList = res.data.userCostSetting;
                            //上次如果没有配置过,需要初始化
                            for (var i=0;i<this.noReportUserList.length; i++) {
                                var rUser = this.noReportUserList[i];
                                console.log('userId====='+rUser.userId);
                                //检查当前列表中的无项目人员是否在之前的里面存在，如果不在需要加上去
                                if (this.userCostSettingList.filter(c=>c.id == rUser.userId).length == 0) {
                                    var item = {name: rUser.name, id: rUser.userId};
                                    this.projectCols.forEach(p=>{
                                        item[p.projectId] = 0;
                                    });
                                    this.userCostSettingList.push(item);
                                }
                            }
                        } });
            },
            //提交无工时人员的分配设置
            saveMonthSetting() {
                //检查数据是否都分配到100%了，防止由于修改了项目列而导致之前的数据不正确的情况
                var errorList = this.userCostSettingList.filter(u=>{
                    let totalPercent = 0.0;
                    this.projectCols.forEach(p=>{
                        totalPercent += parseFloat(u[p.projectId]);
                    });
                    totalPercent = totalPercent.toFixed(1);
                    if (totalPercent != 100) {
                        return true;
                    } else {
                        return false;
                    }
                });
                if (errorList.length > 0) {
                    var nameList = errorList.map(e=>e.name);
                    this.$message({type:'error', message:'存在人员分配比例非100%: '+nameList});
                    return;
                }
                this.http.post('/project-percentage/saveMonthSetting', {projectCols: JSON.stringify(this.projectCols),
                            ymonth: this.date, userSettings: JSON.stringify(this.userCostSettingList)},
                    res => {
                        if (res.code == "ok") {
                            this.$message({type:'success', message:'保存成功'});
                            this.settingDialog = false;
                        } else {
                            this.$message({type:'error', message:'发生错误:'+res.msg});
                        }});
            },
            updatePercentValue() {
                var total = 0.0;
                this.projectCols.forEach(p=>{
                    total += parseFloat(this.curPercentVal[p.projectId]);
                })
                this.totalPercent = total.toFixed(1);
                this.$forceUpdate();
            },
            averageCost() {
                var avg = (100/this.projectCols.length).toFixed(1);
                //最后一个用100减去前面的总和，保证最终合计为100
                for (var i=0;i<this.projectCols.length; i++) {
                    if (i < this.projectCols.length -1) {
                        this.curPercentVal[this.projectCols[i].projectId] = avg;
                    } else {
                        this.curPercentVal[this.projectCols[i].projectId] = (100-avg*(this.projectCols.length-1)).toFixed(1);
                    }
                }
                this.updatePercentValue();
                this.$forceUpdate();
            },
            setPercent(isBatch, row) {
                this.setPercentDialog = true;
                this.chosenNoReportUserIds = [];
                if (!isBatch) {
                    this.chosenNoReportUserIds.push(row.id);
                    //获取当前比例
                    this.projectCols.forEach(p=>{
                        this.curPercentVal[p.projectId] = row[p.projectId];
                    });
                } else {
                    //批量处理
                    this.multipleSelection.forEach(m=>{
                        this.chosenNoReportUserIds.push(m.id);
                    })
                    //批量时获取第一条的比例进行加载
                    this.projectCols.forEach(p=>{
                        this.curPercentVal[p.projectId] = this.multipleSelection[0][p.projectId];
                    });
                }
                this.updatePercentValue();
            },
            //确认设置的项目列
            saveProjectSetting() {
                this.projectsDialog = false;
                this.projectCols = [];
                this.chosenProjects.forEach(c=>{
                    var item = this.allProjectList.filter(a=>a.id == c)[0];
                    this.projectCols.push({projectId: item.id, projectName: item.projectName, projectCode: item.projectCode});
                });
                
                this.$nextTick(()=>{
                    this.$refs.settingTable.doLayout();
                })
            },
            handleProjectSelectionChange(val) {
                this.projectSelection = val;
            },
            showSelectProjectDialog() {
                //设置选中状态
                this.chosenProjects = [];
                this.projectCols.forEach(item=>{
                    this.chosenProjects.push(item.projectId);
                })
                this.projectsDialog = true;
            },
            setPercentSetting() {
                //检测是否填写的情况下，是否达到100%
                if (this.totalPercent != 100) {
                    this.$message({
                            message: '分配比例之和必须是100%',
                            type: "error"
                            });
                    return;
                }

                this.setPercentDialog = false;
                this.chosenNoReportUserIds.forEach(u=>{
                    var targetU = this.userCostSettingList.filter(a=>a.id == u)[0];
                    
                    //遍历项目
                    this.projectCols.forEach(p=>{
                        targetU[p.projectId] = this.curPercentVal[p.projectId];
                    })
                });
                this.userCostSettingList.splice(1,0);
                
            },
            showSettingDialog() {
                this.settingDialog = true;
                this.getMonthSetting();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            switchList() {
                if (this.radio == '全部人员') {
                    this.list = this.allFinanceList;
                } else {
                    this.list = this.noReportUserList;
                }
            },
            downloadByA(row) {
                const a = document.createElement('a'); // 创建a标签
                a.setAttribute('download', row.name);// download属性
                a.setAttribute('href', row.url);// href链接
                a.click();// 自执行点击事件
                a.remove();
            },
            getTemplate() {
                this.http.post('/finance/getTemplate', {companyId: this.user.companyId},
                    res => {
                        if (res.code == "ok") {
                            if (res.data.indexOf('xlsx') > 0) {
                                this.downloadByA({name:'财务成本报表.xlsx', url:res.data});
                            } else {
                                this.downloadByA({name:'财务成本报表.xls', url:res.data});
                            }
                            
                        }});
               
            },
            saveItems() {
                this.http.post('/finance-tblcuscol/save', this.customFieldList,
                    res => {
                        if (res.code == "ok") {
                             this.itemDialog = false;
                            this.getCustomColumn();
                        }});
               
            },
            showItemDialog() {
                this.itemDialog = true;
                this.customFieldList = {field1:null,field2:null, field3:null};
                for (var i=0;i<this.customCols.length; i++) {
                    if (i == 0) {
                        this.customFieldList.field1 = this.customCols[i].fieldName;
                    } else if (i == 1) {
                        this.customFieldList.field2 = this.customCols[i].fieldName;
                    } else if (i == 2) {
                        this.customFieldList.field3 = this.customCols[i].fieldName;
                    }
                }
                
            },
            //获取自定义的字段
            getCustomColumn() {
                this.http.post('/finance-tblcuscol/get', {companyId: this.user.companyId},
                    res => {
                        if (res.code == "ok") {
                            this.customCols = res.data;
                        }});
            },
            // getProjects() {
            //     this.http.post('/finance/getProjects', {companyId: this.user.companyId, yearMonth: this.date},
            //         res => {
            //             if (res.code == "ok") {
            //                 this.projectCols = res.data.financeProjects;
            //                 this.allProjectList = res.data.allProjectList;
            //             }});
                
            // },
            // showNoProjectUsers() {
            //     this.showNPDialog = true;
            //     this.http.post('/finance/getNoProjectUsers', {yearMonth: this.date},
            //     res => {
            //         if (res.code == "ok") {
            //             this.npUserList = res.data;
            //         }});
            // },
            assignToProject(){
                var _this = this;
                this.http.post('/finance/getTimeCost', {yearMonth: this.date, assignNoProUser: this.assignNoProUser},
                res => {
                    if (res.code == "ok") {
                        var xList = [], yList = [], list = res.data.costList, 
                        
                        totalMoneyCost = res.data.totalMoneyCost;
                        var nopCost = 0;
                        if (res.data.noProjectItem.project != null) {
                            this.hasNoProjectUsers = true;
                            nopCost = res.data.noProjectItem.cost;
                        } else {
                            this.hasNoProjectUsers = false;
                        }
                        
                        for(var i in list) {
                            xList.push(list[i].project);
                            
                            yList.push({
                                "value": list[i].cost,
                                "id": list[i].id,
                                "time": list[i].workingTime
                            });
                        }

                        var myChart = echarts.init(document.getElementById("container"));
                        _this.myChart = myChart;
                        var option = {
                            title: {
                                text: this.assignNoProUser?'成本总计 ' + totalMoneyCost + '元'
                                    +(this.hasNoProjectUsers?"，含无项目人员成本 " + nopCost+"元 ":"")
                                    :'成本总计 ' + totalMoneyCost + '元',
                                left:'left',
                            },
                            // 工具箱
                            toolbox: {
                                show: true,
                                feature:{
                                    saveAsImage:{
                                        show:true
                                    },
                                    restore:{
                                        show:true
                                    },
                                    magicType:{
                                        type:['line','bar']
                                    },
                                     
                                }
                            },
                            tooltip:{
                                trigger:'axis',
                                formatter: function (params,ticket,callback) {
                                    var res = params[0].name + "<br/>工作成本"+" : " + params[0].data.value 
                                    + "元 <br/>工作时长"+" : " + params[0].data.time + "小时";
                                    _this.params = params;
                                    return res;
                                }
                            },
                            xAxis: {
                                data: xList,
                                axisLabel: {
                                    interval:0,rotate:20
                                }
                            },
                            yAxis: [{
                                type : 'value',
                                axisLabel: {
                                    formatter:'{value} (元)'
                                }
                            }],
                            series: [{
                                name: '工作时长（h）',
                                type: 'bar',
                                barMaxWidth: 30,
                                data: yList,
                            }]
                        };
                        option && myChart.setOption(option,{notMerge: true});
                        // myChart.getZr().on('click', params => {
                        //     const pointInPixel = [params.offsetX, params.offsetY];
                        //     if (myChart.containPixel('grid', pointInPixel)) {
                        //         console.log(_this.params)
                        //         if(_this.radio=='项目') {
                        //             _this.$router.push("/cost/" + _this.params[0].data.id + "/" + _this.params[0].name);
                        //         }
                        //     }
                        // });
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            //导出财务数据
            exportData() {
                this.listLoading = true;
                this.http.post('/finance/exportData', {
                    date: this.date, assignNoProUser: this.assignNoProUser
                },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        var aTag = document.createElement('a');
                        aTag.download = "财务成本统计.xls";
                        aTag.href = res.data;
                        aTag.click();
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总价';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] += ' 元';
                } else {
                    sums[index] = 'N/A';
                }
                });

                return sums;
            },
            changeMonth() {
                //改变月份
                this.getList();
                this.assignToProject();
            },
            // 批量导入人员
            importFinance(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: "请选择.xls或.xlsx文件",
                        type: "error"
                    });
                } else {
                    this.listLoading = true;
                    let formData = new FormData();
                    formData.append("file", item.file);
                    formData.append("companyId", this.user.companyId);
                    formData.append("yearMonth", this.date);
                    formData.append("syncUserCost", this.importParam.syncUserCost);
                    formData.append("syncHistoryReport", this.importParam.syncHistoryReport);
                    this.isUploading = true;
                    this.http.uploadFile('/finance/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        this.isUploading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "导入成功",
                                type: "success"
                            });
                            this.importDialog = false;
                            //重新读取列表
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },

            
            //获取项目列表
            getList() {
                this.listLoading = true;
                this.http.post('/finance/getByMonth', {
                    companyId: this.user.companyId,
                    yearMonth: this.date
                },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        var list = res.data;
                        this.allFinanceList = list;
                        this.list = this.allFinanceList;
                        this.noReportUserList = list.filter(r=>r.hasReport == 0);
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

        },
        created() {
            
            var d = new Date();
            this.date = d.getFullYear() +'-'+ ((d.getMonth()+1) < 10? '0'+(d.getMonth()+1):d.getMonth()+1);
            
        },
        mounted() {
            let height = window.innerHeight;
            this.tableHeight = height - 245;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 245;
            };
            this.getList();
            this.getCustomColumn();
            // this.getProjects();
        },
        updated() {
            this.$nextTick(() => {
                this.$refs['table'].doLayout();
            }) 
        }
    };
</script>

<style lang="scss" scoped>
.nameList {
    height: 400px;
    overflow: auto;
}
</style>