<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('900853')}}</label>
          <Select v-model="errType" clearable class="searchSelect">
             <Option :value='1' v-text="$t('500054')">{{$t('500054')}}</Option>
             <Option :value='2' v-text="$t('500055')">{{$t('500055')}}</Option>
             <Option :value='3' v-text="$t('500049')">{{$t('500049')}}</Option>
          </Select>
      </div>
      <div class="filter">
          <label>{{$t('900674')}}</label>
          <Select v-model="ytype" class="searchSelect" @on-change="xTypechange">
            <Option :value='0' v-text="$t('500089')">{{$t('500089')}}</Option>
            <Option :value='1' v-text="$t('500085')">{{$t('500085')}}</Option>
          </Select>
      </div>
      <div v-show="!morecondition">
      <div class="filter">
          <label>{{$t('1129')}}：</label>
          <Select v-model="xtype" class="searchSelect" @on-change="xTypechange" style="margin-right:10px;">
            <Option :value='0' v-text="$t('500065')">时间单位</Option>
            <Option :value='1' v-text="$t('1132')">产线层级</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>
      <div class="searchBtn">
        <Button type="primary" class="twoWord intervalRight" icon="ios-search" @click="search(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="search(1)">{{$t('1007')}}</Button>
      </div>
      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <div class="divborder newEchartStyle">
        <div class="echartsId" id="example"></div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import echarts from 'echarts'
import axios from '@/libs/api.request'
export default {
    inject: ['reload'], // 接受App那边提供的方法
    components: {

    },
    data () {
        return {
            morecondition: false, // 条件
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            dateTime: '', // 时间范围
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            errType: '', // 统计指标select
            ytype: 0, // 横坐标select
            xtype: 0,
            type3: 0, // 横坐标子select
            xTypeList: [], // select 集合
            showStr: true, // 下拉框显示或隐藏
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {},
            treedata1: [],
            datalevel: [],
            sectionIdStr: '',
            allsections: [],
            myChart: ''
        }
    },
    created () {
        this.inittime()// 初始化
        this.initlevel()
        this.inidatetype()
        // this.search(0)
    },
    methods: {
        inidatetype () {
            this.xTypeList = [{ value: 0, label: '日' }, { value: 1, label: '周' }, { value: 2, label: '月' }]
        },
        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
                let sdata = res.data.data
                if(sdata!=null&&sdata!=undefined&&sdata&&sdata.length >0){
                    this.levelid = res.data.data[0].value;
                    arr.push(res.data.data[0].value);
                }
                this.leveldata = arr
                this.search(0)
            })
        },
        // 产线层级选择
        getlevel: function (data) {
            this.levelid = data[data.length - 1]
            this.getLevels()
        },
        // 横坐标选择
        xTypechange () {
            this.showStr = true
            if (this.xtype === 0) {
                this.xTypeList = [{ value: 0, label: '日' }, { value: 1, label: '周' }, { value: 2, label: '月' }]
                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 (this.xtype === 0) {
                    this.xTypeList = [{ value: 0, label: '日' }, { value: 1, label: '周' }, { value: 2, label: '月' }]
                    this.type3 = 0
                }
                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
                    }
                }
            })
        },
        inisectionIds () {
            axios.request({
                url: '/config/ProjectLevelSection/GetSectionSelect?reverselevel=1',
                method: 'get'
            }).then(res => {
                // 产线层级
                if (res.data.ret === 1) {
                    if (res.data.data.length !== 0) {
                        res.data.data.forEach(item => {
                            this.allsections.push({ id: item.id, name: item.name })
                        })
                    }
                }
            })
        },
        search (toexcel) {
            if (this.dateTime === undefined || this.dateTime === '') {
                this.$Message.error(this.$t('800154'))
                return false
            }
            if (this.type3 === undefined || this.type3 === '') {
                this.$Message.error(this.$t('500133'))
                return false
            }

            var data = {
                startTime: moment(this.dateTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(this.dateTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                xID: this.xtype,
                yID: this.ytype,
                errType: this.errType,
                patchID: this.type3,
                sectionId: !this.levelid ? 0 : this.levelid, // this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1],
                toexcel: toexcel
            }
            axios.request({
                url: '/cnc/MachineAlarm/listExceptionTimesByDay',
                data,
                method: 'post'
            }).then(res => {
                if (toexcel === 0) {
                    let xName = []
                    let sData = []
                    let abscissa = [] // 横轴
                    let indicators = []
                    let Ytype

                    for( var item in res.data.yData){
                         if (this.ytype === 0) {
                            sData.push((res.data.yData[item] ? (res.data.yData[item]) : 0))
                            Ytype = this.$t('200163')
                        } else {
                            sData.push((res.data.yData[item] ? (res.data.yData[item] / 60).toFixed(2) : 0))
                            Ytype = this.$t('1102')
                        }
                    }
                    
                    res.data.xData.forEach(ele => {
                        xName.push(ele)
                        if (this.ytype === 0) {
                            Ytype = this.$t('200163')
                        } else {
                            Ytype = this.$t('1102')  
                        }
                    })

                    if (this.xtype === 0) {
                        abscissa.push(this.$t('1046'))/* 时间 */
                    } else if (this.xtype === 1) {
                        abscissa.push(this.$t('1132'))/* 产线层级 */
                    }
                    if (this.ytype === 0) {
                        indicators.push(this.$t('500089'))/* 参数异常次数 */
                    } else {
                        indicators.push(this.$t('500085'))/* 参数异常时长 */
                    }
                    this.echartBar(xName, sData, Ytype, abscissa, indicators)
                } else {
                    document.location.href = axios.publicPath + '' + res.data.data
                }
            })
        },
        echartBar (xname, sData, ytype, abscissa, indicators) {
            this.myChart = echarts.init(document.getElementById('example'))
            var option = {
                title: {
                    show: true,
                    text: this.$t('900225'),
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{a} <br/>{b} : {c}',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    data: indicators
                },
                grid: {
                    x: 100,
                    left: '3%',
                    right: '6%',
                    bottom: '12%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        name: abscissa,
                        data: xname,
                        axisLabel: {
                            // interval: 0,
                            rotate: 35
                        },
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        name: ytype,
                        type: 'value',
                        data: ''
                    },
                    {
                        name: '',
                        // type: "value",
                        axisLabel: {
                            interval: 'auto'
                            // formatter: '{value}%'
                        }
                    }
                ],
                series: [
                    {
                        name: indicators[0],
                        type: 'bar',
                        barMaxWidth: 70,
                        // barWidth: '60%',
                        // barGap:"30%",
                        data: sData,
                        itemStyle: {
                            normal: {
                                color: '#4F81BD'
                            }
                        }
                    },
                    {
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    fontWeight: 'bold',
                                    color: '#000000'
                                },
                                lineStyle: {
                                    width: 4
                                }
                            }
                        },
                        symbolSize: 8, // 折线点的大小
                        name: indicators[0],
                        type: 'line',
                        barWidth: '30%',
                        data: sData
                    }
                ]
            }

            this.myChart.setOption(option)
        },
        clear () {
            this.inittime()
            this.initlevel()
            this.errType = '0'
            this.ytype = 0
            this.xtype = 0
            this.type3 = 0
            this.inidatetype()
            this.search(0)
            this.reload()
        }
    }
}
</script>
<style lang="less" scoped>
.echart-div-list {
        margin-top: 15px;
        border: 0px solid #ddd;
        padding: 15px;
    }
</style>
