<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
          <label >{{$t('1132')}}：</label>
          <Cascader :data="datalevel" :value="leveldata" trigger="click" change-on-select class="searchSelect" @on-change="getlevel"></Cascader>
      </div>
      <div class="filter">
          <label >{{$t('900908')}}：</label>
          <DatePicker type="daterange" :value="dateTime" placeholder="" class="searchInput middleWidth" @on-change="selectdate"></DatePicker>
      </div>
      <div class="filter">
          <label>{{$t(900675)}}</label>
          <Select v-model="type2" class="searchSelect" @on-change="xTypechange" style="margin-right:10px;">
            <Option value='time' v-text="$t('500122')">时间周期</Option>
            <Option value='machine' v-text="$t('500132')">产线区域</Option>
          </Select>
          <Select v-model="type3" clearable class="searchSelect" v-show="showStr">
            <Option v-for="(item,key) in xTypeList" :value="item.value" :key="key">{{ item.label }}</Option>
          </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord intervalRight" icon="ios-search" @click="search(0)">{{$t('1001')}}</Button>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="search(1)">{{$t('1007')}}</Button>
      </div>
    </div>
    <div class="divborder newEchartStyle">
      <div id="main" class="echartsId"> </div>
      <Table
        class="echartsTable"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        @on-selection-change="handleSelectRow"
        :columns="tableColumns1"></Table>
    </div>
  </div>
</template>

<script>
// import echarts from 'echarts'
import axios from '@/libs/api.request'
import echarts from 'echarts'
export default {
    components: {

    },
    data () {
        return {
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            tableData1: [], // 列表数据
            dateTime: '', // 时间范围
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            type1: '0', // 统计指标select
            type2: 'time', // 横坐标select
            type3: 0, // 横坐标子select
            xTypeList: [], // select 集合
            showStr: true, // 下拉框显示或隐藏
            toexcel: 0,
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {},
            treedata1: [],
            datalevel: [],
            myChart: '',
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + 1
                        )
                    },
                    width: '60px'
                },
                {
                    title: this.$t(300080),
                    key: 'name'
                },
                {
                    title: 'OEE1',
                    key: 'OEE1'
                },
                {
                    title: 'OEE2',
                    key: 'OEE2'
                },
                {
                    title: 'OEE3',
                    key: 'OEE3'
                },
                {
                    title: 'OEE',
                    key: 'OEE'
                }
            ]
        }
    },
    created () {
        this.inittime()// 初始化
        this.initlevel()
        this.inidatetype()
        this.search(0)
    },
    methods: {
        inidatetype () {
            this.xTypeList = [{ value: 0, label: this.$t(900864) }, { value: 1, label: this.$t(1136) }, { value: 2, label: this.$t(1138) }]
        },
        inittime () {
            // 时间赋值
            var date = new Date()
            var start = this.$time.timestampToTime(date.getTime() - 3600 * 1000 * 24 * 30)
            var end = this.$time.timestampToTime(date.getTime() - 3600 * 1000 * 24)
            this.dateTime = [start, end]
        },
        selectdate (e) {
            this.dateTime = [e[0], e[1]]
        },
        // 产线层级
        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.leveldata = data
            this.getLevels()
        },
        // 横坐标选择
        xTypechange () {
            this.showStr = true
            if (this.type2 === 'time') {
                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.type2 === 'machine') {
                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.type2 === 'machine') {
                    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
                    }
                }
            })
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        handleSelectRow: function (data) {
            var ids = []
            for (var i in data) {
                ids.push(data[i].id)
            }
            this.selectids = ids
        },
        search (toexcel) {
            this.toexcel = toexcel
            var sectionId = this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1]
            axios.request({
                url: '/config/UserLevel/listNCMachineIDArr?id=' + sectionId,
                method: 'get'
            }).then(res => {
                var machineids = res.data.data
                if (machineids.length > 0) {
                    this.getecharts(machineids)
                } else {
                    this.$Message.error('无法获取设备信息')
                }
            })
        },
        getecharts (machineids) {
            let data = {
                starttime: this.dateTime[0],
                endtime: this.dateTime[1],
                machineidarr: machineids,
                x_id: this.type3,
                level_id: this.type2 === 'time' ? 0 : this.type3,
                x_type: this.type2,
                sectionID: this.leveldata[this.leveldata.length - 1],
                toexcel: this.toexcel
            }

            axios.request({
                url: '/cnc/ProductSum/Getoee',
                data,
                method: 'post'
            }).then(res => {
                if (this.toexcel) {
                    if (res.data.ret == 1) {
                        document.location.href = axios.publicPath + '' + res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                } else {
                    if (res.data.ret == 1) {
                        var data = res.data.data;
                        for (var i = 0; i < Object.keys(data.y).length; i++) {
                            if (data.y[i]['OEE1'] < 0) {
                                data.y[i]['OEE1'] = 0;
                            }
                            if (data.y[i]['OEE2'] < 0) {
                                data.y[i]['OEE2'] = 0;
                            }
                            if (data.y[i]['OEE3'] < 0) {
                                data.y[i]['OEE3'] = 0;
                            }
                            if (data.y[i]['oee'] < 0) {
                                data.y[i]['oee'] = 0;
                            }
                        }
                        var len = data.y[0];
                        if (len != undefined && len.hasOwnProperty('OEE1')) {
                            // 有OEE1-3的情况
                            this.goechares(data);
                            this.appendTr(data);
                        } else {
                            // 没有OEE1-3的情况
                            this.goechares1(data);
                            this.appendTr1(data);
                        }
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                }
            })
        },
        appendTr1 (data) {
            let name = this.type2 === 'time' ? '时间范围' : '产线层级'
            this.tableColumns1 = [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + 1
                        )
                    },
                    width: '60px'
                },
                {
                    title: name,
                    key: 'name'
                },
                {
                    title: 'OEE',
                    key: 'OEE'
                }
            ]
            var x = data.x;
            var arr = []
            for (var i = 0; i < Object.keys(data.y).length; i++) {
                if (data.y[i]['oee'] === undefined) {
                    data.y[i]['oee'] = 'N/A';
                }
                arr.push({
                    name: x[i],
                    OEE: data.y[i]['oee']
                })
            }
            this.tableData1 = arr
        },
        goechares1 (obj) {
            var xAxis = obj.x;
            var OEE = new Array();
            var OEE1 = new Array();
            var OEE2 = new Array();
            var OEE3 = new Array();

            for (var i = 0; i < Object.keys(obj.y).length; i++) {
                OEE[i] = obj.y[i]['oee'];
            }

            var myChart1 = echarts.init(document.getElementById('main'))
            var	option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xAxis,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            show: true,
                            // textStyle: {
                            //     color: '#fff',
                            //     fontSize:'25'
                            // },
                            interval: 0,
                            rotate: 30
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '%'
                    }
                ],
                series: [
                    {
                        name: 'OEE',
                        type: 'bar',
                        barMaxWidth: 70,
                        data: OEE

                    }
                ]
            };
            myChart1.setOption(option)
        },
        appendTr (data) {
            let name = this.type2 === 'time' ? '时间范围' : '产线层级'
            this.tableColumns1 = [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + 1
                        )
                    },
                    width: '60px'
                },
                {
                    title: name,
                    key: 'name'
                },
                {
                    title: 'OEE1',
                    key: 'OEE1'
                },
                {
                    title: 'OEE2',
                    key: 'OEE2'
                },
                {
                    title: 'OEE3',
                    key: 'OEE3'
                },
                {
                    title: 'OEE',
                    key: 'OEE'
                }
            ]
            var x = data.x;
            var arr = []
            for (var i = 0; i < Object.keys(data.y).length; i++) {
                if (data.y[i]['OEE1'] === undefined) {
                    data.y[i]['OEE1'] = 'N/A';
                }
                if (data.y[i]['OEE2'] === undefined) {
                    data.y[i]['OEE2'] = 'N/A';
                }
                if (data.y[i]['OEE3'] === undefined) {
                    data.y[i]['OEE3'] = 'N/A';
                }
                if (data.y[i]['oee'] === undefined) {
                    data.y[i]['oee'] = 'N/A';
                }
                arr.push({
                    name: x[i],
                    OEE1: data.y[i]['OEE1'],
                    OEE2: data.y[i]['OEE2'],
                    OEE3: data.y[i]['OEE3'],
                    OEE: data.y[i]['oee']
                })
            }
            this.tableData1 = arr
        },
        goechares (obj) {
            var xAxis = obj.x;
            var OEE1 = new Array();
            var OEE2 = new Array();
            var OEE3 = new Array();
            var OEE = new Array();
            obj.y.forEach((ele, i) => {
                OEE1[i] = ele.OEE1;
                OEE2[i] = ele.OEE2;
                OEE3[i] = ele.OEE3;
                OEE[i] = ele.OEE;
            })
            var myChart1 = echarts.init(document.getElementById('main'))
            var option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                toolbox: {
                    feature: {
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['bar'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                legend: {
                    data: ['OEE1', 'OEE2', 'OEE3', 'OEE']
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xAxis,
                        axisPointer: {
                            type: 'shadow'
                        },
                        axisLabel: {
                            show: true,
                            // textStyle: {
                            //     color: '#fff',
                            //     fontSize:'25'
                            // },
                            interval: 0,
                            rotate: 30
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '',
                        axisLabel: {
                            formatter: '{value} %'
                        }
                    }

                ],
                series: [
                    {
                        name: 'OEE1',
                        type: 'bar',
                        barMaxWidth: 70,
                        data: OEE1
                    },
                    {
                        name: 'OEE2',
                        type: 'bar',
                        barMaxWidth: 70,
                        data: OEE2
                    },
                    {
                        name: 'OEE3',
                        type: 'bar',
                        barMaxWidth: 70,
                        data: OEE3
                    },
                    {
                        name: 'OEE',
                        type: 'bar',
                        barMaxWidth: 70,
                        data: OEE
                    }
                ]
            };

            myChart1.setOption(option)
        }
    }
}
</script>
<style lang="less">

</style>
