<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item>
                    <el-button type="text" @click="backToList" icon="el-icon-back" class="back">{{ $t('fan-hui') }}</el-button>
                </el-form-item>
                <el-form-item class="divLine"></el-form-item>
                <el-form-item>
                    <span class="workName">{{detailName}}</span>
                </el-form-item>
                <el-form-item style="float:right;">
                    <span style="font-size:18px;">{{ $t('xiang-mu-cheng-ben') }}：<span style="color:#20a0ff;">{{cost.toFixed(2)}}{{ $t('yuan') }}</span></span>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="24"  style="margin-top:10px;padding-bottom: 0px;text-align:center;">
            <el-radio-group v-model="radio" @change="getList">
                <el-radio-button :label="$t('ren-yuan')"></el-radio-button>
                <!-- <el-radio-button :label="$t('other.taskGroup')" v-if="user.company.packageProject != 0"></el-radio-button> -->
                <el-radio-button :label="$t('lable.subproject')" v-if="user.timeType.mainProjectState != '1'"></el-radio-button>
                <!-- <el-radio-button :label="$t('jie-duan')" v-if="user.company.packageProject != 0"></el-radio-button> -->
            </el-radio-group>
        </el-col>
        <div id="clearfix" :style="'overflow-x: auto;width:100%;padding-bottom: 0px; position: relative; height:'+containerHeight+'px;'">
            <div id="container" :style="'height:' + tableHeight + 'px'"></div> 
        </div>
    </section>
</template>

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

    export default {
        data() {
            return {
                yAxisValue: localStorage.yAxisValue,
                startDate:null,
                endDate: null,
                detailId: this.$route.params.id,
                detailName: this.$route.params.name,
                radio:this.$t('ren-yuan'),
                user: JSON.parse(sessionStorage.getItem("user")),

                cost: 0,

                tableHeight: 0,
                
                echart: null,
            };
        },
        methods: {
            //返回
            backToList() {
                if (this.startDate != null) {
                    this.$router.push("/cost?startDate="+this.startDate+"&endDate="+this.endDate);
                } else {
                    this.$router.push("/cost");
                }
            },

            //获取项目列表
            getList() {
                this.listLoading = true;
                var url = "";
                if (this.radio==this.$t('ren-yuan')) {
                    url = this.port.project.projectCost;
                } else if (this.radio==this.$t('other.taskGroup')) {
                    url = '/project/getCostByGroup';
                } else if (this.radio==this.$t('lable.subproject')) {
                    url = '/sub-project/getTimeCost';
                } else {
                    url = "/project/getCostInStage";
                }
                this.http.post(url, {
                    id: this.detailId,
                    startDate: this.startDate,
                    endDate: this.endDate,
                },
                res => {
                    // 
                        for(var i in res.data.costList) {
                            if(i>20) {
                                this.widthHtval = +this.widthHtval + 40
                            } else {
                                this.widthHtval = document.body.clientWidth - 230
                            }
                        }
                    // 
                    this.listLoading = false;
                    var _this = this;
                    if (res.code == "ok") {
                        if(this.user.userNameNeedTranslate == 1 && this.radio == this.$t('ren-yuan')) {
                            let arr = []
                            for(var i in res.data.costList) {
                                let obj = {}
                                obj.type = 'userName'
                                obj.id = res.data.costList[i].name
                                arr.push(obj)
                            }
                            this.dealWithTranslation(arr, res.data.costList, res.data.totalMoneyCost)
                            // this.pullAway(res.data.costList, res.data.totalMoneyCost)
                        } else {
                            this.pullAway(res.data.costList, res.data.totalMoneyCost)
                        }
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            dealWithTranslation(items, dataArr, cosess) {
                if (WWOpenData.initCanvas) {
                    WWOpenData.initCanvas()
                }
                const myFunOne = async () => {
                    const result = await new Promise((resolve, reject) => {
                        if(WWOpenData.prefetch) {
                             WWOpenData.prefetch({ items }, (err, data) => {
                                if (err) { return reject(err) }
                                resolve(data)
                            })
                        }
                       
                    })
                    for(var i in dataArr) {
                        dataArr[i].name = result.items[i].data
                    }
                    this.pullAway(dataArr, cosess)
                }
                
                myFunOne()
            },
            // 抽离出来的方法
            pullAway(datalist, cosess) {
                // var xList = [],yList = [] , list = res.data.costList;
                var _this = this;
                var xList = [],yList = [] , list = datalist;
                // this.cost = res.data.totalMoneyCost;
                this.cost = cosess;
                for(var i in list) {
                    if(this.radio == this.$t('other.taskGroup')){
                        xList.push(list[i].GroupName);
                    }else{
                        xList.push(list[i].name);
                    }
                    yList.push({
                        "value": this.yAxisValue==0?list[i].costMoney:list[i].cost,
                        "cost": list[i].cost,
                        "money": list[i].costMoney,
                    });
                }

                var myChart = echarts.init(document.getElementById("container"));
                // 设置宽度
                myChart.resize({
                    width: this.widthHtval
                })
                _this.myChart = myChart;
                var option = {
                    // 工具箱
                    toolbox: {
                        show: true,
                        feature:{
                            saveAsImage:{
                                show: this.user.userNameNeedTranslate == 1 ? false : true
                            },
                            restore:{
                                show:true
                            },
                            magicType:{
                                type:['line','bar']
                            }
                        }
                    },
                    grid : {
                        top : 80,    //距离容器上边界40像素
                        bottom: 100,   //距离容器下边界30像素
                        left: 150,
                        right: 150
                    },
                    tooltip:{
                        trigger:'axis',
                        formatter: function (params,ticket,callback) {
                            var res
                            if(_this.user.userNameNeedTranslate == 1 && _this.radio == _this.$t('ren-yuan')) {
                                res = '' + "<br/>"+_this.$t('workcost')+" : " + params[0].data.money 
                                + _this.$t('yuan')+"<br/>"+_this.$t('screening.workTime')+" : " + params[0].data.cost + _this.$t('time.hour');
                            } else {
                                res = params[0].name + "<br/>"+_this.$t('workcost')+" : " + params[0].data.money 
                                + _this.$t('yuan')+"<br/>"+_this.$t('screening.workTime')+" : " + params[0].data.cost + _this.$t('time.hour');
                            }
                            
                            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?_this.$t('workcost')+'（'+_this.$t('yuan')+'）':_this.$t('screening.workTime')+'（'+_this.$t('time.hour')+'）',
                        type: 'bar',
                        barMaxWidth: 30,
                        data: yList,
                    }]
                };
                myChart.setOption(option,{notMerge: true});
            },
             // 左右滚动
            scrollFunction () {
                this.domObj = document.getElementById('clearfix') // 通过id获取要设置的div
                if (this.domObj.attachEvent) { // IE
                this.domObj.attachEvent('onmousewheel', this.mouseScroll)
                } else if (this.domObj.addEventListener) {
                this.domObj.addEventListener('DOMMouseScroll', this.mouseScroll, false)
                }
                this.domObj.onmousewheel = this.domObj.onmousewheel = this.mouseScroll
            },

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

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

    #container {
        float: left;
        width: 100%;
    }
</style>

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