<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">

        <div class="filter">
          <label id="产品名称">{{$t('100088')}}：</label>
          <Select
            v-model="productId"
            label-in-value
            @on-change="loadMaterial(productId)"
            clearable
            class="searchSelect"
          >
            <Option
              v-for="item in productlist"
              :value="item.id"
              :key="item.id"
            >{{item.code}}-{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="物料编号">{{$t('100390')}}：</label>
          <Select v-model="materialId" label-in-value clearable class="searchSelect">
            <Option
              v-for="item in materiallist"
              :value="item.id"
              :key="item.id"
            >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="统计维度">{{$t('9900087')}}：</label>
          <Select v-model="ttl" label-in-value clearable class="searchSelect">
            <Option
              v-for="item in ttllist"
              :value="item.id"
              :key="item.id"
            > {{ item.name }}</Option>
          </Select>
        </div>
      <div class="filter">
            <label>{{$t(1132)}}：</label>
            <Cascader
              :data="datalevel"
              :value="leveldata"
              v-model="sectionid"
              change-on-select
              @on-change="selectSection"
              class="searchSelect"
            ></Cascader>
          </div>
      <div v-show="!morecondition">
        <div>
          <div class="filter">
            <label>{{$t('1035')}}</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 class="filter">
            <label>Top：</label>
            <Select v-model="top" label-in-value  class="searchSelect">
              <Option v-for="item in toplist" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </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="md-download" @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="barForm">
		  </div>
        <Table
        class="echartsTable"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></Table>
       </div>
    </div>
  </div>
</template>
<script>
import echarts from 'echarts'
import axios from '@/libs/api.request'
import moment from 'moment'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
    name: 'Businessmanagement', // 组件不刷新
    data () {
        return {
            morecondition: false,
            obj: {},
            productId: 0,
            materialId: 0,
            daterange: '',
            productlist: [],
            materiallist: [],
            leveldata: [],
            datalevel: [],
            sectionid: [],
            echartData: [],
            tableData1: [],
            top: 5,
            toplist: [
                { id: 5, name: '5' },
                { id: 10, name: '10' },
                { id: 30, name: '30' },
                { id: 50, name: '50' },
                { id: 100, name: '100' }
            ],
            ttl: 1,
            ttllist: [
                { id: 1, name: this.$t(920165) },
                { id: 2, name: this.$t(930062) },
                { id: 3, name: this.$t(930063) },
                { id: 4, name: this.$t(930064) }
            ],
            xname: '', // x轴名称
            yname: '', // y轴名称
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    width: 70
                },
                {
                    title: this.$t('1026'),
                    key: 'sectionname'
                },
                {
                    title: this.$t('5500042'),
                    key: 'num'
                }
            ]
        }
    },
    created () {
        this.initlevel()
        this.InitTime()
        this.selectdate(this.daterange)
        this.loadProcduct()
        this.search()
    },
    methods: {
        changecondition () {
            this.morecondition = !this.morecondition
        },
        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
                })
        },
        selectSection (v) {
            this.position = v[v.length - 1]
            var params = {
                sectionId: v[v.length - 1]
            }
            this.leveldata = v
        },
        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')
            })
        },
        downexcel () {
            if (this.dtStart == '' || this.dtStart === undefined) {
                this.$Message.error(this.$t('5500043'))
                return false
            }
            var params = {
                productId: this.productId,
                section: this.position,
                materialId: this.materialId,
                stime: this.dtStart,
                etime: this.dtEnd,
                top: this.top,
                type: this.ttl,
                export: 1
            }
            axios.request({
                url: '/qms/RepairData/GetRateWateTop',
                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))
                }
            })
        },
        // 查找
        search () {
            if (this.dtStart == '' || this.dtStart === undefined) {
                this.$Message.error(this.$t('5500043'))
                return false
            }
            var params = {
                productId: this.productId,
                section: this.position,
                materialId: this.materialId,
                stime: this.dtStart,
                etime: this.dtEnd,
                top: this.top,
                type: this.ttl
            }
            axios
                .request({
                    url: '/qms/RepairData/GetRateWateTop',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.echartData = res.data.data
                        // console.log(this.echartData);
                        let x = this.echartData.x
                        let y = this.echartData.y
                        let rate = this.echartData.rate

                        var table = this.echartData.tables;
                        if (x.length == 0 || y.length == 0 || rate.length == 0) {
                            this.$Message.error(this.$t('1000'))
                            this.toBarForm(
                                this.echartData.x,
                                this.echartData.y,
                                this.echartData.rate
                            )
                        } else {
                            this.toBarForm(
                                this.echartData.x,
                                this.echartData.y,
                                this.echartData.rate
                            )
                        }

                        switch (this.ttl) {
                        case 1:
                            this.xname = this.$t(920165);
                            break;
                        case 2:
                            this.xname = this.$t(930062);
                            break;
                        case 3:
                            this.xname = this.$t(930063);
                            break;
                        case 4:
                            this.xname = this.$t(930064);
                            break;
                        default:
                            this.xname = '';
                            break;
                        }
                        this.tableColumns1 = [
                            {
                                type: 'index',
                                title: this.$t('1008'),
                                key: 'xuhao',
                                width: 70
                            },
                            {
                                title: this.xname,
                                key: 'Item'
                            },
                            {
                                title: this.$t('300084'),
                                key: 'Val'
                            },
                            {
                                title: this.$t('5000048'),
                                key: 'Rate'
                            }
                        ]
                        this.mockTableData1(table)
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        handleRowChange (currentRow, oldCurrentRow) {

        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        Item: item.item,
                        Val: item.val,
                        Rate: item.rate
                        // batch: item.batch_quantity,
                        // numRate: item.quantity_rate+"%",
                        // batchRate: item.batch_quantity_rate+"%"
                    })
                }
            })
            this.tableData1 = data
        },
        // 加载产品
        loadProcduct () {
            axios
                .request({
                    url: 'config/projectproduct/GetProducts',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productlist = res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        // 加载产品物料
        loadMaterial (productId) {
            this.materialId = 0
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/Material/GetMaterialByProcut',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.materiallist = res.data.data
                    } else {
                    }
                })
        },
        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
        },
        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]
            }
        },
        InitTime () {
            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'
            ]
        },
        toBarForm (x, y, y1) {
            let arr = []
            if (y1.length > 0) {
                y1.forEach(item => {
                    arr.push(parseFloat(item).toFixed(2))
                })
            }
            var intervalx
            var max_y = Math.ceil(Math.max(...y) / 5) * 5
            intervalx = max_y / 5
            var myChart = echarts.init(document.getElementById('barForm'))
            var option = {
                title: {
                    text: this.$t(9900044),
                    y: 'top',
                    x: 'left',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b0}<br />{a0}: {c0}<br />{a1}: {c1}%',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#283b56'
                            // #0F58D6
                        }
                    }
                },
                grid: {
                    bottom: 100 // 默认60
                },
                legend: {
                    data: [this.$t(90000046), this.$t(5000048) + '(%)']
                },
                xAxis: {
                    name: this.$t(100391),
                    nameTextStyle: {
                        padding: [10, 0, -50, -40]
                    },
                    type: 'category',
                    data: x,
                    axisLabel: {
                        interval: 0,
                        rotate: 20
                    }
                },

                yAxis: [
                    {
                        name: this.$t(90000046),
                        type: 'value',
                        // interval:5
                        interval: intervalx,
                        max: max_y
                    },
                    {
                        name: this.$t(5000048) + '%',
                        type: 'value',
                        data: y1,
                        max: 100,
                        min: 0,
                        interval: 20
                        // interval:5
                    }
                ],
                series: [
                    {
                        data: y,
                        name: this.$t(90000046),
                        type: 'bar',
                        barMaxWidth: 70,
                        barWidth: 30,
                        label: {
                            show: true,
                            color: 'black',
                            position: 'top', // 在中间显示
                            distance: 2
                        },
                        itemStyle: {
                            normal: {
                                color: '#0F58D6'
                            }
                        }
                    },
                    {
                        data: arr,
                        type: 'line',
                        name: this.$t(5000048),
                        barWidth: 30,
                        yAxisIndex: 1,
                        label: {
                            show: false,
                            color: 'red',
                            formatter: '{c}%',
                            position: 'top', // 在上方显示
                            distance: 2
                        },
                        itemStyle: {
                            normal: {
                                show: false,
                                formatter: '{c}%',
                                color: 'red'
                            }
                        }
                    }
                ]
            }
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        }
    // toBar() {
    //   var myChart = echarts.init(document.getElementById('bar'));
    //   var option = {
    //     title: {
    //       text: "以通道工位报废金额排序"
    //     },
    //     tooltip: {},
    //     legend: {
    //       // data: ["销量"]
    //       x:'center',
    //       y:'bottom'
    //     },
    //     xAxis: {
    //       data: [2017, 2018, 2019],
    //       //以通道工位报废金额排序
    //       axisLabel: {
    //         interval: 0 //代表显示所有x轴标签显示
    //       }
    //     },
    //     yAxis: [
    //       {
    //         type: "value",
    //         min: 0,
    //         max: 9,
    //         interval: 1,
    //         show: true
    //       },
    //       {
    //         type: "value",
    //         min: 0,
    //         max: 100,
    //         interval: 10,
    //         axisLabel: {
    //           formatter: "{value} %"
    //         }
    //       }
    //     ],
    //     series: [
    //       {
    //         name: "Scrap Quantity",
    //         type: "bar",
    //         barWidth: 30,
    //         data: [1, 2, 3], //以通道工位报废金额排序top
    //         itemStyle: {
    //           normal: {
    //             color: "#0F58D6"
    //           }
    //         },
    //         label: {
    //           show: true,
    //           color: "#333"
    //         }
    //       },
    //       {
    //         name: "Scrap Rate",
    //         type: "line",
    //         yAxisIndex: 1,
    //         data: [20, 30, 40], //以通道工位报废金额排序top报废率
    //         symbolSize: 5,
    //         itemStyle: {
    //           normal: {
    //             label: {
    //               show: true,
    //               formatter: "{c}%",
    //               color:'#333'
    //             },
    //             color: "red"
    //           }
    //         }
    //       }
    //     ]
    //   };
    //   myChart.setOption(option);
    //   window.onresize = function() {
    //     myChart.resize();
    //   };
    // }
    }
}
</script>
<style scoped>

</style>
