<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div>
        <div class="filter">
          <label >{{$t('100307')}}：</label>
          <Select v-model="productid" label-in-value clearable filterable @on-change="initmaterials" class="searchSelect" >
              <Option v-for="item in products" :value="item.id" :key="item.id">{{ item.name+"【"+ item.code +"】" }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label >{{$t('100390')}}：</label>
          <Select v-model="materialid" label-in-value clearable filterable class="searchSelect" >
              <Option v-for="item in materials" :value="item.id" :key="item.structureid">{{ item.name+"【"+ item.pn +"】" + "【" + item.spec + "】" }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label >{{$t('100391')}}：</label>
          <Select v-model="materialNameId" label-in-value clearable filterable class="searchSelect" >
              <Option v-for="item in materialNames" :value="item.id" :key="item.structureid">{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label >{{$t('1950597')}}：</label>
          <Select v-model="itemid" label-in-value  clearable filterable class="searchSelect" >
              <Option v-for="item in items" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>

        <!-- 次级搜索条件--隐藏 -->
      <div v-show="!morecondition">
        <div>
          <div class="filter">
          <label>{{$t('1129')}}：</label>
          <Select v-model="x_type" label-in-value clearable class="searchSelect">
            <Option value="0">{{$t('1101')}}</Option>
            <Option value="1">{{$t('1136')}}</Option>
            <Option value="2">{{$t('1138')}}</Option>
            <Option value="5">{{$t('1140')}}</Option>
            <Option value="4">{{$t('1142')}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label >{{$t('1950502')}}：</label>
          <Select v-model="testroom" label-in-value clearable class="searchSelect" >
              <Option v-for="item in edittestrooms" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
        </div>
        <div class="filter">
            <label>{{$t('1046')}}：</label>
            <DatePicker
              id="日期"
              type="datetimerange"
              v-model="daterange"
              confirm
              placeholder=""
              class="searchInput MaxWidth "
              format="yyyy-MM-dd HH:mm:ss"
              @on-change="selectdate"
            ></DatePicker>
        </div>
      </div>
      </div>

      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
      </div>

      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>

    </div>
    <div class="divborder" ref='chart'>
        <!--<div id='chart1' style="height:400px;"></div>
        <div id='chart2' style="height:400px;"></div>-->
    </div>
  </div>
</template>

<script>
import axios from '@/libs/api.request'
import echarts from 'echarts'
import moment from 'moment'
export default{
    data () {
        return {
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            morecondition: false, // 条件
            products: [],
            dtStart: '',
            dtEnd: '',
            daterange: '',
            host: axios.publicPath,
            materials: [],
            leveldata: [],
            datalevel: [],
            sectionid: [],
            materialid: 0,
            productid: 0,
            edittestrooms: [],
            testroom: '',
            itemid: 0,
            items: [],
            x_type: 0,
            materialNames: [],
            materialNameId: ''
        }
    },
    created () {
        var nowtime = Date.parse(new Date()) / 1000
        var oldtime = nowtime - 86400 * 7
        this.daterange = [this.datetrans(oldtime) + '00:00:00', this.datetrans(nowtime) + '23:59:59']
        this.selectdate(this.daterange)
        this.initproducts()
        this.initedittestrooms()
        this.initlevel()
        // this.inititems()
        this.inititemList()
    },
    methods: {
        initedittestrooms () {
            axios.request({
                url: '/qms/SendTestCollection/GetTestRoomDict',
                method: 'get'
            })
                .then(res => {
                    this.edittestrooms = res.data.data
                })
        },
        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
            })
        },
        initmaterials () {
            axios.request({
                url: '/config/Material/GetSonMaterialsByProduct?productid=' + this.productid,
                method: 'get'
            }).then(res => {
                this.materials = res.data.data
            })

            axios.request({
                url: '/config/Material/GetSonMaterialNamesByProduct?productid=' + this.productid,
                method: 'get'
            }).then(res => {
                this.materialNames = res.data.data
            })

            // this.inititems(this.productid)
        },
        inititems (pid) {
            axios.request({
                url: '/qms/InspectStandard/GetItems?productid=' + pid,
                method: 'get'
            }).then(res => {
                this.items = res.data.data
            })
        },
        inititemList () {
            axios.request({
                url: '/qms/InspectStandard/GetAllCheckItemNameList',
                method: 'get'
            }).then(res => {
                this.items = res.data.data
            })
        },
        datetrans (date) {
            if (date === '' || date === undefined || date === 0 || date === null) {
                return ''
            }
            date = new Date(date * 1000)
            var Y = date.getFullYear() + '-'
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
            var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
            return Y + M + D
        },
        search () {
            if (this.itemid === 0 || this.itemid === undefined || this.itemid === null || this.itemid === '') {
                this.$Message.error(this.$t(200237))
                return
            }
            var mychart = this.$refs.chart
            mychart.innerHTML = ''
            var params = {
                productid: this.productid,
                testroom: this.testroom,
                starttime: this.dtStart,
                endtime: this.dtEnd,
                materialid: this.materialid,
                itemid: this.itemid,
                x_type: this.x_type,
                materialNameId: this.materialNameId
            }
            axios.request({
                url: '/qms/Statistical/GetTestRoomQualifiedReport',
                data: params,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    var data = res.data.data
                    if (data.factoryData !== null && data.factoryData !== undefined && data.factoryData !== []) {
                        var myCharts = []
                        var options = []
                        data.factoryData.forEach((ele, index) => {
                            mychart.innerHTML += "<div id='factory" + index + "' style='height:400px;width:100%;float:left'></div>"
                            mychart.innerHTML += "<div style='width:100%;float:left'>"
                            ele.channelData.forEach((element, index1) => {
                                mychart.innerHTML += "<div id='channel" + index + '' + index1 + "' style='height:400px;float:left;width:50%;'></div>"
                            })
                            mychart.innerHTML += '</div>'
                        })
                        data.factoryData.forEach((ele, index) => {
                            myCharts.push(echarts.init(document.getElementById('factory' + index)))
                            options.push(this.addOption(ele.x, ele.y, ele.y1, ele.y2, ele.factory))
                            ele.channelData.forEach((element, index1) => {
                                myCharts.push(echarts.init(document.getElementById('channel' + index + '' + index1)))
                                options.push(this.addOption(element.x, element.y, element.y1, element.y2, element.channel))
                            })
                        })
                        this.echarts1(myCharts, options)
                    }
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        addOption (x, y1, y2, y3, title) {
            var option = {
                title: {
                    text: title,
                    x: 'center',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: '{b0}<br/>{a0}: {c0}<br />{a1}: {c1}<br />{a2}: {c2}%<br />'
                },
                legend: {
                    data: [this.$t(1950595), this.$t(930031), this.$t(930030)],
                    right: '20%',
                    bottom: '90%'
                },
                /* grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        }, */
                xAxis: [
                    {
                        name: this.$t(1046),
                        nameLocation: 'end',
                        nameTextStyle: {
                            padding: [30, 0, 0, -25]
                        },
                        type: 'category',
                        data: x,
                        axisLabel: {
                            interval: 0,
                            rotate: 40
                        }
                    }
                ],
                yAxis: [
                    {
                        name: this.$t('300084'),
                        type: 'value',
                        minInterval: 1
                    },
                    {
                        name: this.$t(930030),
                        type: 'value',
                        max: 100,
                        axisLabel: {
                            formatter: '{value} %',
                            show: true
                        },
                        axisTick: {
                            show: false
                        },
                        splitLine: {
                            show: false
                        }
                    }
                ],
                series: [
                    {
                        name: this.$t(1950595),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: '广告',
                        color: 'green',
                        data: y1
                    },
                    {
                        name: this.$t(930031),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: '广告',
                        data: y2
                    },
                    {
                        name: this.$t(930030),
                        type: 'line',
                        color: 'blue',
                        yAxisIndex: 1,
                        symbolSize: 9,
                        data: y3,
                        itemStyle: {
                            normal: {
                                label: {
                                    formatter: '{c} %',
                                    show: true
                                }
                            }
                        }
                    }
                ]
            }
            return option
        },
        echarts1 (myCharts, options) {
            myCharts.forEach((ele, index) => {
                myCharts[index].setOption(options[index])
                window.onresize = function () {
                    myCharts[index].resize()
                }
            })
        },
        selectdate (e) {
            this.dtStart = e[0]
            this.dtEnd = e[1]
            let last_str = this.dtEnd.split(' ')[1]
            if (last_str === '00:00:00') {
                this.dtEnd = moment(this.dtEnd).format('YYYY-MM-DD') + ' 23:59:59'
                this.daterange = [this.dtStart, this.dtEnd]
            }
        },
        initproducts () {
            axios.request({
                url: '/config/ProjectProduct/GetProducts',
                method: 'get'
            }).then(res => {
                this.products = res.data.data
            })
        }
    }
}

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

</style>
