<template>
  <div class="testdiv">
    <div class="divborder" style="margin:0px;">
        <div class="filter">
          <label >{{$t('1132')}}：</label>
          <Cascader :data="datalevel" :value="leveldata" trigger="click" change-on-select style="display:inline-block;width:200px;" @on-change="getlevel"></Cascader>
      </div>
         <div class="filter">
         <label >{{$t('200179')}}:</label>
         <Select v-model="group" label-in-value clearable style="width:160px;" @on-change="groupchange">
              <Option v-for="item in grouplist" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>
         <div class="filter">
         <label >{{$t('200208')}}</label>
         <Select v-model="user" label-in-value clearable style="width:160px;" >
              <Option v-for="item in userlist" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>
         <div class="filter">
         <label >{{$t('900908')}}:</label>
         <DatePicker type="daterange" :value="dateTime" placeholder="Select date" style="width: 300px;"  @on-change="selectdate"></DatePicker>
        </div>
          <Button type="primary" style="margin:0 10px" icon="ios-search" @click="search(0)">{{$t('1001')}}</Button>
          <Button type="primary" style="margin:0 10px" icon="ios-cloud-download" @click="search(1)()">{{$t('1007')}}</Button>
    </div>
     <div id="div_echarts" style="height:400px;padding:10px;">
      </div>
    <div class="divborder">
      <Table
        style="margin-top:10px"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        @on-selection-change="handleSelectRow"
        :columns="tableColumns1"></Table>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import axios from '@/libs/api.request'
export default {
    name: 'producetime', // 组件不刷新
    data () {
        return {
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            datalevel: [],
            tableData1: [],
            detailobj: {},
            treeContents: [],
            group: 0,
            grouplist: [],
            user: 0,
            userlist: [],
            dateTime: '',
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + 1
                        )
                    },
                    width: '60px'
                },
                {
                    title: this.$t('200003'),
                    key: 'location'
                },
                {
                    title: this.$t('950296'),
                    key: 'user_name'
                },
                {
                    title: this.$t('100088'),
                    key: 'product_name'
                },
                {
                    title: this.$t('900967'),
                    key: 'route_name'
                },
                {
                    title: this.$t('100090'),
                    key: 'drawcode'
                },
                {
                    title: this.$t('950297'),
                    key: 'actual_beat'
                },
                {
                    title: this.$t('950298'),
                    key: 'actual_updown'
                },
                {
                    title: this.$t('1049'),
                    key: 'start_time'
                },
                {
                    title: this.$t('1050'),
                    key: 'end_time'
                }
            ]
        }
    },
    created () {
        this.initlevel()
        this.inittime()
        this.getgroups()
        this.search(0)
    },
    methods: {
    // 产线层级
        initlevel () {
            axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                const arr = []
                this.datalevel = res.data.data
                arr.push(res.data.data[0].value)
                this.leveldata = arr
            })
        },
        // 产线层级选择
        getlevel: function (data) {
            this.levelid = data[data.length - 1]
        },
        inittime () {
            // 时间赋值
            var date = new Date()
            this.dateTime = [moment(date.getTime() - 3600 * 1000 * 24 * 15).format('YYYY-MM-DD ') + '00:00:00', moment(date.getTime()).format('YYYY-MM-DD HH:mm:ss')]
        },
        selectdate (e) {
            this.dateTime = [e[0], e[1]]
        },
        getgroups () {
            axios.request({
                url: '/config/WorkingGroup/GetAllWorkGroup?departid=0',
                method: 'get'
            }).then(res => {
                this.grouplist = res.data.data
            })
        },
        getusers () {
            axios.request({
                url: '/config/WorkingGroup/GetAllUsersByWorkGroup?id=' + this.group,
                method: 'get'
            }).then(res => {
                this.userlist = res.data.data
            })
        },
        groupchange () {
            this.getusers()
        },
        search (toexcel) {
            var params = {
                level_id: this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1],
                userId: this.user,
                workgroupId: this.group,
                timerange: moment(this.dateTime[0]).format('YYYY-MM-DD HH:mm:ss') + ' - ' + moment(this.dateTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                toexcel: toexcel
            }
            axios
                .request({
                    url: '/cnc/WorkingState/MachineBeatAnalysis',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.baseEcharts()
                    if (toexcel === 1) {
                        if (res.data.ret === 1) {
                            window.location.href = axios.publicPath + '' + res.data.data
                        } else {
                            this.$Message.error(this.$t(res.data.msg))
                        }
                    } else {
                        this.tableData1 = []

                        if (res.data.data != null && res.data.data.length > 1) {
                            var xname = []
                            var y_data1 = []
                            var y_data2 = []
                            res.data.data.forEach(ele => {
                                xname.push(ele.machine_name)
                                y_data1.push(ele.actual_beat)
                                y_data2.push(ele.actual_updown)
                            })
                            this.getEcharts(xname, y_data1, y_data2, res.data.data)
                            this.mockTableData1(res.data.data)
                        }
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        location: item.location,
                        user_name: item.user_name,
                        product_name: item.product_name,
                        route_name: item.route_name,
                        drawcode: item.drawcode,
                        actual_beat: item.actual_beat === 0 ? 'NA' : item.actual_beat,
                        actual_updown: item.actual_updown === 0 ? 'NA' : item.actual_updown,
                        start_time: item.start_time,
                        end_time: item.end_time,
                        id: item.id
                    })
                }
            })
            this.tableData1 = data
        },
        getEcharts (xname, ydata1, ydata2, data) {
            var main_test = echarts.init(document.getElementById('div_echarts'))
            main_test.setOption({
                tooltip: {
                    backgroundColor: 'rgba(255,0,0,0)', // 通过设置rgba调节背景颜色与透明度
                    formatter: params => {
                        var showHtm = ''
                        var code = 0
                        data.forEach(ele => {
                            if (code === 0 && ele.machine_name === params[0]['name']) {
                                showHtm += '<div style="background-color:gray;border-radius:5px;padding:5px;">' + ele.machine_name + '<br>' +
                                    this.$t('100088') + '：' + ele.product_name + '<br>' +
                                    this.$t('500006') + '：' + ele.route_name + '<br>' +
                                    this.$t('950299') + '：' + ele.actual_beat + '<br>' +
                                    this.$t('950300') + '：' + ele.actual_updown + '<br>' +
                                    '</div>'
                            }
                            code++
                        })
                        return showHtm
                    }
                },
                xAxis: {
                    data: xname
                },
                series: [
                    {
                        data: ydata1
                    },
                    {
                        data: ydata2
                    }
                ]
            })
        },
        baseEcharts () {
            var option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    data: [this.$t('950299'), this.$t('950300')]// 关机排在最后
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: []
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: this.$t(940010),
                        min: 0
                    }
                ],
                series: [

                    {
                        name: this.$t('950299'),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: this.$t('500067'),
                        data: [],
                        itemStyle: {
                            normal: {
                                color: 'rgba(97, 165, 232, 1)'
                            }
                        }
                    },
                    {
                        name: this.$t('950300'),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: this.$t('500067'),
                        data: [],
                        itemStyle: {
                            normal: {
                                color: 'rgba(126, 207, 81, 1)'
                            }
                        }
                    }
                ]
            }
            var main_test = echarts.init(document.getElementById('div_echarts'))
            main_test.clear()
            main_test.setOption(option)
        },
        handleSelectRow: function (data) {
            var ids = []
            for (var i in data) {
                ids.push(data[i].id)
            }
            this.selectids = ids
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        Export () {
            let params = {
            }
            axios.request({
                url: '/config/BeatSetDownLoad/GetTemplates',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = axios.publicPath + '' + res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg));
                }
            })
        }
    }
}
</script>
<style lang="less">
    .treeSelect{
      span{
        background:#2D8CF1;
        color:#fff;
        margin: 0;
        padding: 0 4px;
        border-radius: 3px;
        cursor: pointer;
        vertical-align: top;
      }
}
</style>
