<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('200207')}}</label>
        <Select v-model="section" label-in-value @on-change="sectionchange" clearable style="width:160px;" >
              <Option v-for="item in sectionlist" :value="item.id" :key="item.id">{{ item.title }}</Option>
          </Select>
        </div>
         <div class="filter">
         <label >{{$t('200179')}}:</label>
         <Select v-model="group" label-in-value clearable style="width:160px;" >
              <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>
         <div class="filter">
         <label >{{$t('950288')}}:</label>
          <Select v-model="state" label-in-value clearable style="width:160px;" >
              <Option v-for="item in statelist" :value="item.id" :key="item.id">{{ item.title }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t('1129')}}：</label>
          <Select v-model="xtype" style="width:120px;" @on-change="xTypechange">
            <Option :value='2' v-text="$t('500065')">时间单位</Option>
            <Option :value='3' v-text="$t('1132')">产线层级</Option>
            <Option :value='1' v-text="$t('950292')">状态类型</Option>
            <Option :value='4' v-text="$t('950289')">班组</Option>
          </Select>
          <Select v-model="type3" clearable style="width:120px;margin-left:10px;" v-show="showStr">
            <Option v-for="(item,key) in xTypeList" :value="item.value" :key="key">{{ item.label }}</Option>
          </Select>
      </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;">
      </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: [],
            sectionlist: [],
            section: 0,
            group: 0,
            grouplist: [],
            user: 0,
            userlist: [],
            state: 0,
            statelist: [],
            dateTime: '',
            xtype: 2,
            type3: 0,
            showStr: true,
            xTypeList: [],
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + 1
                        )
                    },
                    width: '60px'
                },
                {
                    title: this.$t('950288'),
                    key: 'key'
                },
                {
                    title: this.$t('950294'),
                    key: 'value'
                }
            ]
        }
    },
    created () {
        this.initlevel()
        this.getsections()
        this.getstates()
        this.inittime()
        this.inidatetype()
        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]
        },
        inidatetype () {
            this.xTypeList = [{ value: 0, label: this.$t(900864) }, { value: 1, label: this.$t(1136) }, { value: 2, label: this.$t(1138) }]
        },
        // 横坐标选择
        xTypechange () {
            this.showStr = true
            if (this.xtype === 0) {
                this.xTypeList = [{ value: 0, label: this.$t(900864) }, { value: 1, label: this.$t(1136) }, { value: 2, label: this.$t(1138) }]
                this.type3 = 0
            } else if (this.xtype === 1) {
                this.getLevels()
            } else {
                this.showStr = false
                this.xTypeList = []
            }
        },
        getLevels () {
            this.xTypeList = []
            axios.request({
                url: '/config/ProjectLevelSection/GetLevelsBySection?sectionId=' + this.levelid,
                method: 'get'
            }).then(res => {
                // 产线层级
                if (res.data.ret === 1 && this.xtype === 1) {
                    if (res.data.data.length !== 0) {
                        res.data.data.forEach(item => {
                            this.xTypeList.push({ value: item.id, label: item.title })
                        })
                        this.type3 = this.xTypeList[0].value
                    } else {
                        this.showStr = false
                    }
                }
            })
        },
        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]]
        },
        getsections () {
            axios.request({
                url: '/config/ProjectUser/getUserDepartment',
                method: 'get'
            }).then(res => {
                this.sectionlist = res.data.data
            })
        },
        getgroups () {
            axios.request({
                url: '/config/WorkingGroup/GetAllWorkGroup?departid=' + this.section,
                method: 'get'
            }).then(res => {
                this.grouplist = res.data.data
            })
        },
        getusers () {
            axios.request({
                url: '/config/ProjectUser/getUserListsBySectionId?sectionid=' + this.section,
                method: 'get'
            }).then(res => {
                this.userlist = res.data.data
            })
        },
        getstates () {
            axios.request({
                url: '/cnc/WorkingState/GetAllState',
                method: 'get'
            }).then(res => {
                this.statelist = res.data.data
            })
        },
        sectionchange () {
            this.getgroups()
            this.getusers()
        },
        search (toexcel) {
            var data = {
                level_id: this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1],
                section_id: this.section,
                user_mid: this.user,
                workgroup_id: this.group,
                state: this.state,
                xtype: this.xtype,
                x_id: this.type3,
                time_range: 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/MachineStateAnalysis',
                    data,
                    method: 'post'
                })
                .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 nameArray = []
                            var valueArray = []
                            res.data.data.forEach(ele => {
                                nameArray.push(ele.key)
                                valueArray.push(Math.round(ele.value / 3600 * 100) / 100)
                            })
                            this.getEcharts(nameArray, valueArray)
                            this.mockTableData1(res.data.data)
                        }
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        key: item.key,
                        value: this.timechange(item.value),
                        id: item.id
                    })
                }
            })
            this.tableData1 = data
        },
        getEcharts (nameArray, valueArray) {
            var main_test = echarts.init(document.getElementById('div_echarts'))
            main_test.setOption({
                xAxis: {
                    data: nameArray
                },
                yAxis: {
                    name: this.$t('950293')
                },
                series: [
                    {
                        name: this.$t('950293'),
                        data: valueArray
                    }
                ]
            })
        },
        baseEcharts () {
            let option_base = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    name: '',
                    top: '10px'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '8%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: [],
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            interval: 0,
                            rotate: -20
                        }
                    }
                ],
                yAxis: [
                    {
                        name: '',
                        nameTextStyle: { fontSize: 18 },
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '',
                        type: 'bar',
                        barMaxWidth: 70,
                        barWidth: '60%',
                        data: []
                    }
                ]
            }
            var main_test = echarts.init(document.getElementById('div_echarts'))
            main_test.clear()
            main_test.setOption(option_base)
        },
        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));
                }
            })
        },
        timechange (num) {
            var str = ''
            if (num > 86400) {
                let d = Math.floor(num / 86400)
                let h = Math.floor((num % 86400) / 3600)
                let m = Math.floor(((num % 86400) % 3600) / 60)
                let s = ((num % 86400) % 3600) % 60
                str = d + this.$t('1101') + h + this.$t('1102') + m + this.$t('1103') + s + this.$t('1104')
                return str
            } else if (num > 3600) {
                let h = Math.floor(num / 3600)
                let m = Math.floor((num % 3600) / 60)
                let s = (num % 24) % 60
                str = h + this.$t('1102') + m + this.$t('1103') + s + this.$t('1104')
                return str
            } else if (num > 60) {
                let m = Math.floor(num / 60)
                let s = Math.floor(num % 60)
                str = '' + m + this.$t('1103') + s + this.$t('1104')
                return str
            } else {
                str = num + this.$t('1104')
                return str
            }
        }
    }
}
</script>
<style lang="less">
    .treeSelect{
      span{
        background:#2D8CF1;
        color:#fff;
        margin: 0;
        padding: 0 4px;
        border-radius: 3px;
        cursor: pointer;
        vertical-align: top;
      }
}
</style>
