<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;" 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="assignToProject" style="margin-left:10px;">查看项目成本分配</el-button>
            </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>
    </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 {
                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,
            };
        },
        methods: {
            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;
                        }});
            },
            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 + '元'
                                    +(this.hasNoProjectUsers?"，无项目人员成本总计 " + nopCost+"元, 共: "+(totalMoneyCost+nopCost)+"元":"")
                                    ,
                                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);
                        // 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);
                    console.log('date====='+this.date);
                    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.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();
            this.getCustomColumn();
        },
        updated() {
            this.$nextTick(() => {
                this.$refs['table'].doLayout();
            }) 
        }
    };
</script>

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