<template>
    <section>
        <el-row style="padding-bottom: 0px;text-align:center;margin-top:20px;z-index: 999;">
        <el-col :span="6" >
            <div ><span style="color:#999;">{{ $t('chartY') }} </span>
            <el-radio-group v-model="yAxisValue" @change="onYAxisChange" size="small">
            <el-radio-button label="0" v-if="permissions.countCost">{{ $t('accordingtothecost') }}</el-radio-button>
            <el-radio-button label="1" v-if="permissions.countHours">{{ $t('accordingtoworkinghours') }}</el-radio-button>
            </el-radio-group></div>
        </el-col>
        <el-col :span="14" style="display: flex;flex-wrap: wrap;">
            <el-date-picker v-show="user.timeType.fixMonthcost==0"  size="small"
            v-model="dateRange" :editable="false" 
            format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
            @change="getEchart" 
            :clearable="true" 
            :range-separator="$t('other.to')"
            type="daterange" 
            :start-placeholder="$t('time.startDate')"
            :end-placeholder="$t('time.endDate')"
            ></el-date-picker>

            <el-date-picker v-show="user.timeType.fixMonthcost==1"
            v-model="dateRange" :editable="false"  size="small"
            format="yyyy-MM" value-format="yyyy-MM" 
            @change="getEchart" 
            :clearable="false" 
            type="month" 
            ></el-date-picker>

            <el-radio-group v-model="radio" @change="getEchart" style="margin-left:10px;"  size="small">
                <el-radio-button :label="$t('other.project')"></el-radio-button>
                <el-radio-button :label="$t('zhu-xiang-mu')" v-if="user.timeType.mainProjectState"></el-radio-button>
                <el-radio-button :label="$t('projectclassification')"></el-radio-button>
                <el-radio-button :label="$t('lable.department')"></el-radio-button>
                <el-radio-button :label="$t('ren-yuan')" v-if="permissions.countPersonnel"></el-radio-button>
                <el-radio-button :label="namess" v-if="jichu.customDegreeActive == 1"></el-radio-button>
                <el-radio-button v-for="item in theCustomList" :key="item.id" :label="item.name"></el-radio-button>
            </el-radio-group>
<!-- 
            <el-select v-model="customName" filterable placeholder="请选择" style="margin-top: 10px;width: 350px" v-if="theCustomListFlg" @change="jieliu()">
                <el-option v-for="item in customList" :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select> -->

            <el-select v-model="personnelValue" filterable clearable :placeholder="$t('pleaseselectpersonnel')"  size="small" style="margin-top: 10px;width: 350px" v-if="radio == $t('ren-yuan')" @change="personnel()">
                <el-option v-for="item in hasReportUserList" :key="item.id" :label="item.name" :value="item.name">
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px;margin-left: 20px" v-if="item.jobNumber">{{ item.jobNumber }}</span>
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="4">
            <el-button @click="exportProjectData" v-if="theCustomListFlg"  size="small">{{ $t('reporderived') }}</el-button>
            <el-button @click="showExportDialog" v-else  size="small">{{ $t('reporderived') }}</el-button>
        </el-col>
        </el-row>
        <!-- <div id="clearfix" :style="'width:'+widthHtval+'px;position: relative; height:'+containerHeight+'px;'">
             <div id="container" :style="'height:'+containerHeight+'px;width:100%'"></div>
        </div> -->
        <div id="clearfix" :class="radio == $t('ren-yuan') ? 'ryuans' : ''" :style="'overflow-x: auto;width:100%;padding-bottom: 100px; position: relative; height:'+containerHeight+'px;'">
            <div id="container" :style="'height:'+(containerHeight - 20)+'px;width:100%'"></div>
            <div class="poss">
                <el-pagination
                  @size-change="echartsSizeChange"
                  @current-change="echartsCurrentChange"
                  :current-page="page"
                  :page-sizes="[50]"
                  :page-size="50"
                  layout="total, sizes, prev, pager, next"
                  :total="total">
                </el-pagination>
            </div>
        </div>
        <!-- <div>
             <div id="container" :style="'height:'+containerHeight+'px;width:100%'"></div>
        </div> -->
        <div style="position:fixed;top:170px;left:600px;" v-show="radio==$t('lable.department') && parentDeptId != null">
            <el-button @click="backToParentDept">{{ $t('returnsuperior') }}</el-button>
        </div>

        <!--导出报表条件选择 -->
        <el-dialog :title="$t('timeReportExport')" 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="$t('defaultText.selectProject')" v-if="radio != $t('ren-yuan') && radio != $t('projectclassification') && radio != $t('lable.department')">
                    <el-select v-model="exportParam.projectId" :placeholder="$t('other.allProject')"  clearable style="width:350px;" filterable="true" popper-class="projectSelectPopperClass">
                        <el-option v-for="item in projectList"  :key="item.id" :label="item.projectName + item.projectCode" :value="item.id">
                            <span style="float: left;color: #8492a6;">{{ item.projectCode }}</span>
                            <span style="float: right;font-size: 13px;">{{ item.projectName }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item :label="$t('departmentchoice')" v-if="radio == $t('other.project')">
                    <el-cascader v-model="exportParam.deptId" :options="departmentList" :placeholder="$t('defaultText.pleaseChoose')"
                        :props="{ checkStrictly: true, expandTrigger: 'hover' }" clearable filterable style="width:350px;"
                    ></el-cascader>
                </el-form-item>

                <el-form-item prop="projectCategoryId" :label="$t('projectclassification')" v-if="radio == $t('projectclassification')">
                    <el-select v-model="exportParam.projectCategoryId" :placeholder="$t('classificationitems')"  clearable style="width:350px;" filterable="true">
                        <el-option v-for="item in categoryList"  :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="userIds" :label="$t('screening.selectPeople')" v-if="radio == $t('ren-yuan')">
                    <el-select v-model="exportParam.userIds" :placeholder="$t('lable.allStaff')" 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?$t('time.dateRange'):$t('Selectmonth')">
                    <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="$t('other.to')"
                        type="daterange" 
                        :start-placeholder="$t('time.startDate')"
                        :end-placeholder="$t('time.endDate')"
                    ></el-date-picker>

                    
                    <el-date-picker v-show="user.timeType.fixMonthcost==1"
                    v-model="dateRange" :editable="false" 
                    format="yyyy-MM" value-format="yyyy-MM" 
                    @change="getEchart" 
                    :clearable="true" 
                    type="month" 
                    ></el-date-picker>
                </el-form-item>
                
                <el-form-item :label="$t('screening.selectPeople')" v-if="radio == $t('other.project') || radio == $t('projectclassification')">
                    <el-select v-model="exportParam.userId"  :placeholder="$t('lable.allStaff')" style="width: 350px" filterable="true" clearable="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-item prop="type" :label="$t('choosethestyle')" v-if="radio == $t('other.project') || radio == $t('projectclassification')">
                    <el-select v-model="exportParam.type" :placeholder="$t('choosethestyle')" style="width:350px;" >
                        <el-option :label="radio == $t('projectclassification') ? $t('classifiedontheline') : $t('Itemontheline')" value="0"></el-option>
                        <el-option :label="radio == $t('projectclassification') ? $t('classifiedcolumns') : $t('itemisonthecolumn')" value="1"></el-option>
                    </el-select>
                    <div class="prompt">
                        <el-popover placement="top" width="1200" trigger="hover">
                            <img src="../../assets/image/hanglie.png" alt="" width="100%" v-if="this.radio != $t('projectclassification')">
                            <img src="../../assets/image/hanglie_corp.png" alt="" width="100%" v-else>
                            <i class="el-icon-question" slot="reference" />
                        </el-popover>
                    </div>
                </el-form-item>
                <el-form-item v-if="(radio == $t('other.project') || radio == $t('projectclassification')) && exportParam.type == '0'">
                    <el-checkbox v-model="exportParam.projectSum" >{{ $t('individualprojectdata') }}</el-checkbox>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exportProjectData" style="width:100%;" >{{ $t('export.export') }}</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from "../../common/js/util";
    export default {
        data() {
            return {
                allListData: [],
                page: 1,
                size: 50,
                total: 0,
                personnelValue: '',
                personnelAll: [],
                yAxisValue: localStorage.yAxisValue?localStorage.yAxisValue:0,
                parentDeptStack:[],
                parentDeptId:null,
                hasReportUserList:[],
                projectList:[],
                categoryList: [],
                exportParam:{projectId:null,dateRange:[],userId: null,type: '0'},
                exportDialog:false,
                dateRange:[],
                user: JSON.parse(sessionStorage.getItem("user")),
                permissions: JSON.parse(sessionStorage.getItem("permissions")),
                radio: sessionStorage.radio!=null?sessionStorage.radio:this.$t('other.project'),
                containerHeight: 0,    
                // myChart: null,
                params: null,
                widthHtval: document.body.clientWidth - 230,
                users: [],
                jichu: [],
                namess: '',
                timers: null, // 点击的时间
                zhishin: 0,
                theCustomList: [], // 自定义数据来源
                theCustomListFlg: false, // 判断是否点击的是自定义配置的数据来源
                theCustomListId: '',
                theCustomListPlantLIst: [],
                theCustomListPlant: '',
                customId: '',
                customName: '',
                customList: [],
                departmentList: []
            };
        },
        methods: {
            echartsCurrentChange(val){
                this.page = val
                // console.log('CurrentChange');
                if(this.radio == this.$t('ren-yuan')){
                    this.gtff()
                }else{
                    this.jieliu_echarts()
                }
                
            },
            //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)
                // this.http.post(this.port.manage.list, {
                //         departmentId: -1,
                //         pageIndex: 1,
                //         // pageSize: 99999
                //         pageSize: -1
                //     },
                this.http.post('/user/getSimpleActiveUserList', {},
                    res => {
                        if (res.code == "ok") {
                            this.users = res.data;
                        } else {
                            this.$message({
                            message: res.msg,
                            type: "error"
                            });
                        }
                    },
                    error => {
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                },
            
            showExportDialog() {
                // console.log(12345)
                this.exportDialog = true;
                this.exportParam.dateRange = this.dateRange;
                // console.log(this.hasReportUserList)
                if (this.radio == this.$t('ren-yuan')) {
                    // this.exportParam.userIds = [];
                }
                if (this.radio == this.$t('other.project')) {
                    this.exportParam.deptId = []
                }
            },
            //获取我的项目列表
            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 = {stateKey: 1};
                 if (this.exportParam.dateRange != null) {
                    param = {startDate:this.exportParam.dateRange[0], endDate: this.exportParam.dateRange[1],stateKey: 1};
                 }
                 var url = "/project/exportTimeCost";
                 var fileName = this.$t('projectmanhourcoststatistics')+ '.xls';
                 if (this.radio == this.$t('ren-yuan') ) {
                    //  console.log(this.exportParam.userIds);
                     fileName = this.$t('labortimecoststatistics')+ '.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.radio == this.$t('projectclassification')){
                    fileName = this.$t('projectclassificationlaborosttatistics')+ '.xls';
                    url = '/project/exportTimeCostByCategory'
                    if(this.exportParam.projectCategoryId){
                        param.projectCategoryId = this.exportParam.projectCategoryId
                    }
                }
                if(this.radio == this.$t('lable.department')){
                    fileName = this.$t('departmenthourscoststatistics')+ '.xls'
                    url = '/department/exportDeptStatistic'
                }
                
                if (this.exportParam.projectId && this.radio != this.$t('ren-yuan') && this.radio != this.$t('projectclassification')) {
                    param.projectId = this.exportParam.projectId;
                }
                if (this.exportParam.userId) {
                    if(this.radio == this.$t('other.project') || this.radio == this.$t('lable.department') || this.radio == this.$t('ren-yuan') || this.radio == this.$t('projectclassification')){
                        param.userId = this.exportParam.userId;
                    }
                }
                if (this.exportParam.type == 1) {
                    this.exportParam.projectSum = null
                }
                if (this.exportParam.projectSum != null) {
                    if(this.radio == this.$t('other.project') || this.radio == this.$t('lable.department') || this.radio == this.$t('projectclassification')){
                        param.projectSum = this.exportParam.projectSum;
                    }
                }
                if(!this.theCustomListFlg) {
                    param.type = this.exportParam.type*1
                } 
                if(this.theCustomListFlg) {
                    url = '/project/exportTimeCostByUserCustom'
                    fileName = this.radio + this.$t('statistical') + '.xls'
                    // param.subCustomName = this.customName
                    param.customId = this.theCustomListId
                    param.fieldName = this.theCustomListPlant
                }
                if(this.exportParam.deptId) {
                    if(this.exportParam.deptId.length > 0) {
                        param.deptId = this.exportParam.deptId[this.exportParam.deptId.length - 1]
                    }
                }
                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"
                        });
                    });
            },
            // 人员筛选
            personnel() {
                this.page = 1
                if(this.personnelValue) {
                    var arrlist = JSON.parse(JSON.stringify(this.personnelAll))
                    var arr = []
                    for(var i in arrlist.list) {
                        if(arrlist.list[i].name == this.personnelValue) {
                            arr.push(arrlist.list[i])
                        }
                    }
                    arrlist.list = arr
                    this.allListData = arrlist
                    this.gtff()
                } else {
                    this.allListData = this.personnelAll
                    this.gtff()
                }
            },
            //获取人员成本统计列表
            getUserCostList() {
                this.listLoading = true;
                // console.log(this.port.project.userCost, '获取人员成本统计列表')
                // console.log(this.user.timeType.fixMonthcost)
                // console.log(Boolean(this.dateRange))
                let startDateNum = ''
                let endDateNum = ''
                if(this.dateRange) {
                    startDateNum = this.user.timeType.fixMonthcost==0?this.dateRange[0]:this.dateRange
                    endDateNum = this.user.timeType.fixMonthcost==0?this.dateRange[1]:this.dateRange
                } 
                // return 
                this.http.post(this.port.project.userCost, {
                    // startDate:this.user.timeType.fixMonthcost==0?this.dateRange[0]:this.dateRange, 
                    // endDate: this.user.timeType.fixMonthcost==0?this.dateRange[1]:this.dateRange
                    startDate: startDateNum,
                    endDate: endDateNum
                },
                res => {
                    this.listLoading = false;
                    var _this = this;
                    this.hasReportUserList = [];
                    if (res.code == "ok") {
                        // 
                            
                        // 
                        this.personnelAll = res.data
                        this.allListData = res.data
                        this.gtff()
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 共同方法
            gtff() {
                let data = this.allListData
                var _this = this;
                this.hasReportUserList = data.userList;
                this.total = data.list.length
                var xList = [] , yList = [] , list = data.list.slice(0+50*(this.page-1),49+50*(this.page-1)), array = [] , series = [];
                var totalMoneyCost = data.totalCostMoney;
                var totalHours = 0.0;
                for(var i in list) {
                    if(i>20) {
                        this.widthHtval = +this.widthHtval + 60
                    } else {
                        this.widthHtval = document.body.clientWidth - 230
                    }
                }
                if (list.length > 0) {
                    var num = list.length==0?0:list[0].project.length;
                    // console.log('for 1');
                    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)
                            }
                        }
                    }
                    // console.log('for 2');
                    for(var i in array) {
                        yList.push(array[i]);
                        var dataList = [];
                        // console.log('for 2 1');
                        for(var j in list) {
                            var project = list[j].project , num = 0;
                            if(project.length != 0) {
                                // console.log('for 2 1 1');
                                for(var k in project) {
                                    if(project[k].project == array[i]) {
                                        let item = {
                                            "value": this.yAxisValue==0?project[k].money:project[k].time,
                                        }
                                        if(this.permissions.countCost){
                                            item.money = project[k].money
                                        }
                                        if(this.permissions.countHours){
                                            item.cost = project[k].time
                                            totalHours += parseFloat(project[k].time);
                                        }
                                        dataList.push(item)
                                        
                                    } else {
                                        num++;
                                    }
                                    if(k == project.length-1 && num != project.length-1) {
                                        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"));
                    totalHours = totalHours.toFixed(1);
                    // 设置宽度
                    myChart.resize({
                        width: this.widthHtval
                    })
                    // console.log('设置宽度');
                    // 设置宽度
                    _this.myChart = myChart;
                    var option = { 
                        //总成本
                        title: {
                            // text: '工时成本总计' + totalMoneyCost.toFixed(2) + '元, 时长'+totalHours+'小时',
                            text: this.$t('otalhourscost')+ '：' + 
                            ((this.permissions.countCost) ? this.$t('costof') + ' ' + totalMoneyCost.toFixed(2) + ' ' + this.$t('yuan') + ',' : '') + 
                            ((this.permissions.countHours) ? this.$t('time.duration') + ' ' +totalHours + ' ' + this.$t('time.hour') : ''),
                            left:'left',
                        },
                        // 工具箱
                        legend: {
                            x: 80,
                            y: 10,
                            data: yList,
                            show: true,
                    　　　　　 top:"5%",//与上方的距离 可百分比% 可像素px
                        },
                        grid : {
                            top : 80,    //距离容器上边界40像素
                            // bottom: 100,   //距离容器下边界30像素
                            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;
                                var totalCost = 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'>" + _this.$t('headerTop.projectName') + "：" + params[i].seriesName 
                                            + "</font><br/>" + 
                                            ((_this.permissions.countCost) ? _this.$t('workcost')+ ":" + params[i].data.money + _this.$t('yuan') + "</br>" : '') + 
                                            ((_this.permissions.countHours) ? _this.$t('screening.workTime') + ":" + params[i].data.cost + _this.$t('time.hour') + "</br>" : '') + "</div>";
                                        totalTime += Number(params[i].data.cost);
                                        totalCost += Number(params[i].data.money);
                                    }
                                }
                                res = res +'<br/>'+ params[0].name+ '<br/>' + _this.$t('zong-ji') + '：' + 
                                ((_this.permissions.countHours) ? totalTime.toFixed(1) + _this.$t('time.hour') : '') + 
                                ((_this.permissions.countCost) ? totalCost.toFixed(2) + _this.$t('yuan') : '') + 
                                "<br/>";
                                return res;
                            }
                        },
                        xAxis: {
                            data: xList,
                            axisLabel: {
                                interval:0,rotate:20
                            }
                        },
                        yAxis: [{
                            type : 'value',
                            axisLabel: {
                                formatter:this.yAxisValue==0?'{value} ('+this.$t('yuan')+')':'{value} ('+this.$t('time.hour')+')'
                                // formatter:this.yAxisValue==0?'{value} (元)':'{value} (小时)'
                            }
                        }],
                        series: series,
                    };
                    // console.log('setoption');
                    myChart.setOption(option,{notMerge:true});
            },
            yanjiu() {
                // console.log('触发')
            },
            getEchart(e){
                var that = this
                // 更具选中的名字筛选出对应的自定义id
                that.theCustomListFlg = false
                let ints = null
                for(var i in that.theCustomList) {
                    if(that.radio == that.theCustomList[i].name) {
                        that.theCustomListId = that.theCustomList[i].id
                        that.theCustomListPlant = that.theCustomListPlantLIst[i]
                        that.theCustomListFlg = true
                        ints = i
                    }
                }
                if(that.theCustomListFlg) {
                    that.customList = that.theCustomList[ints].subUserCustomList
                    that.customName = that.theCustomList[ints].subUserCustomList[0].name
                    // that.getCusTom()
                }
                that.jieliu()
            },
            getCusTom() {
                this.http.post('/sub-user-custom/list',{
                    userCustomId: this.theCustomListId
                },res => {
                    if(res.code == 'ok'){
                        this.customList = res.data
                        this.customName = res.data[0].name
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    })
                })
            },
            getCategoryList(){
                this.http.post('/project-category/list',{},
                res => {
                    if(res.code == 'ok'){
                        this.categoryList = res.data
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                })
            },
            backToParentDept() {
                if (this.radio == this.$t('lable.department')) {
                    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 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==this.$t('other.project')) {
                    url = this.port.project.listCost;
                }else if(this.radio == this.$t('zhu-xiang-mu')){
                    url = '/project/getTimeCostByMainProject'
                    // param.userId = this.user.id
                }else if (this.radio==this.$t('projectclassification')) {
                    url = '/project/getTimeCostByCategory';
                    // param.parentDeptId = this.parentDeptId;
                    // param.userId = this.user.id
                } else if (this.radio==this.$t('lable.department')) {
                    url = this.port.project.depCost;
                    param.parentDeptId = this.parentDeptId;
                } else if (this.radio==this.$t('ren-yuan')) {
                    this.getUserCostList();
                    return;
                } else if (this.radio == this.namess) {
                    url = '/project/getDegreeCost'
                } else if (this.theCustomListFlg) {
                    url = '/project/getTimeCostByUserCustom'
                    // param.subCustomName = this.customName
                    param.customId = this.theCustomListId
                    param.fieldName = this.theCustomListPlant
                    // console.log(param, '要传的数据')
                }
                this.http.post(url, param,
                res => {
                    if (res.code == "ok") {
                        this.allListData = res.data
                        this.page = 1
                        if(this.user.userNameNeedTranslate == '1' && this.radio == this.$t('lable.department')) {
                            console.log('进入我处理的方法')
                            let arr = []
                            for(var i in this.allListData.costList) {
                                let obj = {}
                                obj.type = this.allListData.costList[i].type
                                obj.id = this.allListData.costList[i].departmentName
                                arr.push(obj)
                            }
                            this.dealWithTranslation(arr)
                        } else {
                            this.jieliu_echarts()
                        }
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            dealWithTranslation(items) {
                console.log('进来的值', items)

                    if (WWOpenData.initCanvas) {
                        WWOpenData.initCanvas()
                        console.log('成功了吧')
                    }
                    
                    const myFunOne = async () => {
                        const result = await new Promise((resolve, reject) => {
                            console.log('我触发了')
                            console.log(WWOpenData)
                            console.log(WWOpenData.prefetch)
                            if(WWOpenData.prefetch) {
                                 WWOpenData.prefetch({ items }, (err, data) => {
                                    console.log(items)
                                    console.log(err)
                                    console.log(data)
                                    if (err) { return reject(err) }
                                    resolve(data)
                                })
                            }
                           
                        })
                        console.log(result, '取到的数据')
                        // result.items.map((v)=>{
                        //     console.log(v,'返回数据 Echar 图标')
                        //     this.dep_name.push(v.data)
                        // })
                        // this.on_analysis() // ECharts 渲染函数
                        let arrList = []
                        for(var i in result) {
                            this.allListData.costList[i].departmentName = result[i].data
                        }
                        console.log(this.allListData, '最终的数据')
                        this.jieliu_echarts()
                    }
                    
                    myFunOne()
            },
            jieliu_echarts(){
                var _this = this;
                // 更具数据的长度去加每个柱子的间距
                        var xList = []
                        var yList = []
                        var list
                        var totalMoneyCost;
                        var totalHours = 0.0;
                        if(this.radio == this.$t('other.project') || this.radio == this.$t('projectclassification') || this.radio==this.$t('lable.department') || this.radio == this.$t('zhu-xiang-mu')) {
                            // this.allListData = res.data.costList
                            this.total = this.allListData.costList.length
                            list = this.allListData.costList.slice(0+50*(this.page-1),49+50*(this.page-1))
                            for(var i in list) {
                                if(i>20) {
                                    this.widthHtval = +this.widthHtval + 60
                                } else {
                                    this.widthHtval = document.body.clientWidth - 230
                                }
                            }
                            // list = res.data.costList
                            totalMoneyCost = ((this.radio==this.$t('other.project') || this.radio == this.$t('projectclassification'))?this.allListData.totalMoneyCost:this.allListData.totalCostMoney);

                            for(var i in list) {
                                if(this.radio==this.$t('other.project') || this.radio == this.$t('zhu-xiang-mu')) {
                                    if(this.radio == this.$t('other.project')){
                                        xList.push(list[i].project);
                                    }else{
                                        xList.push(list[i].mainProjectName);
                                    }
                                    
                                    let item = {
                                        "value": this.yAxisValue==0?(list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney:(list[i].cost ? list[i].cost.toFixed(1) : 0),
                                        "id": list[i].id || i,
                                    }
                                    if(this.permissions.countCost){
                                        // item.money = list[i].costMoney.toFixed(2)
                                        item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                                    }
                                    if(this.permissions.countHours){
                                        item.cost = list[i].cost
                                        totalHours += parseFloat(list[i].cost);
                                    }
                                    yList.push(item);
                                    
                                } else if(this.radio == this.$t('lable.department')){
                                    xList.push(list[i].departmentName);
                                    let item = {
                                        // "value": this.yAxisValue==0 ? list[i].costMoney.toFixed(2) || list[i].costMoney: list[i].costTime.toFixed(1),
                                        "value": this.yAxisValue==0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney: (list[i].costTime ? list[i].costTime.toFixed(1) : 0),
                                        "id": list[i].departmentId,
                                        "hasSubDept": list[i].hasSubDept
                                    }
                                    if(this.permissions.countCost){
                                        // item.money = list[i].costMoney.toFixed(2)
                                        item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                                    }
                                    if(this.permissions.countHours){
                                        item.cost = list[i].costTime
                                        totalHours += parseFloat(list[i].costTime);
                                    }
                                    yList.push(item);
                                    
                                }else {
                                    xList.push(list[i].categoryName);
                                    let item = {
                                        // "value": this.yAxisValue==0?list[i].costMoney.toFixed(2) || list[i].costMoney:list[i].cost.toFixed(1),
                                        "value": this.yAxisValue==0?(list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney:(list[i].cost ? list[i].cost.toFixed(1) : 0),
                                        "id": list[i].id || i,
                                    }
                                    if(this.permissions.countCost){
                                        // item.money = list[i].costMoney.toFixed(2)
                                        item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                                    }
                                    if(this.permissions.countHours){
                                        item.cost = list[i].cost
                                        totalHours += parseFloat(list[i].cost);
                                    }
                                    yList.push(item);
                                }
                            }
                        } 
                        else if(this.theCustomListFlg) {
                            // this.allListData = res.data.list
                            this.total = this.allListData.list.length
                            list = this.allListData.list.slice(0+50*(this.page-1),49+50*(this.page-1))
                            // list = res.data.list
                            
                            for(var i in list) {
                                // console.log(list[i].name, list[i].costMoney, list[i].cost)
                                xList.push(list[i].name);
                                let item = {
                                    "value": this.yAxisValue==0?list[i].costMoney:list[i].cost,
                                    "id": list[i].id || i,
                                }
                                if(this.permissions.countCost){
                                    // item.money = list[i].costMoney.toFixed(2)
                                    item.money = list[i].costMoney ? list[i].costMoney.toFixed(2) : 0
                                    totalMoneyCost += parseFloat(list[i].costMoney);
                                }
                                if(this.permissions.countHours){
                                    item.cost = list[i].cost
                                    totalHours += parseFloat(list[i].cost);
                                }
                                yList.push(item);
                                
                            }
                        } 
                        else {
                            // list = res.data
                            // this.allListData = res.data
                            this.total = this.allListData.length
                            list = this.allListData.slice(0+50*(this.page-1),49+50*(this.page-1))
                            
                            for(var i in list) {
                                // console.log(list[i].name, list[i].costMoney, list[i].cost)
                                xList.push(list[i].name);
                                let item = {
                                    "value": this.yAxisValue==0?list[i].costMoney:list[i].cost,
                                    "id": list[i].id || i,
                                }
                                if(this.permissions.countCost){
                                    // item.money = list[i].costMoney.toFixed(2)
                                    item.money = list[i].costMoney ? list[i].costMoney.toFixed(2) : 0
                                    totalMoneyCost += parseFloat(list[i].costMoney);
                                }
                                if(this.permissions.countHours){
                                    item.cost = list[i].cost
                                    totalHours += parseFloat(list[i].cost);
                                }
                                yList.push(item);
                                
                            }
                        }
                        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.$t('other.project') || this.radio == this.$t('zhu-xiang-mu') || this.radio == this.$t('ren-yuan') || this.radio == this.$t('projectclassification') || this.radio==this.$t('lable.department')) {
                            var option = {
                                title: {
                                    text: this.$t('otalhourscost') + '：' + ((this.permissions.countCost) ? this.$t('costof') + ' ' + this.zhishin + ' ' +this.$t('yuan') + ',' : '') + ((this.permissions.countHours) ? this.$t('time.duration') + ' ' +totalHours+ ' ' +this.$t('time.hour') : ''),
                                    left:'left',
                                },
                                // 工具箱
                                toolbox: {
                                    show: true,
                                    feature:{
                                        saveAsImage:{show:true},restore:{show:true}, magicType:{ type:['line','bar']},
                                    }
                                },
                                tooltip:{
                                    trigger:'axis',
                                    formatter: function (params,ticket,callback) {
                                        _this.params = params;
                                        var res = params[0].name + "<br/>" + 
                                        ((_this.permissions.countCost) ? _this.$t('workcost')+" : " + params[0].data.money 
                                        + _this.$t('yuan')+"<br/>" : '') + 
                                        ((_this.permissions.countHours) ? _this.$t('screening.workTime')+" : " + params[0].data.cost + _this.$t('time.hour') : '');
                                        // console.log(res, '将要渲染的数据')
                                        return res;
                                    }
                                    // trigger:'axis',
                                    //  formatter: function (params,ticket,callback) {
                                    //      _this.params = params;
                                    //      var res = params[0].name + "<br/>" + 
                                    //      ((_this.permissions.countCost) ? "工作成本"+" : " + params[0].data.money 
                                    //      + "元 <br/>" : '') + 
                                    //      ((_this.permissions.countHours) ? "工作时长"+" : " + params[0].data.cost + "小时" : '');
                                    //      return res;
                                    //  }

                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:this.yAxisValue==0?'{value} ('+this.$t('yuan')+')':'{value}'+this.$t('time.hour')
                                    }
                                }],
                                series: [{
                                    name: this.yAxisValue==0?this.$t('workcost')+'（'+this.$t('yuan')+'）':this.$t('screening.workTime')+'（'+this.$t('time.hour')+'）',
                                    type: 'bar',
                                    barMaxWidth: 30,
                                    data: yList,
                                }],
                                grid: {  
                                    left: '100px',  
                                }  
                            };
                        } else {
                            var option = {
                                title: {
                                    // text: '工时成本总计' + this.zhishin + '元, 时长'+totalHours+'小时',
                                    text: this.$t('otalhourscost')+ '：' + ((this.permissions.countCost) ? this.$t('costof') + ' ' + this.zhishin + ' ' + this.$t('yuan')+ ',' : '') + ((this.permissions.countHours) ? this.$t('time.duration') + ' ' + totalHours + ' ' + this.$t('time.hour') : ''),
                                    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.permissions.countCost) ? _this.$t('workcost')+" : " + params[0].data.money 
                                        + _this.$t('yuan')+"<br/>" : '') + 
                                        ((_this.permissions.countHours) ? _this.$t('screening.workTime')+" : " + params[0].data.cost + _this.$t('time.hour') : '');
                                        _this.params = params;
                                        return res;
                                    }
                                },
                                xAxis: {
                                    data: xList,
                                    axisLabel: {
                                        interval:0,rotate:20
                                    }
                                },
                                yAxis: [{
                                    type : 'value',
                                    axisLabel: {
                                        formatter:this.yAxisValue==0?'{value} ('+this.$t('yuan')+')':'{value}'+this.$t('time.hour')
                                    }
                                }],
                                series: [{
                                    name: this.yAxisValue==0?this.$t('workcost')+'（'+this.$t('yuan')+'）':this.$t('screening.workTime')+'（'+this.$t('time.hour')+'）',
                                    type: 'bar',
                                    barMaxWidth: 30,
                                    data: yList,
                                }],
                                grid: {  
                                    left: '100px',  
                                }  
                            };
                        }
                        
                        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.$t('other.project')) {
                                    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==this.$t('lable.department')) {
                                    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);
                                        }
                                    }
                                }
                            }
                        });
            },

            // 左右滚动
            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
            },
            // 判断后端给的字段
            // 获取自定义
            getZDY() {
                this.http.post('/user-custom/getUserCustomTitle',{},res => {
                    if(res.code == 'ok'){
                        // console.log(res, '数据来源')
                        this.theCustomList = res.data.result
                        this.theCustomListPlantLIst = res.data.field
                    }else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    })
                })
            },
            // 获取部门
            getDepartmentList() {
                this.http.post( this.port.manage.depList, {},
                    res => {
                    if (res.code == "ok") {
                        let dptlist = JSON.parse(JSON.stringify(res.data));
                        this.departmentList = this.changeArr(dptlist);
                    } 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;
            },
        },
        created() {
            this.myChart = null
        },
        mounted() {
            this.containerHeight = window.innerHeight - 200
            // this.containerHeight = window.innerHeight - 130
            const that = this;
            window.onresize = function temp() {
                this.containerHeight = window.innerHeight - 130
                // this.containerHeight = window.innerHeight - 200
            };
            if(this.permissions.countCost){
                this.yAxisValue = '0'
            }else{
                this.yAxisValue = '1'
            }
            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.$t('other.project')
            this.getEchart();
            var _this = this;
            window.addEventListener("resize", function() {
                _this.myChart.resize();
            });
            // this.getDepartment();
            this.getMyProjectList();
            this.getUsers()
            this.jutishez()
            this.scrollFunction()
            // 判断
            if(this.user.timeType.userCustomStatic) {
                this.getZDY()
            }
            this.getDepartmentList()
        },
        beforeDestroy () {
            var myChart = echarts.init(document.getElementById("container"));
            myChart.clear()
        },
    };
</script>

<style lang="scss" scoped>
    #container {
        // display: inline-block;
        display: block;
        position: absolute;
        // width: 100% !important; 
        margin-top: 60px;
    } 
    .ryuans {
        top: -50px;
    }
    .prompt {
        position: absolute;
        right: 10px;
        top: 0;
    }
    .poss {
        position: fixed;
        bottom: -10px;
        right: 1%;
        box-sizing: border-box;
    }
</style>

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