<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item>
                    <el-button type="text" @click="backToList" icon="el-icon-back" class="back">返回</el-button>
                </el-form-item>
                <el-form-item class="divLine"></el-form-item>
                <el-form-item style="width: 500px">
                    <!-- <div class="dipali"> -->
                        <!-- <span class="workName">{{detailName}}</span> -->
                        <el-cascader v-model="departmentId" placeholder="请选择部门" style="width: 180px;margin-left:10px;" @change="getList"
                        :options="option" :props="{ checkStrictly: true }" :show-all-levels="false"></el-cascader>
                    <!-- </div> -->
                </el-form-item>
                <el-form-item >
                    <span style="color:#666;">时间段：{{startDate}}<span style="padding-left:5px;padding-right:5px;">至</span>{{endDate}}</span>
                </el-form-item>
                <el-form-item style="float:right;">
                    <span style="font-size:18px;">部门成本：<span style="color:#20a0ff;">{{cost.toFixed(2)}}元</span></span>
                </el-form-item>
            </el-form>
        </el-col> 
        <div id="clearfix" :style="'overflow-x: auto;width:100%;padding-bottom: 100px; position: relative; height:'+containerHeight+'px;'">
            <div id="container" :style="'height:' + tableHeight + 'px'"></div> 
        </div>
    </section>
</template>

<script>
    import util from "../../common/js/util";

    export default {
        data() {
            return {
                yAxisValue: localStorage.yAxisValue,
                startDate:null,
                endDate: null,
                detailId: this.$route.params.id,
                detailName: this.$route.params.name,

                user: JSON.parse(sessionStorage.getItem("user")),

                cost: 0,

                tableHeight: 0,
                
                echart: null,

                option: [],
                departmentId: [].concat(parseInt(this.$route.params.id)),
            };
        },
        methods: {
            //返回
            backToList() {
                if (this.startDate != null) {
                    this.$router.push("/cost?startDate="+this.startDate+"&endDate="+this.endDate);
                } else {
                    this.$router.push("/cost");
                }
            },

            // 获取部门列表
            getDepartment() {
                this.http.post( this.port.manage.depList, {},
                res => {
                    if (res.code == "ok") {
                        var list = res.data , array = [];

                        // for(var i in list) {
                        //     if(list[i].id == this.detailId) {
                        //         array.push(list[i])
                        //     }
                        // }
                        this.option = this.changeArr(list);
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            // 修改数组
            changeArr(arr) {
                for (var i = 0; i < arr.length; i++) {
                    if(arr[i].id != -1 && arr[i].id != 0) {
                        if (arr[i].children != null && arr[i].children.length>0) {
                            arr[i].children = this.changeArr(arr[i].children);
                        }
                        arr[i].id && (arr[i].value = arr[i].id);
                        delete arr[i].id;
                    }
                }
                for(var i in arr) {
                    if(arr[i].id == -1 || arr[i].id == 0) {
                        arr.splice(i,1)
                    }    
                }
                return arr;
            },

            //获取部门人员工时统计
            getList() {
                this.listLoading = true;
                this.http.post(this.port.project.userCost, {
                    departmentId: this.departmentId[this.departmentId.length-1],
                    startDate: this.startDate,
                    endDate: this.endDate,
                },
                res => {
                    this.listLoading = false;
                    var _this = this;
                    if (res.code == "ok") {
                        // 
                            for(var i in res.data.list) {
                                if(i>20) {
                                    this.widthHtval = +this.widthHtval + 40
                                } else {
                                    this.widthHtval = document.body.clientWidth - 230
                                }
                            }
                        // 
                        var xList = [] , yList = [] , list = res.data.list, array = [] , series = [];
                        if (list.length > 0) {
                            this.cost = res.data.totalCostMoney;
                            for(var i in list) {
                                xList.push(list[i].name);
                                var pro = list[i].project;
                                for(var j in pro) {
                                    if(array.indexOf(pro[j].project) == -1) {
                                        array.push(pro[j].project)
                                    }
                                }
                            }

                            for(var i in array) {
                                yList.push(array[i]);
                                var dataList = [];
                                for(var j in list) {
                                    var curUser = list[j];
                                    var project = list[j].project;
                                    if(project.length != 0) {
                                        //找到当前用户对应的项目
                                        var findProject = project.filter(p=>p.project == array[i]);
                                        if (findProject.length > 0) {
                                            dataList.push({
                                                    "value": this.yAxisValue==0?findProject[0].money:findProject[0].time,
                                                    "cost": findProject[0].time,
                                                    "money": findProject[0].money
                                                })
                                        } else {
                                            dataList.push({
                                                    "value": 0,
                                                    "cost": 0,
                                                    "money": 0,
                                                })
                                        }
                                    } else {
                                        dataList.push({
                                            "value": 0,
                                            "cost": 0,
                                            "money": 0
                                        })
                                    }
                                }

                                series.push({
                                    name: array[i],
                                    type: 'bar',
                                    stack:'1',
                                    barMaxWidth: 30,
                                    data: dataList,
                                })
                            }

                            var myChart = echarts.init(document.getElementById("container"));
                            // 设置宽度
                            myChart.resize({
                                width: this.widthHtval
                            })
                            _this.myChart = myChart;
                            var option = {
                                // 工具箱
                                legend: {
                                    x: 80,
                                    y: 10,
                                    data: yList
                                },
                                grid : {
                                    top : 80,    //距离容器上边界40像素
                                    bottom: 35,   //距离容器下边界30像素
                                    left: 150,
                                    right: 150
                                },
                                toolbox: {
                                    show: true,
                                    feature:{
                                        saveAsImage:{
                                            show:true
                                        },
                                        restore:{
                                            show:true
                                        },
                                        dataView:{
                                            show:true
                                        },
                                        dataZoom:{
                                            show:true
                                        },
                                        magicType:{
                                            type:['line','bar']
                                        }
                                    }
                                },
                                tooltip:{
                                    trigger:'axis',
                                    formatter: function (params,ticket,callback) {
                                        
                                        var totalTime = 0.0;
                                        for(var i in params) {
                                            totalTime += parseFloat(params[i].data.cost)
                                        }
                                        var res = params[0].name + " 工时 : " + totalTime.toFixed(1)+"小时<br/>";
                                        for(var i in params) {
                                            if (params[i].data.value > 0) {
                                                res += "<div style='margin-top:3px;font-size:12px;'><font color='#ddd'>项目名称：" + params[i].seriesName 
                                                    + "</font><br/>工作成本 : " + params[i].data.money
                                                    + "元 <br/>工作时长"+" : " + params[i].data.cost + "小时</br></div>";
                                            }
                                        }
                                        return res;
                                    }
                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:this.yAxisValue==0?'{value} (元)':'{value}（小时）'
                                    }
                                }],
                                series: series,
                            };
                            myChart.setOption(option, {notMerge: true});
                        } else {
                            this.$message({
                                message: "暂无数据",
                                type: "error"
                                });
                        }
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 左右滚动
            scrollFunction () {
                this.domObj = document.getElementById('clearfix') // 通过id获取要设置的div
                if (this.domObj.attachEvent) { // IE
                this.domObj.attachEvent('onmousewheel', this.mouseScroll)
                } else if (this.domObj.addEventListener) {
                this.domObj.addEventListener('DOMMouseScroll', this.mouseScroll, false)
                }
                this.domObj.onmousewheel = this.domObj.onmousewheel = this.mouseScroll
            },

            mouseScroll(event) { // google 浏览器下
                let detail = event.wheelDelta || event.detail
                let moveForwardStep = -1
                let moveBackStep = 1
                let step = 0
                step = detail > 0 ? moveForwardStep * 100 : moveBackStep * 100
                event.preventDefault() // 阻止浏览器默认事件
                this.domObj.scrollLeft = this.domObj.scrollLeft + step
            },
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 145;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 145;
            };
        },
        mounted() {
            this.startDate = this.$route.query.startDate;
            this.endDate = this.$route.query.endDate;
            this.getDepartment();
            this.getList();
            var _this = this;
            window.addEventListener("resize", function() {
                _this.myChart.resize();
            });
            this.scrollFunction()
        }
    };
</script>

<style lang="scss" scoped>
    .toolbar {
        .el-form-item {
            font-size: 14px;
            vertical-align: middle;
        }
        .back {
            font-size: 16px;
            cursor: pointer;
        }
        .divLine {
            width: 2px;
            background: #c3c3c3;
            height: 100%;
        }
        .workName {
            color: #333;
            font-size: 18px;
        }
        .workHours {
            color: #20a0ff;
            font-size: 18px;
        }
    }

    #container {
        float: left;
        width: 100%;
    }
    .dipali {
        display: flex;
        width: 100%;
    }
</style>

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