<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <div class="filter">
        <label>{{$t('1132')}}：</label>
        <Cascader :data="datalevel" v-model="leveldata" :render-format="format" trigger="click" @on-change="levelchange"
          change-on-select class="searchSelect"></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('500088')}}：</label>
        <Select v-model="filterObj.statisticalIndicators" @on-change="statisticalIndicatorsChange" label-in-value
          clearable class="searchSelect">
          <Option :value="1" v-text="$t('9900010')">{{$t('9900010')}}</Option>
          <Option :value="2" v-text="$t('9900011')">{{$t('9900011')}}</Option>
          <Option :value="3" v-text="$t('9900012')">{{$t('9900012')}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('1129')}}：</label>
         <Select v-model="type1" class="searchSelect" @on-change="xTypechange" style="margin-right:10px;">
            <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="x_id" clearable class="searchSelect" v-show="showStr">
            <Option v-for="(item,key) in xTypeList" :value="item.value" :key="key">{{ item.label }}</Option>
          </Select>

        <!-- <Select v-model="filterObj.abscissa" label-in-value @on-change="abscissaChange" clearable style="width:90px;">
          <Option :value="1" v-text="$t('500065')">时间单位</Option>
          <Option :value="2" v-text="$t('1132')">产线层级</Option>
        </Select>
        <Select v-show="filterObj.abscissa===1" @on-change="timeTypeChange" v-model="filterObj.timeType" label-in-value
          clearable style="width:90px;" class="ml5">
          <Option key="a" value="a" v-text="$t('1101')">天</Option>
          <Option key="b" value="b" v-text="$t('1136')">周</Option>
          <Option key="c" value="c" v-text="$t('1138')">月</Option>
        </Select>
        <Select v-show="filterObj.abscissa===2" v-model="filterObj.sectionType" label-in-value clearable style="width:90px;"
          class="ml5">
          <Option v-show="leveldata.length != 2" :key="2" :value="2" v-text="$t('900879')">产线</Option>
          <Option v-show="leveldata.length <= 2" :key="1" :value="1" v-text="$t('900881')">工站</Option>
        </Select> -->
      </div>
       <div class="filter">
            <label>{{$t('900908')}}：</label>
            <DatePicker type="datetimerange" format="yyyy-MM-dd " :clearable="false" v-model="filterObj.timeRange" class="searchInput middleWidth"></DatePicker>
          </div>
      <!-- 次级搜索条件 隐藏 -->
      <div v-show="!morecondition">
        <div>

          <div class="filter" v-if="filterObj.statisticalIndicators===1||filterObj.statisticalIndicators===2">
            <label>{{$t('800191')}}：</label>
            <Select v-model="filterObj.maintenanceType" label-in-value clearable class="searchSelect">
              <Option :value="1">AM</Option>
              <Option :value="2">PM</Option>
              <Option :value="3">CMP</Option>
            </Select>
          </div>
          <!-- <div class="filter">
            <label v-text="$t('90000030')">安灯类型</label>:
            <Select v-model="andonType" multiple :max-tag-count="1" label-in-value clearable style="width:200px;">
              <Option v-for="item in andonList" :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 style="float:right;" >
          <label v-text="$t('8000050')">目标基准线</label>:
          <Input type="number" :min="0" v-model="line_value" @keyup.enter.native="search()" style="margin-right:30px;width:160px;"></Input>
        </div>
        <div style="padding:20px 100px;">
          <div id="main" class="echartsId"></div>
        </div>
        <div style="padding:0 80px;">
          <div>
            <span style="width: 30%;display: inline-block;overflow: hidden;">{{$t(1046)}}：{{this.time}}</span>
            <span style="width: 30%;display: inline-block;overflow: hidden;">{{$t(1157)}}：{{this.linetext}}</span>
          </div>
          <Table v-if="tableshow===1" class="echartsTable" highlight-row :data="tableData1" :columns="tableColumns1" :max-height="300"></Table>
          <Table v-else-if="tableshow===2" class="echartsTable" highlight-row :data="tableData2" :columns="tableColumns2" :max-height="300"></Table>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
    data () {
        return {
            datalevel: [], // 产线层级数据
            leveldata: [], // 产线层级value
            xTypeList: [{ value: 'a', label: this.$t('900864') }, { value: 'b', label: this.$t('1136') }, { value: 'c', label: this.$t('1138') }], // 横坐标
            showStr: true, // 横坐标显示
            type1: 1, // 统计指标select
            x_id: 'a',
            filterObj: {
                statisticalIndicators: 1, // 统计指标
                abscissa: 1, // 横坐标1
                timeType: 'a', // 时间单位横坐标
                sectionType: 514, // 产线层级横坐标
                maintenanceType: 0, // 维护类型
                timeRange: []
            },
            line_value: 0, // 基准线数值
            andonType: [], // andon类型
            andonList: [], // andon类型list
            morecondition: false, // 次级搜索条件 默认隐藏
            tableshow: 0, // 控制表格显示
            time: '', // 列表上面的时间范围
            linetext: '', // 列表上面的设备位置

            tableData1: [],
            tableColumns1: [{
                title: '时间单位',
                key: 'unit'
            },
            {
                title: this.$t('800196'), // 执行数量
                key: 'Execution_quantity'
            },
            {
                title: this.$t('800197'), // 计划数量
                key: 'Planned_quantity'
            }
            ],

            tableData2: [],
            tableColumns2: [{
                title: this.$t(800199),
                key: 'name'

            },
            {
                title: this.$t(900328),
                key: 'actualtime'
            },
            {
                title: this.$t(8000027),
                key: 'standardtime'
            }
            ],

            tableData3: [],
            tableColumns3: [{
                title: this.$t(1008),
                key: 'name',
                render: (h, params) => {
                    return h('span', params.index + 1)
                }
            },
            {
                title: this.$t(950389),
                key: 'val'
            },
            {
                title: this.$t(950390),
                key: 'unit'
            }
            ],

            echartObj: null
        }
    },
    created () {
        this.initlevel()
        this.filterObj.timeRange = [moment(new Date().getTime() - 3600 * 1000 * 24 * 30).format('YYYY-MM-DD '),
            moment(new Date().getTime()).format('YYYY-MM-DD ')
        ]
        this.iniandonlist();
        this.time = this.filterObj.timeRange[0] + ' - ' + this.filterObj.timeRange[1]
        this.search()
    },
    methods: {
    // 初始化产线层级
        initlevel () {
            this.axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    const arr = []
                    this.datalevel = res.data.data
                    this.levelid = res.data.data[0].value
                    arr.push(res.data.data[0].value)
                    this.leveldata = arr
                    // this.leveldata = []
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        iniandonlist () { // 初始化安灯类型
            var params = {
                level: 2
            };
            this.axios
                .request({
                    url: '/tpm/andon/GetErrorsByLevel',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret == 1) {
                        this.andonList = res.data.data;
                    }
                });
        },
        getTitle () {
            if (this.filterObj.statisticalIndicators === 1) {
                if (this.filterObj.abscissa === 1) { // 时间单位-年月日
                    this.tableColumns1[0].title = this.$t(500065)
                    // +'(' + (this.filterObj.timeType === 'a' ? this.$t(1101) : (this.filterObj.timeType ===
                    //       'b' ? this.$t(1136) : this.$t(1138))) +
                    //     ')'
                } else { // 产线层级-产线，工站
                    this.tableColumns1[0].title = this.filterObj.sectionType === 514 ? this.$t(900879) : this.$t(900881)
                }
            }
        },
        format (labels, selectedData) {
            const index = labels.length - 1
            this.linetext = labels.join(' / ')
            var label = labels.join(' / ')
            return label
        },
        levelchange (data) {
            // if (this.leveldata.length === 1) {
            //   this.filterObj.sectionType = 514
            // }
            // if (this.leveldata.length === 2) {
            //   this.filterObj.sectionType = 515
            // }
            // if (this.leveldata.length > 2) {
            //   this.filterObj.sectionType = ''
            // }
            this.levelid = data[data.length - 1]
            this.leveldata = data
            this.getLevels()
        },
        // 横坐标选择
        xTypechange () {
            this.showStr = true
            if (this.type1 === 1) {
                this.xTypeList = [{ value: 'a', label: this.$t('900864') }, { value: 'b', label: this.$t('1136') }, { value: 'c', label: this.$t('1138') }]
                this.x_id = 'a'
            } else if (this.type1 === 2) {
                this.getLevels()
            } else {
                this.showStr = true
                // this.xTypeList = []
            }
        },
        getLevels () {
            this.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.x_id = this.xTypeList[0].value
                    } else {
                        this.showStr = false
                    }
                }
            })
        },
        changecondition () {
            this.morecondition = !this.morecondition
        },
        statisticalIndicatorsChange (value) {
            this.type1 = 1
            this.x_id = 'a'
            this.filterObj.sectionType = 514
            this.filterObj.maintenanceType = 0 // am\pm
        },
        timeTypeChange (value) {
            this.tableColumns2[0].title = value.value === 'a' ? this.$t(800199) : (value.value === 'b' ? this.$t(800200)
                : this.$t(800201))
        },
        abscissaChange (value) {

        },
        // 渲染列表开始
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                var tim
                if (item.tim == null) {
                    tim = '-'
                }
                data.push({
                    unit: item.tim,
                    Execution_quantity: item.les,
                    Planned_quantity: item.total
                })
            })
            this.tableData1 = data
        },
        search () {
            if (this.filterObj.timeRange[0] === '') {
                this.$Message.error(this.$t('1143'))
                return false
            }
            if(!this.x_id){
                this.$Message.error(this.$t('5500238'))
                return false
            }

            this.getTitle()
            var starttime = moment(this.filterObj.timeRange[0]).format('YYYY-MM-DD ')
            var endtime = moment(this.filterObj.timeRange[1]).format('YYYY-MM-DD ')
            if (this.filterObj.statisticalIndicators === 2) {
                this.planRate(starttime, endtime, this.leveldata[this.leveldata.length - 1]) // 绘制计划比
            } else if (this.filterObj.statisticalIndicators === 3) {
                this.statistics(starttime, endtime, this.leveldata[this.leveldata.length - 1]) // 绘制工单统计
            } else {
                var params = {
                    id: this.leveldata[this.leveldata.length - 1]
                }
                this.axios.request({ // 根据产线层级获得数组
                    url: '/config/UserLevel/ListMachineIdArrEx',
                    params,
                    method: 'get'
                }).then(res => {
                    if (res.data.ret === 1) {
                        this.time = starttime + ' - ' + endtime
                        this.completionRate(starttime, endtime, res.data.data) // 绘制完成率
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
            }
        },
        statistics (starttime, endtime, sectionid) {
            var data = {
                sectionId: this.leveldata[this.leveldata.length - 1],
                starttime: starttime,
                endtime: endtime,
                level_id: sectionid,
                x_type: this.type1, // 故障次数
                x_id: this.x_id, // 横坐标
                offlinestatus: '',
                mode: 0,
                expections: this.andonType ? this.andonType : []
            }
            this.axios.request({
                url: '/tpm/Statistics/RepairWorkOrderSumEx',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    if (this.type1 === 1) {
                        this.tableColumns3[1].title = this.$t(100074)
                        this.tableColumns3[2].title = this.$t(800205)
                    } else if (this.type1 === 2) {
                        this.tableColumns3[1].title = this.$t(1026)
                        this.tableColumns3[2].title = this.$t(800205)
                    }
                    this.tableshow = 3;
                    this.mockTableData3(res.data.data.x, res.data.data.y1)
                    var x = res.data.data.x
                    x.forEach(element => {
                        if (element == null) {
                            element = '-'
                        }
                    })
                    const obj = this.$time.removezero(res.data.data)
                    this.plans3(obj.arr, obj.arr1, obj.arr2)
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        plans3 (xName, barData, lineData) {
            let name = ''
            for (var i = 0; i < lineData.length; i++) {
                lineData[i] = parseInt(lineData[i] * 100)
            }
            if (this.echartObj != null && this.echartObj != '' && this.echartObj != undefined) {
                this.echartObj.dispose()
            }
            this.echartObj = echarts.init(document.getElementById('main'))
            this.echartObj.clear()
            let option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                // tooltip: {
                //   trigger: 'axis',
                //   axisPointer: {
                //     type: 'cross',
                //     crossStyle: {
                //       color: '#999'
                //     }
                //   }
                // },
                legend: {
                    data: [this.$t('8000026'), this.$t('700143') + '%']
                    //                data:['执行数','计划数']
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        // if (B == 0) {
                        //   return params[0].name + '<br/>' + params[0].seriesName + ' : ' + params[0].value + '%'
                        // } else {
                        return params[0].name + '<br/>' + params[0].seriesName + ' : ' + params[0].value +
                            '<br/>' + params[1].seriesName + ' : ' + params[1].value + '%'
                        // }
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    top: '10%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: xName,
                    axisPointer: {
                        type: 'shadow'
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 50
                    }
                }],
                yAxis: [{
                    type: 'value',
                    name: this.$t('8000026')
                },
                {
                    type: 'value',
                    name: this.$t('700143') + '%',
                    min: 0,
                    max: 100,
                    splitLine: {
                        show: false
                    }
                }
                ],
                series: [{
                    name: this.$t('8000026'),
                    type: 'bar',
                    barMaxWidth: 70,
                    data: barData,
                    markLine: {
                        data: [
                            { yAxis: this.line_value }
                        ]
                    }
                },
                {
                    name: this.$t('700143') + '%',
                    type: 'line',
                    yAxisIndex: 1,
                    data: lineData
                }
                ]
            }
            this.echartObj.setOption(option)
            // window.onresize = function(){
            //     myChart.resize();
            // }
        },
        planRate (starttime, endtime, sectionid) {
            // console.log(this.this.filterObj.maintenanceType)
            var data
            if (this.type1 === 1) {
                data = {
                    sectionId: this.leveldata[this.leveldata.length - 1],
                    starttime: starttime,
                    endtime: endtime,
                    sectionid: sectionid,
                    mode: this.filterObj.maintenanceType,
                    Xtype: this.type1, // xtype为时间(1)时,x轴=a,b,c
                    x_id: this.x_id,
                    expections: this.andonType ? this.andonType : []
                }
            } else if (this.type1 === 2) {
                data = {
                    sectionId: this.leveldata[this.leveldata.length - 1],
                    starttime: starttime,
                    endtime: endtime,
                    sectionid: sectionid,
                    mode: this.filterObj.maintenanceType,
                    Xtype: this.type1,
                    x_id: this.x_id, // xtype为产线层级(2)时,x轴=工站（515），产线（514）
                    expections: this.andonType ? this.andonType : []
                }
            } else {
                data = {
                    sectionId: this.leveldata[this.leveldata.length - 1],
                    start_time: starttime,
                    end_time: endtime,
                    sectionid: sectionid,
                    Xtype: this.type1, // xtype为执行人(3)时,x轴=3
                    mode: this.filterObj.maintenanceType
                }
            }
            this.axios.request({
                url: '/tpm/Statistics/PlanTimeAnalysis',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    var x = res.data.data.x
                    x.forEach(element => {
                        if (element == null) {
                            element = '-'
                        }
                    })
                    this.tableshow = 2;
                    this.tableData2 = res.data.data.planTimeCounts;
                    const obj = this.$time.removezero(res.data.data)
                    this.plans(obj.arr1, obj.arr2, obj.arr, res.data.data.y3)
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        mockTableData2 (data) {
            this.tableData2 = data
        },
        mockTableData3 (x, y1) {
            let data = []
            x.forEach((item, index) => {
                data.push({
                    val: item,
                    unit: y1[index] + this.$t(200163)
                })
            })
            this.tableData3 = data
        },
        completionRate (starttime, endtime, midArr) {
            var data
            if (this.type1 === 1) {
                data = {
                    sectionId: this.leveldata[this.leveldata.length - 1]?this.leveldata[this.leveldata.length - 1]:0,
                    start_time: starttime,
                    end_time: endtime,
                    machineidarr: midArr,
                    mode: this.filterObj.maintenanceType, // am,pm
                    // Xtype: this.filterObj.timeType, // xtype为时间(1)时,x轴=a,b,c
                    Xtype: this.type1, // xtype为时间(1)时,x轴=a,b,c
                    x_id: this.x_id,
                    expections: this.andonType ? this.andonType : []
                }
            } else if (this.type1 === 2) {
                data = {
                    sectionId: this.leveldata[this.leveldata.length - 1],
                    start_time: starttime,
                    end_time: endtime,
                    machineidarr: midArr,
                    mode: this.filterObj.maintenanceType, // am,pm
                    // Xtype: this.filterObj.abscissa, // x轴
                    Xtype: this.type1, // x轴
                    x_id: this.x_id,
                    expections: this.andonType ? this.andonType : []
                }
            }
            this.axios.request({
                url: '/tpm/Plan/SearchStatistical',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.tableshow = 1;
                    this.mockTableData1(res.data.datas)
                    var x = res.data.data.x
                    x.forEach(element => {
                        if (element === null) {
                            element = '-'
                        }
                    })
                    const obj = this.$time.removezero(res.data.data)
                    this.plans(obj.arr1, obj.arr2, obj.arr, res.data.data.y3)
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        // ehcart图
        plans (A, B, C, D) {
            if (this.echartObj != null && this.echartObj != '' && this.echartObj != undefined) {
                this.echartObj.dispose()
            }
            var arrx = []
            var Aname = '';
            var Bname = '';
            if (this.filterObj.statisticalIndicators === 1) {
                Aname = this.$t('800202')
                Bname = this.$t('800203')
                arrx = [this.$t('800202'), this.$t('800203')]
            } else {
                Aname = this.$t('900328')
                Bname = this.$t('8000027')
                arrx = [this.$t('900328'), this.$t('8000027')]
            }
            this.echartObj = echarts.init(document.getElementById('main'))
            this.echartObj.clear()
            var option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                legend: {
                    data: arrx
                },
                // title: {
                //   text: this.$t('800204')
                // },
                tooltip: {
                    trigger: 'axis'
                },
                calculable: true,
                xAxis: [{
                    type: 'category',
                    data: C,
                    axisLabel: {
                        interval: 0,
                        rotate: 50
                    }
                }],
                yAxis: [{
                    type: 'value'
                }],
                series: [{
                    name: Aname,
                    type: 'bar',
                    barMaxWidth: 70,
                    data: A,
                    markLine: {
                        data: [
                            { yAxis: this.line_value }
                        ]
                    }
                },
                {
                    name: Bname,
                    type: 'bar',
                    barMaxWidth: 70,
                    data: B
                }
                ]
            }
            this.echartObj.setOption(option)
        },
        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')
            })
        }
    }
}
</script>
<style lang="less" scoped>
  .conditionborder {
    right: 0px;
    bottom: -11px;
  }
</style>
