<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-form-item style="float:right;">
                <el-link type="primary" :underline="false" href="./upload/财务人员成本模板.xlsx" download="财务人员成本模板.xlsx">财务模板下载</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>
        </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="houseFund" label="住房公积金" ></el-table-column>
            <el-table-column prop="others" label="其他" ></el-table-column>
            <el-table-column prop="totalCost" label="总成本" ></el-table-column>
        </el-table>
       
        <el-form :inline="true" >
            <el-form-item >
                <el-link type="primary" :underline="false" @click="assignToProject">查看项目成本分配</el-link>
            </el-form-item>
            <el-form-item style="float:right;">
                <el-link type="primary" :underline="false" @click="exportData">导出数据</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>
    </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 {
                user: JSON.parse(sessionStorage.getItem("user")),
                userDetailVisible: false,
                userDetail:{},
                date: null,
                tableHeight: 0,
                listLoading: false,
                list: [],

                addLoading: false,
                
                myChart: null,
                params: null,
            };
        },
        methods: {

            assignToProject(){
                var _this = this;
                this.http.post('/finance/getTimeCost', {yearMonth: this.date},
                res => {
                    if (res.code == "ok") {
                        var xList = [], yList = [], list = res.data.costList, 
                        totalMoneyCost = res.data.totalMoneyCost;
                        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: '项目成本统计 总计' + 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,
                            }]
                        };
                        myChart.setOption(option);
                        // 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
                },
                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();
            },
            // 批量导入人员
            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);
                    console.log('date====='+this.date);
                    formData.append("yearMonth", this.date);
                    this.http.uploadFile('/finance/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.$message({
                                message: "导入成功",
                                type: "success"
                            });
                            //重新读取列表
                            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.list = list;
                    } 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();
        },
        updated() {
            this.$nextTick(() => {
                this.$refs['table'].doLayout();
            }) 
        }
    };
</script>

<style lang="scss" scoped>
</style>