<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="datetimerange" :value="datetime" placeholder="" class="searchInput MaxWidth" @on-change="selectdate"></DatePicker>
      </div>
      <div class="filter">
          <label >{{$t('900853')}}</label>
          <Select v-model="machinestate" clearable class="searchSelect">
            <Option :value='0' >{{$t('1014')}}</Option>
             <Option :value='1' >{{$t('500054')}}</Option>
             <Option :value='2' >{{$t('500055')}}</Option>
             <Option :value='3' >{{$t('500049')}}</Option>
          </Select>
      </div>
      <div class="filter">
          <label >{{$t('900854')}}</label>
         <Select v-model="bigsmallspan" clearable class="searchSelect minWidth" style="margin-right:10px;">
            <Option :value='1' >{{$t('200026')}}</Option>
            <Option :value='2' >{{$t('200027')}}</Option>
          </Select>
           <Input class="searchInput minWidth" type="number" v-model="timespan" /><span>{{this.$t('1104')}}</span>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord intervalRight" icon="ios-search" @click="tosearch(0)">{{$t('1001')}}</Button>
        <Button type="primary" class="fourWord" icon="md-close-circle"  @click="clear()">{{$t('1039')}}</Button>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="tosearch(1)">{{$t('1007')}}</Button>
      </div>
    </div>
     <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1">
        <template slot-scope="{row, index}" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="show(index)">{{$t('900312')}}</Button>
        </template></Table>

        <!-- <Modal title="查看" v-model="viewobj" :styles="{top: '40px',width:'800px'}">
            <div class="modal_body" style="width:800px!important;padding:0 20px;height:400px!important;">
                <div class="filter">
                    <label>{{$t('900855')}}</label>
                    <label style="text-align: left">{{location}}</label>
                </div>
                <div class="filter">
                    <label>{{$t('500079')}}：</label>
                    <label style="text-align: left">{{errortype}}</label>
                </div>
                <div class="filter">
                    <label>{{$t('900857')}}</label>
                    <label style="text-align: left">{{duration}}</label>
                </div>
                <div class="filter">
                    <label>{{$t('1035')}}</label>
                    <label style="width:400px;text-align: left">{{timerange}}</label>
                </div>
                <div id="main" style="width:100%;height:300px;">
                 </div>
            </div>
            <div slot="footer">
            <Button type="primary" size="large" @click="viewdata()">{{$t('1028')}}</Button>
        </div>
      </Modal> -->

    <div class="pageDiv">
      <div class="pageDirection">
        <Page
          :total="total"
          :current="page"
          @on-change="changePage"
          show-elevator
          show-sizer
          show-total
          @on-page-size-change="handlePageSize"
          :page-size-opts="[10,20,30,40,100]"
        ></Page>
      </div>
    </div>
  </div>
  </div>
</template>

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

    },
    data () {
        return {
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            tableData1: [], // 列表数据
            datetime: '', // 时间范围
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            machinestate: '0',
            bigsmallspan: 1,
            page: 1,
            pagesize: 10,
            total: 0,
            datalevel: [],
            timespan: '',
            detailobj: {},
            viewobj: false,
            location: '',
            errortype: '',
            timerange: '',
            duration: '',
            tableColumns1: [
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + (this.page - 1) * this.pagesize + 1)
                    },
                    width: '160px'
                },
                {
                    title: this.$t('200003'),
                    key: 'stas'
                },
                {
                    title: this.$t('500084'),
                    key: 'exception_type',
                    width: '300px'
                },
                {
                    title: this.$t('1049'),
                    key: 'start_time'
                },
                {
                    title: this.$t('1050'),
                    key: 'end_time'
                },
                {
                    title: this.$t('500086'),
                    key: 'time_span'
                }
            ],
            excel:0, //是否导出
        }
    },
    created () {
        this.inittime()// 初始化
        this.initlevel()
        this.tosearch(0)
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
        inittime () {
            // 时间赋值
            var date = new Date()
            this.datetime = [moment(date.getTime()).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]];
            let dtStart = e[0];
            let dtEnd = e[1];
            let last_str = dtEnd.split(' ')[1];
            if (last_str == '00:00:00') {
                dtEnd = moment(dtEnd).format('YYYY-MM-DD') + ' 23:59:59';
                this.datetime = [dtStart, dtEnd];
            }
        },
        // 产线层级
        initlevel () {
            axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                const arr = []
                this.datalevel = res.data.data
                let sdata = res.data.data
                if(sdata!=null&&sdata!=undefined&&sdata&&sdata.length >0){
                    arr.push(res.data.data[0].value)
                    this.levelid = res.data.data[0].value;
                }
                this.leveldata = arr
                this.tosearch()
            })
        },
        // 产线层级选择
        getlevel: function (data) {
            this.levelid = data[data.length - 1]
        },
        tosearch (excel) {
            this.excel = excel
            this.page = 1
            this.pagesize = 10
            this.search()
        },
        search () {
            if (this.datetime === undefined || this.datetime === '') {
                this.$Message.error(this.$t('800154'))
                return false
            }
            var data = {
                big_small: this.bigsmallspan,
                big_small_span: this.timespan,
                errtype: this.machinestate,
                sectionID: !this.levelid ? 0 : this.levelid, // this.leveldata[this.leveldata.length - 1],
                startTime: moment(this.datetime[0]).format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(this.datetime[1]).format('YYYY-MM-DD HH:mm:ss'),
                page: this.page,
                pagesize: this.pagesize,
                toexcel:this.excel
            }

            axios.request({
                url: '/cnc/MachineAlarm/getAbnormalList',
                data,
                method: 'post'
            })
                .then(res => {
                    if(this.excel === 1){
                        document.location.href = axios.publicPath + "" + res.data.data;
                        return false;
                    }
                    this.total = 0
                    this.tableData1 = []
                    if (res.data.ret === 1 && res.data.data.length > 0) {
                        this.total = res.data.total
                        this.mockTableData1(res.data.data)
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        time_span: this.timechange(item.time_span),
                        stas: item.stas,
                        machineID: item.machineID,
                        exception: item.exception_type,
                        exception_type: this.formatstate(item.exception_type),
                        sectionID: item.sectionID,
                        id: item.id,
                        start_time: this.$time.timestampToTimeSpan(item.start_time),
                        end_time: this.$time.timestampToTimeSpan(item.end_time),
                        uplimit: item.uplimit,
                        downlimit: item.downlimit
                    })
                }
            })
            this.tableData1 = data
        },
        show (index) {
            this.viewobj = true
            this.location = this.tableData1[index].stas
            this.errortype = this.tableData1[index].exception_type
            this.timerange = this.tableData1[index].start_time + ' - ' + this.tableData1[index].end_time
            this.duration = this.tableData1[index].time_span
            var data = {
                machineID: this.tableData1[index].machineID,
                type: this.tableData1[index].exception,
                spindle: 1,
                stime: this.$time.datestrtotime(this.tableData1[index].start_time),
                etime: this.$time.datestrtotime(this.tableData1[index].end_time),
                uplimit: this.tableData1[index].uplimit,
                downlimit: this.tableData1[index].downlimit
            }
            axios.request({
                url: '/cnc/MachineAlarm/getLook',
                data,
                method: 'post'
            })
                .then(res => {
                    if (res.data.ret === 1) {
                        var xName = res.data.xName
                        var yData3 = res.data.yData3
                        var yData1 = []
                        var yData2 = []
                        xName.forEach(ele => {
                            yData1.push(res.yData1)
                            yData2.push(res.yData2)
                        })
                        this.look(xName, yData1, yData2, yData3)
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        formatstate (exception_type) {
            if (exception_type === 1) {
                return this.$t('500054')
            } else if (exception_type === 2) {
                return this.$t('500055')
            } else if (exception_type === 3) {
                return this.$t('500049')
            } else {
                return exception_type
            }
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        handlePageSize (value) {
            this.pagesize = value
            this.tableData1 = this.search()
        },
        changePage (value) {
            this.page = value
            this.tableData1 = this.search()
        },
        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
            }
        },
        clear () {
            this.inittime()
            this.initlevel()
            this.machinestate = '0'
            this.bigsmallspan = '1'
            this.timespan = ''
            this.page = 1
            this.pagesize = 10
            this.search()
        },
        viewdata () {
            this.viewobj = false
        },
        look (xName, yData1, yData2, yData3) {
            var myChart = echarts.init(document.getElementById('main'))
            myChart.setOption({
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: [this.$t('200060'), this.$t('200059'), this.$t('500087')]
                },
                grid: {
                    left: '3%',
                    right: '6%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xName
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: this.$t('200060'),
                        type: 'line',
                        data: yData1
                    },
                    {
                        name: this.$t('200059'),
                        type: 'line',
                        data: yData2
                    },
                    {
                        name: this.$t('500087'),
                        type: 'line',
                        data: yData3
                    }
                ]
            })
        }
    }
}
</script>
<style lang="less" scoped>
.echart-div-list {
        margin-top: 15px;
        border: 0px solid #ddd;
        padding: 15px;
    }
 .modal_body label {
  width: 100px;
  display: inline-block;
  text-align: left;
}
</style>
