<template>
  <div class="testdiv">
    <div class="divborder" style="margin:0px;">
        <div class="filter">
          <label >{{$t('1132')}}：</label>
          <Cascader :data="datalevel" :value="leveldata" trigger="click" change-on-select style="display:inline-block;width:200px;" @on-change="getlevel"></Cascader>
      </div>
         <div class="filter">
         <label >{{$t('900908')}}:</label>
         <DatePicker type="daterange" :value="dateTime" placeholder="Select date" style="width: 300px;"  @on-change="selectdate"></DatePicker>
        </div>
         <div class="filter">
          <label>{{$t(9900087)}}：</label>
          <Select v-model="xtype" style="width:120px;" @on-change="xTypechange">
            <Option :value='1' v-text="$t('100307')">产品</Option>
            <Option :value='2' v-text="$t('100046')">人员</Option>
          </Select>
          <Select v-model="type3" clearable style="width:120px;margin-left:10px;" v-show="vtype1show">
            <Option v-for="(item,key) in productList" :value="item.id" :key="key">{{ item.name }}</Option>
          </Select>
          <Select v-model="type3" clearable style="width:120px;margin-left:10px;" v-show="vtype2show">
            <Option v-for="(item,key) in userList" :value="item.id" :key="key">{{ item.name + "-》" + item.work_code }}</Option>
          </Select>
      </div>
          <Button type="primary" style="margin:0 10px" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
    </div>
     <div id="echarts_div" style="width:100%;height:400px;"></div>
    <div class="divborder">
      <Table
        style="margin-top:10px"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        @on-selection-change="handleSelectRow"
        :columns="tableColumns1"></Table>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import axios from '@/libs/api.request'
export default {
    name: 'producetime', // 组件不刷新
    data () {
        return {
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            datalevel: [],
            tableData1: [],
            detailobj: {},
            treeContents: [],
            group: 0,
            grouplist: [],
            user: 0,
            userlist: [],
            dateTime: '',
            xtype: 1,
            productList: [],
            type3: '',
            userList: [],
            vtype1show: true,
            vtype2show: false,
            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: this.$t(200233),
                    key: 'number'
                },
                {
                    title: this.$t(200234),
                    key: 'average'
                },
                {
                    title: this.$t(200235),
                    key: 'short'
                },
                {
                    title: this.$t(200236),
                    key: 'long'
                }
            ]
        }
    },
    created () {
        this.initlevel()
        this.inittime()
        this.getProducts()
        this.search()
    },
    methods: {
    // 产线层级
        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.levelid = data[data.length - 1]
        },
        inittime () {
            // 时间赋值
            var date = new Date()
            this.dateTime = [moment(date.getTime() - 3600 * 1000 * 24 * 15).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]]
        },
        xTypechange () {
            if (this.xtype === 1) {
                this.vtype1show = true
                this.vtype2show = false
                this.getProducts()
            } else {
                this.vtype1show = false
                this.vtype2show = true
                this.getUsers()
            }
        },
        getProducts () {
            axios.request({
                url: '/cnc/Product/GetProducetname',
                method: 'get'
            }).then(res => {
                this.productList = res.data.data
            })
        },
        getUsers () {
            axios.request({
                url: '/config/user/GetUsers',
                method: 'get'
            }).then(res => {
                this.userList = res.data.data
            })
        },
        search () {
            var params = {
                section_id: this.leveldata.length === 0 ? 0 : this.leveldata[this.leveldata.length - 1],
                timerange: moment(this.dateTime[0]).format('YYYY-MM-DD HH:mm:ss') + ' - ' + moment(this.dateTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                type: this.xtype,
                patchid: this.type3
            }
            axios
                .request({
                    url: '/cnc/WorkingState/DebugStateSummary',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 0) {
                        return
                    }
                    this.tableData1 = []
                    if (res.data.data != null && res.data.data.length > 1) {
                        var arr = []
                        var nameArray = []
                        res.data.data.each(rele => {
                            nameArray.push(ele.name)
                            arr.push(ele.datas)
                        })
                        this.baseEcharts(arr, nameArray)
                        this.mockTableData1(res.data.data)
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    var datalist = this.asc(item.datas)
                    var number = datalist.length// 次数
                    var average = Math.floor(sum(datalist) / datalist.length)// 平均值
                    data.push({
                        number: number,
                        name: item.name,
                        average: average * 60,
                        short: this.timechange(datalist[0] * 60),
                        long: this.timechange(datalist[number - 1] * 60)
                    })
                }
            })
            this.tableData1 = data
        },
        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
            }
        },
        baseEcharts (arr, nameData) {
            var data = this.prepareBoxplotData(arr)
            option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'item',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '4%',
                    right: '4%',
                    bottom: '10%'
                },
                xAxis: {
                    type: 'category',
                    data: nameData,
                    boundaryGap: true,
                    nameGap: 30,
                    splitArea: {
                        show: false
                    },
                    axisLabel: {
                        formatter: nameData
                    },
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '分钟',
                    splitArea: {
                        show: true
                    }
                },
                series: [
                    {
                        name: 'boxplot',
                        type: 'boxplot',
                        data: data.boxData,
                        tooltip: {
                            formatter: param => {
                                return [
                                    param.name + ': ',
                                    this.$t(200233) + ': ' + param.data[7] + '分钟',
                                    this.$t(200234) + ': ' + param.data[6] + '分钟',
                                    this.$t(200235) + ': ' + param.data[1] + '分钟',
                                    this.$t(200236) + ': ' + param.data[5] + '分钟'
                                ].join('<br/>')
                            }
                        }
                    }
                ]
            }

            var main_test = echarts.init(document.getElementById('echarts_div'))
            main_test.clear()
            main_test.setOption(option)
        },
        // 处理数据
        prepareBoxplotData (rawData, opt) {
            opt = opt || []
            var boxData = []
            var outliers = []
            var axisData = []
            var boundIQR = opt.boundIQR
            var useExtreme = boundIQR === 'none' || boundIQR === 0

            for (var i = 0; i < rawData.length; i++) {
                axisData.push(i + '')
                var ascList = this.asc(rawData[i].slice())

                var number = ascList.length// 次数
                var average = Math.floor(this.sum(ascList) / ascList.length)// 平均值

                var Q1 = this.quantile(ascList, 0.25)
                var Q2 = this.quantile(ascList, 0.5)
                var Q3 = this.quantile(ascList, 0.75)
                var min = ascList[0]
                var max = ascList[ascList.length - 1]

                var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1)

                var low = useExtreme
                    ? min
                    : Math.max(min, Q1 - bound)
                var high = useExtreme
                    ? max
                    : Math.min(max, Q3 + bound)

                boxData.push([min, Q1, Q2, Q3, max, average, number])
                for (var j = 0; j < ascList.length; j++) {
                    var dataItem = ascList[j]
                    if (dataItem < low || dataItem > high) {
                        var outlier = [i, dataItem]
                        opt.layout === 'vertical' && outlier.reverse()
                        outliers.push(outlier)
                    }
                }
            }
            return {
                boxData: boxData,
                outliers: outliers,
                axisData: axisData
            }
        },

        quantile (ascArr, p) {
            var H = (ascArr.length - 1) * p + 1
            var h = Math.floor(H)
            var v = +ascArr[h - 1]
            var e = H - h
            return e ? v + e * (ascArr[h] - v) : v
        },
        // 排序
        asc (arr) {
            arr.sort(function (a, b) {
                return a - b
            })
            return arr
        },
        // 求和
        sum (arr) {
            return arr.join('+')
        },
        handleSelectRow: function (data) {
            var ids = []
            for (var i in data) {
                ids.push(data[i].id)
            }
            this.selectids = ids
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        Export () {
            let params = {
            }
            axios.request({
                url: '/config/BeatSetDownLoad/GetTemplates',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = axios.publicPath + '' + res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg));
                }
            })
        }
    }
}
</script>
<style lang="less">
    .treeSelect{
      span{
        background:#2D8CF1;
        color:#fff;
        margin: 0;
        padding: 0 4px;
        border-radius: 3px;
        cursor: pointer;
        vertical-align: top;
      }
}
</style>
