<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div>
        <div class="filter">
          <label >{{$t('1950491')}}：</label>
          <Cascader :data="datalevel" :value="leveldata"  trigger="click" @on-change="handlelevelchange" change-on-select class="searchSelect"></Cascader>
        </div>
        <div class="filter">
          <label >{{$t('100307')}}：</label>
          <Select v-model="productid" label-in-value @on-change="initmaterials" clearable filterable 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('920165')}}：</label>
          <Select v-model="materialid" label-in-value clearable filterable class="searchSelect" >
              <Option v-for="item in materials" :value="item.id" :key="item.id">{{ 
                ((item.name === null || item.name === undefined || item.name === '') ? '' : item.name) +
                ((item.pn === null || item.pn === undefined || item.pn === '') ? '' : "【"+ item.pn +"】") + 
                ((item.spec === null || item.spec === undefined || item.spec === '') ? '' : "【" + item.spec + "】") }}</Option>
          </Select>
        </div>
        <div class="filter">
                <label >{{$t(9900087)}}：</label>
                <Select v-model="Statisticstype" label-in-value clearable class="searchSelect" >
                    <Option :value="0" :key="0">{{$t(5500021)}}</Option>
                    <Option :value="1" :key="1">{{$t(5500022)}}</Option>
                </Select>
            </div>
        <!-- 次级搜索条件--隐藏 -->
      <div v-show="!morecondition">
        <div>
            <div class="filter">
            <label >{{$t(5500023)}}：</label>
            <Select v-model="xtype" label-in-value clearable class="searchSelect" >
                <Option :value="0" :key="0">{{$t(930064)}}</Option>
                <!--<Option :value="1" :key="1">送检工位</Option>-->
                <Option :value="2" :key="2">{{$t(5500024)}}</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 intervalRight" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
        <Button type="primary" class="fourWord" icon="ios-document" @click="downpdf()">{{$t('900741')}}</Button>
      </div>
     <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <div class="divborder newEchartStyle" >
      <div id="demo">
          <div class="echartsId" id="div_echarts" ref="echart">
      </div>
      <Table
        class="echartsTable"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></Table>
      </div>

    </div>

  </div>
</template>

<script>
import axios from '@/libs/api.request'
import echarts from 'echarts'
import moment from 'moment'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default{
    data () {
        return {
            Statisticstype: 0, // 统计维度
            xtype: 0, // 横坐标
            materialid: 0,
            materials: [],
            sectionid: 0,
            leveldata: [],
            datalevel: [],
            productid: 0,
            products: [],
            morecondition: false,
            tableData1: [],
            daterange: [],
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    width: 70
                },
                {
                    title: this.$t(930064),
                    key: 'section'
                },
                {
                    title: this.$t(1950640),
                    key: 'time'
                },
                {
                    title: this.$t(1950641),
                    key: 'time1'
                },
                {
                    title: this.$t(1950642),
                    key: 'time2'
                }
            ],
            loading: false
        }
    },
    created () {

    },
    mounted () {
        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.initlevel()
        this.initproducts()
        this.initmaterials()
        this.search()
    },
    methods: {
        downpdf () {
            var target = document.querySelector('#demo')
            html2canvas(target, { allowTaint: true, dpi: 172, background: '#fff' }).then(function (canvas) {
                var contentWidth = canvas.width
                var contentHeight = canvas.height

                // 一页pdf显示html页面生成的canvas高度;
                var pageHeight = contentWidth / 592.28 * 841.89
                // 未生成pdf的html页面高度
                var leftHeight = contentHeight
                // pdf页面偏移
                var position = 0
                // html页面生成的canvas在pdf中图片的宽高（a4纸的尺寸[595.28,841.89]）
                var imgWidth = 595.28
                var imgHeight = 592.28 / contentWidth * contentHeight

                var pageData = canvas.toDataURL('image/jpeg', 1.0)
                var pdf = new JsPDF('', 'pt', 'a4')

                // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
                // 当内容未超过pdf一页显示的范围，无需分页
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= 841.89
                        // 避免添加空白页
                        if (leftHeight > 0) {
                            pdf.addPage()
                        }
                    }
                }
                pdf.save('content.pdf')
            })
        },
        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
        },
        handlelevelchange (data) {
            this.leveldata = data
            if (data && data.length > 0) {
                this.sectionid = data[data.length - 1]
                this.initproducts()
            }
        },
        initlevel () {
            axios.request({
                url: '/qms/SendTestCollection/GetInspectionSectionTree?inspectiontype=1&iscompelete=1',
                method: 'get'
            }).then(res => {
                var arr = []
                this.datalevel = res.data.data
                arr.push(res.data.data[0].value)
                this.leveldata = arr
            })
        },
        initmaterials () {
            this.materials = [{ id: 0, name: '', pn: '', spec: '' }]
            axios.request({
                url: '/qms/SendTestCollection/GetInspectionMaterials?productid=' + this.productid + '&iscompelete=1',
                method: 'get'
            }).then(res => {
                this.materials = res.data.data
            })
        },
        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: '/qms/SendTestCollection/GetInspectionProducts?sectionid=' + this.sectionid + '&iscompelete=1',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    this.products = res.data.data
                }
            })
        },
        search () {
            var params = {
                productid: this.productid,
                sectionid: this.sectionid,
                materialid: this.materialid,
                starttime: this.dtStart,
                endtime: this.dtEnd,
                type: this.Statisticstype,
                x_type: this.xtype
            }
            axios.request({
                url: '/qms/Statistical/GetSendTestInspectionTime',
                data: params,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    var data = res.data.data
                    // 画图
                    this.getEcharts(data.x, data.y, data.y1, data.y2)
                    this.mockTableData1(data.datalist)
                }
            })
        },
        mockTableData1 (tablelist) {
            let data = []
            if (this.xtype === 2 || this.xtype === '2') {
                this.tableColumns1 = [
                    {
                        type: 'index',
                        title: this.$t('1008'),
                        key: 'xuhao',
                        width: 70
                    },
                    {
                        title: this.$t(100307),
                        key: 'section'
                    },
                    {
                        title: this.$t(1950640),
                        key: 'time'
                    },
                    {
                        title: this.$t(1950641),
                        key: 'time1'
                    },
                    {
                        title: this.$t(1950642),
                        key: 'time2'
                    }
                ]
            } else {
                this.tableColumns1 = [
                    {
                        type: 'index',
                        title: this.$t('1008'),
                        key: 'xuhao',
                        width: 70
                    },
                    {
                        title: this.$t(930064),
                        key: 'section'
                    },
                    {
                        title: this.$t(1950640),
                        key: 'time'
                    },
                    {
                        title: this.$t(1950641),
                        key: 'time1'
                    },
                    {
                        title: this.$t(1950642),
                        key: 'time2'
                    }
                ]
            }
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        section: item.section,
                        time: item.time,
                        time1: item.time1,
                        time2: item.time2
                    })
                }
            })
            this.tableData1 = data
        },
        getEcharts (x, y, y1, y2) {
            if (x.length > 6) {
                this.$refs.echart.style.height = (x.length * 18) + 'px';
            } else {
                this.$refs.echart.style.height = '300px';
            }
            var myChart = echarts.init(document.getElementById('div_echarts'))
            myChart.resize()
            var option = {
                title: {
                    text: '',
                    subtext: '',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                color: ['blue'],
                legend: {
                    data: [this.$t(5500025)]
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01],
                    name: this.$t(1046)
                },
                yAxis: {
                    type: 'category',
                    data: x,
                    name: (this.xtype === 2 || this.xtype === '2') ? this.$t(100307) : this.$t(930064)
                },
                series: [
                    {
                        name: this.$t(1950640),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: 'time',
                        // barWidth:30,
                        data: y,
                        itemStyle: {
                            normal: {
                                color: '#61A5E8',
                                label: {
                                    show: false, // 开启显示
                                    position: 'insideRight', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    },
                    {
                        name: this.$t(1950641),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: 'time',
                        // barWidth:30,
                        data: y1,
                        itemStyle: {
                            normal: {
                                color: '#F59A23',
                                label: {
                                    show: false, // 开启显示
                                    position: 'insideRight', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    },
                    {
                        name: this.$t(1950642),
                        type: 'bar',
                        barMaxWidth: 70,
                        stack: 'time',
                        // barWidth:30,
                        data: y2,
                        itemStyle: {
                            normal: {
                                color: '#70B603',
                                label: {
                                    show: false, // 开启显示
                                    position: 'insideRight', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    }
                ]
            };
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        handleRowChange (currentRow, oldCurrentRow) {

        }
    }
}

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

</style>
