<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(900910)}}</label>
        <Select
          v-model="datetype"
          label-in-value
          clearable
           class="searchSelect"
          @on-change="timechange"
        >
          <Option :value="1" id="今天">{{$t("900911")}}</Option>
          <Option :value="2" id="昨天">{{$t("900390")}}</Option>
          <Option :value="3" id="本周">{{$t("900912")}}</Option>
          <Option :value="4" id="上周">{{$t("900913")}}</Option>
          <Option :value="5" id="本月">{{$t("900914")}}</Option>
          <Option :value="6" id="上月">{{$t("900915")}}</Option>
          <Option :value="7" id="本年">{{$t("900916")}}</Option>
          <Option :value="8" id="上年">{{$t("900917")}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('900908')}}：</label>
        <DatePicker
          type="datetimerange"
          :value="dateTime"
          placeholder=""
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>

        <div class="filter">
          <label >{{$t('1129')}}：</label>
          <Select v-model="type1"  class="searchSelect marginR_o" @on-change="xTypechange">
            <Option :value='1' v-text="$t('500065')">{{$t('500065')}}</Option>
            <Option :value='2' v-text="$t('1132')">{{$t('1132')}}</Option>
          </Select>
          <Select v-model="type2" clearable  class="searchSelect" >
            <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 class="echartsId" id="main">
		  </div>
      <Table
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
        @on-selection-change="getSelection" :loading="loading"
        class="echartsTable"
      ></Table>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import axios from '@/libs/api.request';
import echarts from 'echarts'
export default {
    components: {},
    data () {
        return {
            loading: false,
            leveldata: [], // 产线层级集合
            treedata1: [],
            datalevel: [],
            levelid: 0, // 产线层级id
            tableData1: [], // 列表数据
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            type1: 1, // 横坐标类型
            type2: 0, // 具体横坐
            xTypeList: [], // select 集合
            obj: {},
            dateTime: [
                moment(new Date().getTime() - 3600 * 1000 * 24 * 1).format(
                    'YYYY-MM-DD '
                ) + '00:00:00',
                moment(new Date().getTime()).format('YYYY-MM-DD ') + '23:59:59'
            ],
            datetype: 0,
            selection: [],
            tableColumns1: [
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + 1);
                    },
                    width: 80,
                    align: 'center'
                },
                {
                    title: this.$t('8000040'), // 通道/日期
                    key: 'sectionName',
                    align: 'center'
                },
                {
                    title: 'OEE', // oee
                    key: 'oee',
                    align: 'center'
                }
            ]
        };
    },
    created () {

    },
    mounted () {
        this.initlevel()
        this.inidatetype()
        this.search(0)
    },
    methods: {
        timechange () {
            let datetime = this.$time.changetime(this.datetype)
            let dt = datetime.split(' - ')
            this.dateTime = [dt[0], dt[1]]
        },
        inidatetype () { // 初始化横坐标
            this.xTypeList = [{ value: 0, label: this.$t('900864') }, { value: 1, label: this.$t('1136') }, { value: 2, label: this.$t('1138') }, { value: 999, label: this.$t('99200039') }]
        },
        // 横坐标选择
        xTypechange () {
            if (this.type1 === 1) {
                this.xTypeList = [{ value: 0, label: this.$t('900864') }, { value: 1, label: this.$t('1136') }, { value: 2, label: this.$t('1138') }, { value: 999, label: this.$t('99200039') }]
                this.type2 = 0
            } else if (this.type1 === 2) {
                this.getLevels()
            } else {
                this.xTypeList = []
            }
        },
        getLevels () {
            axios.request({
                url: '/config/ProjectLevelSection/GetLevelidsBySection?sectionId=' + this.levelid,
                method: 'get'
            }).then(res => {
                // 产线层级
                if (res.data.ret === 1 && this.type1 === 2) {
                    this.xTypeList = []
                    if (res.data.data.length !== 0) {
                        res.data.data.forEach(item => {
                            this.xTypeList.push({ value: item.id, label: item.title })
                        })
                        this.type2 = this.xTypeList[0].value
                    } else {
                    }
                }
            })
        },
        initechart (x, y) {
            var myChart = echarts.init(document.getElementById('main'));
            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: this.$t(900999),
                    left: '5%',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                color: ['#59A9FA'],
                tooltip: {},
                legend: {
                    data: [this.$t(900999)]
                },
                xAxis: {
                    data: x,
                    axisLabel: {
                        interval: 0, // 坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
                        rotate: 30 // 调整数值改变倾斜的幅度（范围-90到90）
                    }
                },
                yAxis: {},
                series: [{
                    name: this.$t(900999),
                    type: 'bar',
                    data: y,
                    barMaxWidth: 70,
                    itemStyle: {
                        normal: {
                            label: {
                                formatter: function (data) { // 显示格式
                                    return data.value + '%'
                                },
                                show: true, // 开启显示
                                position: 'top', // 在上方显示
                                textStyle: { // 数值样式
                                    color: 'black'
                                    // fontSize: 12
                                }
                            }
                        }
                    }
                }]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        // 产线层级
        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) {
            // if(data.length<=2){
            //   this.$Message.error()
            // }
            this.levelid = data[data.length - 1];
            // this.getLevels();
        },
        getSelection (value) {
            // 监听选择变化
            this.idList = []
            this.selection = value;
            for (let i = 0; i < this.selection.length; i++) {
                this.idList.push(this.selection[i].id);
            }
        },
        selectdate (e) {
            this.dateTime = [e[0], e[1]];
            let dtStart = e[0];
            let dtEnd = e[1];
            let last_str = dtEnd.split(' ')[1]
            if (last_str === '00:00:00') {
                this.dtEnd = moment(dtEnd).format('YYYY-MM-DD') + ' 23:59:59'
                this.dateTime = [dtStart, this.dtEnd]
            }
        },
        search (toexcel) {
            if (this.dateTime === undefined || this.dateTime === '') {
                this.$Message.error(this.$t('800154'));
                return false;
            }
            let date1 = new Date(this.dateTime[0]);
            let date2 = new Date(this.dateTime[1]);

            this.starttime = date1.getTime() / 1000;
            this.endtime = date2.getTime() / 1000;

            let data = {
                section: this.levelid,
                type: this.type1,
                xtype: this.type2,
                start: this.starttime,
                end: this.endtime,
                toexcel: toexcel
            }
            axios
                .request({
                    url: '/tpm/AndonSummary/GetOeeStatistical',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (toexcel === 0) {
                        var xdata = []
                        var ydata = []
                        var listdata = []
                        if (res.data.ret == 1) {
                            xdata = res.data.data.x
                            ydata = res.data.data.y
                            listdata = res.data.data.data
                        }
                        this.initechart(xdata, ydata)
                        this.mockTableData1(listdata)
                    } else {
                        if (res.data.ret === 1) {
                            document.location.href = axios.publicPath + '' + res.data.data;
                        } else {
                            this.$Message.error(this.$t('1000039'));
                        }
                    }
                });
        },
        mockTableData1 (tablelist) {
            let data = [];
            if (tablelist && tablelist.length > 0) {
                tablelist.forEach(item => {
                    if (item) {
                        data.push({
                            sectionName: item.name,
                            oee: item.rate + '%'
                        })
                    }
                })
            }
            this.tableData1 = data;
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.currentObj = currentRow;
        },
        handlePageSize (value) {

        },
        changePage (value) {

        }
    }
};
</script>
<style lang="less" scoped>

</style>
