<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('960418')}}：</label>
        <Cascader
          :data="expectionLevel"
          :value="expectionLeveldata"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="handleExpectionlevelchange"
        ></Cascader>
      </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')">时间单位</Option>
            <Option :value='2' v-text="$t('1132')">产线层级</Option>
            <Option :value='3' v-text="$t('5000011')">异常类别</Option>
            <Option :value='4' v-text="$t('8000022')">责任岗位</Option>
          </Select>
          <Select v-model="type2" 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 class="echartsId" id="production">
		  </div>
     <Table
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
        class="echartsTable"
      ></Table>
    </div>
  </div>
</template>

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

    },
    data () {
        return {
            leveldata: [], // 产线层级集合
            treedata1: [],
            morecondition: false,
            datalevel: [],
            levelid: 0, // 产线层级id
            tableData1: [], // 列表数据
            dateTime: '', // 时间范围
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            type1: 1, // 统计指标select
            type2: 0, // 横坐标select
            xTypeList: [], // select 集合
            showStr: true, // 下拉框显示或隐藏
            expectionLevel: [], // 异常级联框数据
            expectionLeveldata: [], // 异常级联value
            last_expection: 0, // 级联选择选中的最后一个异常
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {},
            factory: '',
            factories: [],
            channel: '',
            channels: [],
            allsections: [],
            table_th_change: '日期',
            myChart: '',
            date1: '',
            // table_header:[],//表头数组
            tableColumns1: [
                {
                    type: 'index2',
                    title: this.$t('1008'), // 序号
                    align: 'center',
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + 1)
                    },
                    width: 80
                },
                {
                    title: this.$t('5000012') + this.$t(101107), // 异常时长
                    align: 'center',
                    key: 'error_hours'
                },
                {
                    title: this.$t('5000013'), // 异常次数
                    align: 'center',
                    key: 'error_count'
                },
                {
                    title: this.$t('5000015'), // 平均响应时长
                    align: 'center',
                    key: 'average_response_hours'
                },
                {
                    title: this.$t('5000016'), // 平均处理时长
                    align: 'center',
                    key: 'average_handle_hours'
                },
                {
                    title: this.$t('5000017'), // 异常占比
                    align: 'center',
                    key: 'error_percent'
                }
            ]
        }
    },
    created () {
        this.inittime()// 初始化
        this.initlevel()
        this.inidatetype()
        this.inisectionIds()
        // this.inionelevel()
        this.search(0)
        this.initexpectionType()
    },
    methods: {
        initexpectionType () {
            this.axios.request({
                url: '/tpm/AndonBaseSetting/GetExpectionTypeTree',
                method: 'get'
            })
                .then(res => {
                    this.expectionLevel = res.data.data
                })
        },
        handleExpectionlevelchange (value, selectedData) {
            this.expectionLeveldata = value
            this.last_expection = value[value.length - 1]
        },
        timechange () {
            var time = this.$time.changetime(this.date1).split(' - ')
            this.dateTime = [time[0], time[1]]
        },
        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())
            this.dateTime = [start, end]
        },
        selectdate (e) {
            this.dateTime = [e[0], e[1]]
        },
        // 产线层级
        initlevel () {
            axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    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]
            this.leveldata = data
            this.getLevels()
        },
        // 横坐标选择
        xTypechange () {
            this.showStr = true
            if (this.type1 === 1) {
                this.xTypeList = [{ value: 0, label: this.$t('900864') }, { value: 1, label: this.$t('1136') }, { value: 2, label: this.$t('1138') }]
                this.type2 = 0
            } else if (this.type1 === 2) {
                this.getLevels()
            } else {
                this.showStr = false
                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 {
                        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.type1 === 1 || this.type1 === 2) {
                if (this.type2 === undefined || this.type2 === '') {
                    this.$Message.error(this.$t('500133'))
                    return false
                }
            }
            var data = {
                dateTime: moment(this.dateTime[0]).format('YYYY-MM-DD') + ' - ' + moment(this.dateTime[1]).format('YYYY-MM-DD'),
                type: this.type1,
                typeValue: this.type2,
                sectionId: this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1],
                expection: this.last_expection,
                toexcel: toexcel
            }
            axios.request({
                url: '/tpm/AndonSummary/GetErrorSummary',
                data,
                method: 'post'
            }).then(res => {
                if (toexcel === 0) {
                    //  this.table_header=[]
                    if (res.data.ret === 1) {
                        this.getALLData(res.data.data)
                        var obj = {
                            title: this.$t(600532), // 横坐标
                            key: 'title',
                            align: 'center'
                        }
                        if (this.type1 === 1) {

                        } else if (this.type1 === 2) {
                            obj.title = this.$t(1132)
                        } else if (this.type1 === 3) {
                            obj.title = this.$t(930011)
                        } else {
                            obj.title = this.$t(8000022)
                        }
                        if (this.tableColumns1.length === 6) {
                            this.tableColumns1.splice(1, 0, obj)
                        } else {
                            this.tableColumns1.splice(1, 1, obj)
                        }
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                } else {
                    if (res.data.ret === 1) {
                        document.location.href = axios.publicPath + '' + res.data.data
                    } else {
                        this.$Message.error(this.$t('1000039'))
                    }
                }
            })
        },
        getALLData (allData) {
            // 时间周期
            if (this.type1 === 1) { // 时间周期
                this.table_th_change = 0
                this.pareto1(allData)
            } else if (this.type1 === 2) { // 产线层级
                this.table_th_change = 1
                this.pareto(allData)
            } else if (this.type1 === 3) { // 异常类别
                this.table_th_change = 1
                this.pareto(allData)
            } else if (this.type1 === 4) { // 责任部门
                this.table_th_change = 1
                this.pareto(allData)
            }
            if (allData && allData.table.length > 0) {
                this.mockTableData1(allData.table)
            }
        },
        pareto (res) {
            if (this.myChart !== null && this.myChart !== '' && this.myChart !== undefined) {
                this.myChart.dispose()
            }

            var sumdata = []
            for (var i = 0; i < res.dataYList[0].length; i++) {
                sumdata.push(res.dataYList[0][i] + res.dataYList[1][i])
            }
            var datainterval = Math.ceil(Math.max(...res.dataY2) / 5)
            var datainterval2 = Math.ceil(res.max / 5)
            var Ydatamax = Math.ceil(res.max / 5) * 5
            var legend = [this.$t('5000016'), this.$t('5000015')]
            this.myChart = echarts.init(document.getElementById('production'))
            var option = {
                color: ['#393D49', '#3574ad', '#f0ad4e'],
                title: {
                    text: '',
                    left: 'center',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b0}<br />{a0}: {c0}%<br />{a1}: {c1} ' + this.$t(200028) + '<br />{a2}: {c2} ' + this.$t(200028),
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    data: [this.$t('5000016'), this.$t('5000015'), this.$t(950016)],
                    x: 'center'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: res.dataX,
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        name: this.$t('5000012') + this.$t(101107), // 异常时长
                        type: 'value',
                        data: res.dataYList,
                        max: Ydatamax,
                        interval: datainterval2,
                        // interval:datainterval2,
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: this.$t(950016),
                        interval: datainterval,
                        axisLabel: {
                            formatter: '{value}%'
                        }
                    }
                ],
                series: [
                    {
                        name: this.$t(950016),
                        type: 'line',
                        yAxisIndex: 1,
                        data: res.dataY2,
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: '{c}%',
                                color: 'black'
                            }
                        }
                    },
                    {
                        name: this.$t('5000016'),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: '总量',
                        label: {
                            normal: {
                                show: false,
                                position: 'top'
                            }
                        },
                        data: res.dataYList[0]
                    },
                    {
                        name: this.$t('5000015'),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: '总量',
                        label: {
                            normal: {
                                show: false,
                                position: 'top'
                            }
                        },
                        data: res.dataYList[1]
                    },
                    {
                        name: this.$t(930010),
                        type: 'line',
                        lineStyle: {
                            opacity: 0
                        },
                        label: {
                            normal: {
                                show: false,
                                position: 'top',
                                color: 'black'
                            }
                        },
                        data: sumdata
                    }
                ]
            }
            if (res.dataYList instanceof Array && res.dataYList.length > 0) {
                // res.dataYList.forEach((data, index) => {
                //   option.series.push({
                //     name: legend[index],
                //     type: 'bar',
                //     stack: '总量',
                //     label: {
                //       show: true,
                //       position: 'insideTop'
                //     },
                //     data: data
                //   })
                // })
                this.myChart.clear()
                this.myChart.setOption(option)
            } else {
                this.myChart.clear()
            }
            // this.myChart.setOption(option)
        },
        pareto1 (res) { // 时间周期
            if (this.myChart !== null && this.myChart !== '' && this.myChart !== undefined) {
                this.myChart.dispose()
            }
            // let res = {
            //   data: {
            //     data: {
            //       // legend: ['响应用时', '签到用时', '维修用时', '复现用时'],
            //       dataY: ['维修C组白班', '维修C组夜班', '工程机械小组', '维修B组夜班', '维修B组白班', '维修A组夜班', '维修A组白班'],
            //       dataXList: [
            //         [320, 302, 301, 334, 390, 330, 320],
            //         [120, 132, 101, 134, 90, 230, 210]
            //       ],
            //     },
            //     ret: 1,
            //     msg: ''
            //   }
            // }
            var sumdata = []
            for (var i = 0; i < res.dataYList[0].length; i++) {
                sumdata.push(res.dataYList[0][i] + res.dataYList[1][i])
            }
            var legend = [this.$t('5000016'), this.$t('5000015')]
            this.myChart = echarts.init(document.getElementById('production'))
            var option = {
                color: ['#f0ad4e', '#3574ad'],
                title: {
                    text: '',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: '{b0}<br />{a0}: {c0} ' + this.$t(200028) + '<br />{a1}: {c1} ' + this.$t(200028) + '<br />{a2}: {c2} ' + this.$t(200028)
                },
                legend: {
                    data: [this.$t('5000016'), this.$t('5000015')],
                    x: 'center'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: res.dataX,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            interval: 0,
                            rotate: 40
                        }
                    }
                ],
                yAxis: [
                    {
                        name: this.$t('5000012') + this.$t(101107),
                        type: 'value',
                        data: res.dataYList,
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                series: [
                    {
                        name: this.$t('5000016'),
                        type: 'bar',
                        stack: '总量',
                        label: {
                            normal: {
                                // show: false,
                                // position: 'top'
                            }
                        },
                        data: res.dataYList[0]
                    },
                    {
                        name: this.$t('5000015'),
                        type: 'bar',
                        stack: '总量',
                        label: {
                            normal: {
                                show: false,
                                position: 'top'
                            }
                        },
                        data: res.dataYList[1]
                    },
                    {
                        name: this.$t(930010),
                        type: 'line',
                        lineStyle: {
                            opacity: 0
                        },
                        label: {
                            normal: {
                                show: false,
                                position: 'top',
                                color: 'black'
                            }
                        },
                        data: sumdata
                    }
                ]
            }
            if (res.dataYList instanceof Array && res.dataYList.length > 0) {
                this.myChart.clear()
                this.myChart.setOption(option)
            } else {
                this.myChart.clear()
            }
            // this.myChart.setOption(option)
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        title: item.title,
                        error_hours: Math.floor(item.error_hours / 60) + this.$t(200028),
                        error_count: item.error_count,
                        average_response_hours: Math.floor(item.average_response_hours / 60) + this.$t(200028),
                        average_handle_hours: Math.floor(item.average_handle_hours / 60) + this.$t(200028),
                        error_percent: item.error_percent + '%'
                    })
                }
            })
            this.tableData1 = data
        }
    }
}
</script>
<style lang="less" scoped>

</style>
