<template>
    <section>
        <el-row style="padding-bottom: 0px;text-align:center;margin-top:20px;z-index: 999;">
        <el-col :span="6" >
            <div>&nbsp;</div>
        </el-col>
        <el-col :span="12" style="">
            <el-date-picker 
            v-model="dateRange" :editable="false" 
            format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
            @change="getEchart" 
            :clearable="true" 
            range-separator="至"
            type="daterange" 
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            ></el-date-picker>

            <el-radio-group v-model="radio" @change="getEchart" style="margin-left:10px;">
                <el-radio-button label="项目"></el-radio-button>
                <!-- <el-radio-button label="部门"></el-radio-button> -->
                <el-radio-button label="人员"></el-radio-button>
                <el-radio-button label="部门"></el-radio-button>
                <!-- <el-radio-button :label="namess" v-if="jichu.customDegreeActive == 1"></el-radio-button> -->
            </el-radio-group>
        </el-col>
        <el-col :span="6">
            <el-button @click="showExportDialog">报表导出</el-button>
        </el-col>
        </el-row>
        <div :style="'width:'+widthHtval+'px;position: relative; height:'+containerHeight+'px;'">
             <div id="container" :style="'height:'+containerHeight+'px;width:100%'"></div>
        </div>
        <div style="position:fixed;top:170px;left:600px;" v-show="radio=='部门' && parentDeptId != null">
            <el-button @click="backToParentDept">返回上级</el-button>
        </div>

        <!--导出报表条件选择 -->
        <el-dialog title="工时报表导出" v-if="exportDialog" :visible.sync="exportDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <el-form ref="form3" :model="exportParam" >
                <el-form-item prop="projectId" label="选择项目" >
                    <el-select v-model="exportParam.projectId" placeholder="全部项目"  clearable style="width:350px;" filterable="true">
                        <el-option v-for="item in projectList"  :key="item.id" :label="item.projectName + item.projectCode" :value="item.id">
                            <span style="float: left;color: #8492a6; font-size: 13px">{{ item.projectCode }}</span>
                            <span style="float: right;margin-left: 20px">{{ item.projectName }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item prop="userIds" label="选择人员" >
                    <el-select v-model="exportParam.userIds" placeholder="全部人员" multiple="true"  clearable style="width:350px;" filterable="true">
                        <el-option v-for="item in hasReportUserList"  :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item prop="projectId" :label="user.timeType.fixMonthcost==0?'日期范围':'选择月份'">
                    <el-date-picker v-show="user.timeType.fixMonthcost==0"
                        v-model="exportParam.dateRange" :editable="false" 
                        format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                        :clearable="false" 
                        range-separator="至"
                        type="daterange" 
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    ></el-date-picker>
                </el-form-item>
                
                <!-- <el-form-item label="选择人员" v-if="radio == '项目' || radio == '部门'">
                    <el-select v-model="exportParam.userId"  placeholder="请选择人员" style="width: 350px" filterable="true">
                        <span v-for="(item, index) in users" :key="index">
                        <el-option :label="item.name" :value="item.id"></el-option>
                        </span> 
                    </el-select>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exportProjectData" style="width:100%;" >导出</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from "../../common/js/util";
    export default {
        data() {
            return {
                yAxisValue: localStorage.yAxisValue?localStorage.yAxisValue:0,
                parentDeptStack:[],
                parentDeptId:null,
                hasReportUserList:[],
                projectList:[],
                exportParam:{projectId:null,dateRange:[],userId: null},
                exportDialog:false,
                dateRange:[],
                user: JSON.parse(sessionStorage.getItem("user")),
                radio: sessionStorage.radio!=null?sessionStorage.radio:'项目',
                containerHeight: 0,    
                myChart: null,
                params: null,
                widthHtval: document.body.clientWidth - 230,
                users: [],
                jichu: [],
                namess: '',
                timers: null, // 点击的时间
                zhishin: 0
            };
        },
        methods: {
            //Y轴点击改变显示的数据
            onYAxisChange() {
                localStorage.yAxisValue = this.yAxisValue;
                this.jieliu();
            },
            jutishez() {
                this.http.post('/time-type/getCompanyTimeSetting', {
                    companyId: this.user.companyId,
                },
                res => {
                    if (res.code == "ok") {
                        this.jichu = res.data
                        if(res.data.customDegreeActive == 1) {
                            this.namess = res.data.customDegreeName
                        }
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            getUsers() {
                // console.log(this.port.manage.list,'getusers')
                this.http.post(this.port.manage.list, {
                        departmentId: -1,
                        pageIndex: 1,
                        pageSize: 99999
                    },
                    res => {
                        if (res.code == "ok") {
                            this.users = res.data.records;
                        } else {
                            this.$message({
                            message: res.msg,
                            type: "error"
                            });
                        }
                    },
                    error => {
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                },
            
            showExportDialog() {
                this.exportDialog = true;
                this.exportParam.dateRange = this.dateRange;
            },
            //获取我的项目列表
            getMyProjectList() {
                this.http.post('/project/getProjectList', {
                },
                res => {
                    if (res.code == "ok") {
                        this.projectList = res.data;
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            exportProjectData() {
                 var param = {};
                 if (this.exportParam.dateRange != null) {
                    param = {startDate:this.exportParam.dateRange[0], endDate: this.exportParam.dateRange[1]};
                 }
                 var url = "/project/exportCustomDataSum";
                 var fileName = this.user.timeType.customDataName + '统计.xls';
                //  if (this.radio == '人员' ) {
                //      console.log(this.exportParam.userIds);
                //      fileName = '人员工时成本统计.xls';
                //      url = '/department/exportUserStatistic';
                //      if (this.exportParam.userIds != null && this.exportParam.userIds.length > 0) {
                //          var ids = '';
                //         this.exportParam.userIds.forEach(u=>{
                //             ids += u+',';
                //         })
                //         param.userIds = ids;
                //      }
                //  } 
                
                if (this.exportParam.projectId != null) {
                    param.projectId = this.exportParam.projectId;
                }
                this.http.post(url, param,
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.exportDialog = false;
                            var aTag = document.createElement('a');
                            aTag.download = fileName;
                            aTag.href = res.data;
                            aTag.click();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
            },
            //获取人员成本统计列表
            getUserCostList() {
                this.listLoading = true;
                let url = this.radio == '人员' ? '/department/getUserCustomDataStatistic' : '/department/getDeptCustomDataStatistic'
                this.http.post(url, {
                    startDate:this.user.timeType.fixMonthcost==0?this.dateRange[0]:this.dateRange, 
                    endDate: this.user.timeType.fixMonthcost==0?this.dateRange[1]:this.dateRange
                },
                res => {
                    this.listLoading = false;
                    var _this = this;
                    this.hasReportUserList = [];
                    if (res.code == "ok") {
                        //工时总成本
                        this.hasReportUserList = this.radio == '人员' ? res.data.userList : res.data.department;
                        var xList = [] , yList = [] , list = res.data.list, array = [] , series = [];
                        
                        var totalHours = 0.0;
                        if (list.length > 0) {
                            var num = list.length==0?0:list[0].project.length;
                            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 project = list[j].project , num = 0;
                                    if(project.length != 0) {
                                        for(var k in project) {
                                            if(project[k].project == array[i]) {
                                                dataList.push({
                                                    "value": project[k].cost,
                                                    "cost": project[k].cost
                                                })
                                                totalHours += parseFloat(project[k].cost);
                                            } else {
                                                num++;
                                            }
                                            if(k == project.length-1 && num != project.length-1) {
                                                dataList.push({
                                                    "value": 0,
                                                    "cost": 0
                                                })
                                            }
                                        }
                                    } else {
                                        dataList.push({
                                            "value": 0,
                                            "cost": 0,
                                        })
                                    }
                                }
                                series.push({
                                    name: array[i],
                                    type: 'bar',
                                    stack:'1',
                                    barMaxWidth: 30,
                                    data: dataList,
                                })
                            }
                        } 
                            
                            
                            var myChart = echarts.init(document.getElementById("container"));
                            totalHours = totalHours.toFixed(1);
                            _this.myChart = myChart;
                            var option = {
                                //总成本
                                title: {
                                    text: _this.user.timeType.customDataName + '总计' + totalHours,
                                    left:'left',
                                },
                                
                                // 工具箱
                                legend: {
                                    x: 80,
                                    y: 10,
                                    data: yList,
                                    show: true,
                        　　　　　　 top:"5%",//与上方的距离 可百分比% 可像素px
                                },
                                grid : {
                                    top : 80,    //距离容器上边界40像素
                                    bottom: 35   //距离容器下边界30像素
                                },
                                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;
                                        var res = "";
                                        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/>"+_this.user.timeType.customDataName+" : " + params[i].data.cost+"</div>";
                                                totalTime += Number(params[i].data.cost);
                                            }
                                        }
                                        res = res +'<br/>'+ params[0].name+ '<br/>总计: ' + totalTime.toFixed(1);
                                        return res;
                                    }
                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:'{value}'
                                    }
                                }],
                                series: series,
                            };
                            myChart.setOption(option,{notMerge:true});
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            yanjiu() {
                // console.log('触发')
            },
            getEchart(){
                var that = this
                // that.timers = setTimeout(()=>{
                    // clearTimeout(that.timers)
                    // console.log(that.timers)
                    that.jieliu()
                // },100);
                // this.jieliu()
            },
            backToParentDept() {
                if (this.radio == '部门') {
                    if (this.parentDeptStack.length > 0) {
                        this.parentDeptStack.pop();
                        if (this.parentDeptStack.length > 0) {
                            this.parentDeptId = this.parentDeptStack[this.parentDeptStack.length -1];
                        } else {
                            this.parentDeptId = null;
                        }
                        this.jieliu();
                    }
                }
            },
            // 脱离出来的方法
            jieliu() {
                sessionStorage.radio = this.radio;
                var _this = this;
                var param = {};
                if (this.dateRange != null) {
                    param = {startDate:this.user.timeType.fixMonthcost==0?this.dateRange[0]:this.dateRange, 
                    endDate: this.user.timeType.fixMonthcost==0?this.dateRange[1]:this.dateRange};
                    // console.log(param);
                }
                var url = '';
                if (this.radio=='项目') {
                    url = '/project/getCustomDataSum';
                // } else if (this.radio=='部门') {
                //     url = '/department/getDeptCustomDataStatistic';
                } else if (this.radio=='人员' || this.radio == '部门') {
                    this.getUserCostList();
                    return;
                } else if (this.radio == this.namess) {
                    url = '/project/getDegreeCost'
                }
                this.http.post(url, param,
                res => {
                    if (res.code == "ok") {
                        for(var i in res.data.costList) {
                            if(i>20) {
                                // this.widthHtval = +this.widthHtval + 2
                                this.widthHtval = +this.widthHtval + 40
                            } else {
                                this.widthHtval = document.body.clientWidth - 230
                            }
                        }
                            
                        // 测试写的
                        var xList = []
                        var yList = []
                        var list
                        var totalMoneyCost;
                        var totalHours = 0.0;
                        if(this.radio == '项目' || this.radio=='部门') {
                            list = res.data.costList
                            totalMoneyCost = ((this.radio=='项目')?res.data.totalMoneyCost:res.data.totalCostMoney);
                            for(var i in list) {
                                if(this.radio=='项目') {
                                    xList.push(this.radio=='项目'?list[i].project:list[i].name);
                                    yList.push({
                                        "value": list[i].cost.toFixed(1),
                                        "id": list[i].id || i,
                                        "cost": list[i].cost
                                    });
                                    totalHours += parseFloat(list[i].cost);
                                } else {
                                    xList.push(list[i].departmentName);
                                    yList.push({
                                        "value": list[i].costTime.toFixed(1),
                                        "id": list[i].departmentId,
                                        "cost": list[i].costTime,
                                        "hasSubDept": list[i].hasSubDept
                                    });
                                    totalHours += parseFloat(list[i].costTime);
                                }
                            }
                        } else {
                            list = res.data
                            var totalMoneyCost = 0;
                            for(var i in list) {
                                // console.log(list[i].name, list[i].costMoney, list[i].cost)
                                xList.push(list[i].name);
                                yList.push({
                                    "value": this.yAxisValue==0?list[i].costMoney:list[i].cost,
                                    "id": list[i].id || i,
                                    "cost": list[i].cost,
                                    "money":list[i].costMoney.toFixed(2)
                                });
                                totalHours += parseFloat(list[i].cost);
                                totalMoneyCost += parseFloat(list[i].costMoney);
                            }
                        }
                        totalHours = totalHours.toFixed(1);
                        
                        var myChart = echarts.init(document.getElementById("container"));
                        myChart.resize({
                            width: this.widthHtval
                        })
                        _this.myChart = myChart;
                        // console.log(totalMoneyCost.toFixed(2), '看看', totalMoneyCost)
                        // var chengbentongji = totalMoneyCost.toFixed(2) || totalMoneyCost
                        if(totalMoneyCost) {
                            this.zhishin = totalMoneyCost.toFixed(2)
                        } 
                        if(this.radio == '项目' || this.radio == '人员' || this.radio=='部门') {
                            var option = {
                                title: {
                                    text: _this.user.timeType.customDataName+'总计：' + totalHours,
                                    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/>"+_this.user.timeType.customDataName+" : " + params[0].data.cost;
                                        _this.params = params;
                                        return res;
                                    }
                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:'{value}'
                                    }
                                }],
                                series: [{
                                    name: _this.user.timeType.customDataName,
                                    type: 'bar',
                                    barMaxWidth: 30,
                                    data: yList,
                                }]
                            };
                        } else {
                            var option = {
                                title: {
                                    text: '工时成本总计' + _this.zhishin + '元, 时长'+totalHours+'小时',
                                    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.money 
                                        + "元 <br/>工作时长"+" : " + params[0].data.cost + "小时";
                                        _this.params = params;
                                        return res;
                                    }
                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:this.yAxisValue==0?'{value} (元)':'{value}小时'
                                    }
                                }],
                                series: [{
                                    name: this.yAxisValue==0?'工作成本（元）':'工作时长（小时）',
                                    type: 'bar',
                                    barMaxWidth: 30,
                                    data: yList,
                                }]
                            };
                        }
                        
                        myChart.setOption(option,{notMerge: true});
                        // myChart.getZr().on('click', params => {
                        //     const pointInPixel = [params.offsetX, params.offsetY];
                        //     if (myChart.containPixel('grid', pointInPixel)) {
                        //         console.log('sss',_this.params)
                        //         if(_this.radio=='项目') {
                        //             if (_this.dateRange != null) {
                        //                 if (this.user.timeType.fixMonthcost == 0) {
                        //                     _this.$router.push("/cost/" + _this.params[0].data.id + "/" + _this.params[0].name
                        //                     +"?startDate="+_this.dateRange[0]+"&endDate="+_this.dateRange[1]);
                        //                 } else {
                        //                     _this.$router.push("/cost/" + _this.params[0].data.id + "/" + _this.params[0].name
                        //                     +"?startDate="+_this.dateRange+"&endDate="+_this.dateRange);
                        //                 }
                        //             } else {
                        //                 _this.$router.push("/cost/" + _this.params[0].data.id + "/" + _this.params[0].name);
                        //             }
                        //         } else if (_this.radio=='部门') {
                        //             if (_this.params[0].data.hasSubDept) {
                        //                 if (_this.parentDeptId != _this.params[0].data.id) {
                        //                     _this.parentDeptId = _this.params[0].data.id;
                        //                     _this.parentDeptStack.push(_this.parentDeptId);
                        //                     _this.jieliu();
                        //                 }
                        //                 // _this.jieliu();
                        //             } else {
                        //                 if (_this.dateRange != null) {
                        //                     _this.$router.push("/costDep/" + _this.params[0].data.id + "/" + _this.params[0].name
                        //                         +"?startDate="+_this.dateRange[0]+"&endDate="+_this.dateRange[1]);
                        //                 } else {
                        //                     _this.$router.push("/costDep/" + _this.params[0].data.id + "/" + _this.params[0].name);
                        //                 }
                        //             }
                        //         }
                        //     }
                        // });
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            }
        },
        created() {
        },
        mounted() {
            this.containerHeight = window.innerHeight - 200
            const that = this;
            window.onresize = function temp() {
                this.containerHeight = window.innerHeight - 200
            };
            if (this.user.timeType.fixMonthcost == 0) {
                if (this.$route.query.startDate != null) {
                    this.dateRange = [this.$route.query.startDate, this.$route.query.endDate];
                } else {
                    //默认查看本月
                    var now = new Date();
                    var t = util.formatDate.format(now, 'yyyy-MM-dd');
                    var startStr = util.formatDate.format(new Date(), 'yyyy-MM') + "-01";
                    this.dateRange = [startStr,t];
                }
                this.exportParam.dateRange = this.dateRange;
            } else if (this.user.timeType.fixMonthcost == 1) {
                if (this.$route.query.startDate != null) {
                    this.dateRange = this.$route.query.startDate;
                } else {
                    //默认查看本月
                    var startStr = util.formatDate.format(new Date(), 'yyyy-MM');
                    this.dateRange = startStr;
                }
                this.exportParam.dateRange = this.dateRange;
            }
            this.radio = '项目'
            this.getEchart();
            var _this = this;
            window.addEventListener("resize", function() {
                _this.myChart.resize();
            });
            // this.getDepartment();
            this.getMyProjectList();
            this.getUsers()
            this.jutishez()
        },
    };
</script>

<style lang="scss" scoped>
    #container {
        // display: inline-block;
        display: block;
        position: absolute;
        // width: 100% !important; 
        margin-top: 60px;
    } 
</style>

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