<template>
    <div class="testdiv">
        <div class="divborder">
            <div>
                <div class="filter">
                    <label v-text="$t('1132')">产线层级</label>:
                    <Cascader :data="datalevel" :value="leveldata" :render-format="format"  trigger="click" @on-change="levelchange" change-on-select style="display:inline-block;width:200px;" ></Cascader>
                </div>
                <div class="filter">
                    <label v-text="$t('1129')">横坐标</label>:
                    <Select v-model="Abscissa" label-in-value clearable style="width:160px;" >
                        <Option  :value="1" v-text="$t('1101')">天</Option>
                        <Option  :value="2" v-text="$t('1136')">周</Option>
                        <Option  :value="3" v-text="$t('1138')">月</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label v-text="$t('1031')">父级设备类型</label>:
                    <Select v-model="ftype" label-in-value @on-change="ftypechange" clearable style="width:160px;" >
                        <Option v-for="item in ftypelist" :value="item.id" :key="item.id">{{ item.title }}</Option>
                    </Select>
                </div>

            </div>
            <!-- 次级搜索条件 隐藏 -->
                <div v-show="!morecondition">
                <div >
                    <div class="filter">
                        <label v-text="$t('1032')">子级设备类型</label>:
                        <Select v-model="ctype" label-in-value @on-change="ctypechange" clearable style="width:200px;" >
                            <Option v-for="item in ctypelist" :value="item.id" :key="item.id">{{ item.title }}</Option>
                        </Select>
                    </div>
                    <div class="filter">
                        <label v-text="$t('200005')">故障类型</label>:
                        <Select v-model="fault_type" label-in-value @on-change="faulttypechange" clearable style="width:160px;" >
                            <Option v-for="(item,key) in fault_typelist" :value="item.listid" :key="key">{{ item.faulttype }}</Option>
                        </Select>
                    </div>
                    <div class="filter">
                        <label v-text="$t('200022')">失效模式</label>:
                        <Select v-model="failure_mode" label-in-value  clearable style="width:160px;" >
                            <Option v-for="(item,key) in failure_modelist" :value="item.id" :key="item.key">{{ item.title }}</Option>
                        </Select>
                    </div>
                </div>
                <div>
                    <div class="filter">
                        <label v-text="$t('200178')">是否停机</label>:
                        <Select v-model="Shutdown" label-in-value  clearable style="width:200px;" >
                            <Option  :value="1" v-text="$t('1000020')">是</Option>
                            <Option  :value="0" v-text="$t('1000021')">否</Option>
                        </Select>
                    </div>
                    <div class="filter">
                        <label v-text="$t('900908')">时间范围</label>:
                        <DatePicker type="datetimerange" format="yyyy-MM-dd HH:mm:ss" v-model="index_time"  style="width: 300px"></DatePicker>
                    </div>
                </div>
                <div>
                    <div class="filter" style="width:273px;">
                        <Checkbox v-model="single1"   size="large">MTTR</Checkbox>
                        <Checkbox v-model="single2"  size="large">MTBF</Checkbox>
                    </div>
                </div>
                <div>

                </div>
                </div>
                <!-- 次级搜索条件  结束 -->
                <div class="buttonall">
                    <Button type="primary" icon="ios-search" @click="search()" v-text="$t('1001')">查询</Button>
                    <Button type="primary" icon="md-download" @click="downpdf()">{{$t('900741')}}</Button>
                </div>
                <div class="conditionblock">
                    <div class="conditionborder" @click="changecondition">
                        <div class="box">
                        <div class="skew">
                        <div class="skew-main">
                            <div v-show="morecondition">
                                <span v-text="$t('950400')" >更多条件<Icon type="ios-arrow-down" /></span>
                            </div>
                            <div v-show="!morecondition">
                                <span v-text="$t('950401')">收起条件<Icon type="ios-arrow-up" /></span>
                            </div>
                        </div>
                        </div>
                    </div>
                    </div>
                </div>
        </div>
        <div class="divborder" style="" v-show="detail">
           <div id="demo">
                <div v-show="mttrshow">
                    <div style="text-align:right;padding-right:100px;padding-top:15px;" >
                    <span v-text="$t('900780')" data-i18n="900780">目标</span>
                    <input type="text" style="width: 50px; cursor:pointer" name="mttrs" v-model="num1">
                    <span v-text="$t('200028')">分钟</span>
                    <Button type="primary" size="small" @click="mttr" v-text="$t('1011')">确定</Button>
                    <!-- <span style="cursor:pointer" class="button operation_btn" id="mttrBtn" data-i18n="1011">确定</span> -->
                </div>
                <div id="mttr" style="height: 280px;margin-top: 10px;"></div>
                <div style="display:inline-block;margin-right:80px;">{{$t('1035')}}{{time}}</div>
                <div style="display:inline-block">{{$t('1031')}}:{{linetext}}</div>
                <Table
                    style="margin-top:10px"
                    highlight-row
                    :data="tableData1"
                    :columns="tableColumns1"
                    max-height="300px"
                    ></Table>
                </div>
                <div v-show="mtbfshow">
                    <div style="text-align:right;padding-right:100px;padding-top:15px;" >
                    <span v-text="$t('900780')">目标</span>
                    <input type="text" style="width: 50px; cursor:pointer" name="mttrs" v-model="num2">
                    <span v-text="$t('200028')" >分钟</span>
                    <Button type="primary" size="small" @click="mtbf" v-text="$t('1011')">确定</Button>
                    <!-- <span style="cursor:pointer" class="button operation_btn" id="mttrBtn" data-i18n="1011">确定</span> -->
                </div>
                <div id="mtbf" style="height: 280px;margin-top: 10px;"></div>
                <div style="display:inline-block;margin-right:80px;">{{$t('1035')}}{{time}}</div>
                <div style="display:inline-block">{{$t('1031')}}:{{linetext}}</div>
                <Table
                    style="margin-top:10px"
                    highlight-row
                    :data="tableData2"
                    :columns="tableColumns2"
                    max-height="300px"
                    ></Table>
                </div>
           </div>
        </div>
    </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
require('echarts/dist/extension/dataTool.js')
export default {
    data () {
        return {
            datalevel: [], // 产线层级数据
            leveldata: [], // 产线层级value
            ftype: '', // 父级设备类型value
            ftypelist: [], // 父级设备类型数据
            ctype: '', // 子级设备类型value
            ctypelist: [], // 子级设备类型数据
            linetext: '', // 产线层级label
            morecondition: false,
            Shutdown: '', // 是否停机
            fault_type: '', // 故障类型value
            fault_typelist: [], // 故障类型数据
            failure_mode: '', // 失效模式
            failure_modelist: [], // 失效模式数据
            Abscissa: '', // 横坐标
            single1: true, // mttr
            single2: true, // mtbf
            time: '', // 列表上方时间
            linetext: '', // 列表上方产线label
            mttrshow: false,
            mtbfshow: false,
            detail: false,
            num1: 20,
            num2: 20,
            tableData1: [], // mttr
            tableData2: [], // mtbf
            tableColumns1: [ // mttr
                {
                    type: 'index2',
                    title: this.$t('1008'), // 序号
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + 1)
                    },
                    width: 60
                },
                {
                    title: this.$t('600532'), // 日期
                    key: 'date'
                },
                {
                    title: this.$t('900337'), // 工单号
                    key: 'work_order'
                },
                {
                    title: this.$t('200038'), // 工位名称
                    key: 'station_name'
                },
                {
                    title: this.$t('200022'), // 失效模式
                    key: 'failure_mode'
                },
                {
                    title: this.$t('1030'), // 备注
                    key: 'remark'
                },
                {
                    title: this.$t('200008'), // 故障描述
                    key: 'Fault_description'
                },
                {
                    title: this.$t('200009'), // 维修排查过程
                    key: 'during'
                },
                {
                    title: this.$t('200010'), // 故障原因
                    key: 'reason'
                },
                {
                    title: this.$t('200011'), // 所用备件
                    key: 'spare_part'
                },
                {
                    title: this.$t('200012'), // 报修时间
                    key: 'report_time'
                },
                {
                    title: this.$t('200041'), // 维修用时
                    key: 'repair_time'
                },
                {
                    title: this.$t('200023'), // 维修人
                    key: 'repair_user'
                }
            ],
            tableColumns2: [
                {
                    type: 'index2',
                    title: this.$t('1008'), // 序号
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + 1)
                    },
                    width: 60
                },
                {
                    title: this.$t('600532'), // 日期
                    key: 'date'
                },
                {
                    title: this.$t('200038'), // 工位名称
                    key: 'station_name'
                },
                {
                    title: 'MTBF',
                    key: 'MTBF'
                }
            ]
        }
    },
    created () {
        this.initlevel()
        this.initftype()
        this.index_time = [moment(new Date().getTime() - 3600 * 1000 * 24 * 14).format('YYYY-MM-DD ') + '00:00:00', moment(new Date().getTime() - 3600 * 1000 * 24 * 1).format('YYYY-MM-DD ') + '23:59:59']
    },
    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
                    arr.push(res.data.data[0].value)
                    this.leveldata = arr
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        levelchange (value) {
            this.leveldata = value
        },
        initftype () {
            this.axios.request({
                url: '/config/MachineType/GetEditDcategory',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.ftypelist = res.data.data
                } else {
                    this.$Message.error(res.data.mag)
                }
            })
        },
        ftypechange () {
            this.ctype = ''
            this.fault_type = ''
            this.failure_mode = ''
            this.axios.request({
                url: '/config/MachineType/GetLastMachineType?id=' + this.ftype,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.ctypelist = res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        ctypechange () { // 子级设备类型变化
            this.fault_type = ''
            this.failure_mode = ''
            let params = {
                machinetypeid: this.ctype
            }
            this.axios.request({
                url: '/tpm/FaultType/GetFaultTypeList',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.fault_typelist = res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        faulttypechange (id) { // 故障类型变化
            this.failure_mode = ''
            let params = {
                faultTypeId: this.fault_type
            }
            this.axios.request({
                url: '/tpm/FaultType/GetInvalidModesByTypeId',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.failure_modelist = res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        format (labels, selectedData) {
            // const index = labels.length - 1
            this.linetext = labels.join(' / ')
            var label = labels.join(' / ')
            return label
        },
        changecondition () {
            this.morecondition = !this.morecondition
        },
        search () {
            if (this.Abscissa == '') {
                this.$Message.error(this.$t('500133'))
                return false
            }
            this.mttrshow = false
            this.mtbfshow = false
            this.time = moment(this.index_time[0]).format('YYYY-MM-DD HH:mm:ss ') + moment(this.index_time[1]).format('YYYY-MM-DD HH:mm:ss')
            if (this.index_time.length === 0) {
                this.$Message.error(this.$t('1143'))
                return false
            }
            if (this.single1) {
                this.mttrshow = true
                this.mttr()
            }
            if (this.single2) {
                this.mtbfshow = true
                this.mtbf()
            }
            if (!this.single1 && !this.single2) {
                this.$Message.error(this.$t('1014') + '(MTTR/MTBF)')
                return false
            } else {
                this.detail = true
            }
        },
        mttr () {
            var data = {
                level_id: this.leveldata[this.leveldata.length - 1],
                type_id: this.ftype,
                concrete_id: this.ctype,
                faulttype_id: this.fault_type,
                fault_id: this.failure_mode,
                starttime: moment(this.index_time[0]).format('YYYY-MM-DD HH:mm:ss'),
                endtime: moment(this.index_time[1]).format('YYYY-MM-DD HH:mm:ss'),
                offlinestatus: this.Shutdown,
                x_id: this.Abscissa,
                target: this.num1
            }
            this.axios.request({
                url: '/tpm/Statistics/repairDataTrendMTTR',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret == 1) {
                    this.echartMTTR(res.data.data.x, res.data.data.y1)
                    this.mockTableData1(res.data.data.y2)
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        mtbf () {
            var data = {
                level_id: this.leveldata[this.leveldata.length - 1],
                type_id: this.ftype,
                concrete_id: this.ctype,
                faulttype_id: this.fault_type,
                fault_id: this.failure_mode,
                starttime: moment(this.index_time[0]).format('YYYY-MM-DD HH:mm:ss'),
                endtime: moment(this.index_time[1]).format('YYYY-MM-DD HH:mm:ss'),
                offlinestatus: this.Shutdown,
                x_id: this.Abscissa,
                target: this.num2

            }
            this.axios.request({
                url: '/tpm/Statistics/repairDataTrendMTBF',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.echartMTBF(res.data.data.x, res.data.data.y1)
                    this.mockTableData2(res.data.data.y2)
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },

        echartMTTR (xdata, sData) {
            var myChart_mttr
            if (myChart_mttr != null && myChart_mttr != '' && myChart_mttr != undefined) {
                myChart_mttr.dispose()
            }
            myChart_mttr = echarts.init(document.getElementById('mttr'))
            var option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xdata
                    }
                ],
                yAxis: [
                    { name: 'MTTR',
                        type: 'value',
                        nameTextStyle: {
                            fontSize: 16
                        }
                    }
                ],
                series: [
                    { itemStyle: {
                        normal: {
                            color: '#c23531'
                        }
                    },
                    name: 'MTTR',
                    type: 'bar',
                    barMaxWidth: 70,
                    data: sData,
                    markLine: {
                        data: [
                            { yAxis: Number(this.num1) }
                        ]
                    }
                    }
                ]
            }
            myChart_mttr.setOption(option)
        },
        echartMTBF (xdata, linedata) {
            var myChart_mtbf
            if (myChart_mtbf != null && myChart_mtbf != '' && myChart_mtbf != undefined) {
                myChart_mtbf.dispose()
            }
            myChart_mtbf = echarts.init(document.getElementById('mtbf'))
            var option = {
                title: {
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xdata,
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    { name: 'MTBF',
                        type: 'value',
                        nameTextStyle: {
                            fontSize: 16
                        }
                    }
                ],
                series: [
                    { itemStyle: {
                        normal: {
                            color: '#c23531'
                        }
                    },
                    name: 'MTBF',
                    type: 'bar',
                    barMaxWidth: 70,
                    barWidth: '60%',
                    data: linedata,
                    markLine: {
                        data: [
                            { yAxis: Number(this.num2) }
                        ]
                    }
                    }
                ]
            }
            myChart_mtbf.setOption(option)
        },
        // 渲染列表1开始
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        date: item.date,
                        work_order: item.id,
                        station_name: item.levelname,
                        failure_mode: fault_content,
                        remark: item.remark,
                        Fault_description: item.fault_description,
                        during: item.repair_process,
                        reason: item.real_faultid_desc,
                        spare_part: item.sparepart,
                        report_time: item.reporttime,
                        repair_time: item.repairtime,
                        repair_user: item.name
                    })
                }
            })
            this.tableData1 = data
        },
        // 渲染列表2开始
        mockTableData2 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        date: item.time,
                        station_name: item.location,
                        MTBF: item.mtbf
                    })
                }
            })
            this.tableData1 = data
        },
        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>

</style>
