<template>
    <div>
        <el-form :inline="true" :model="ruleForm" class="demo-form-inline">
            <el-form-item>
                <Area @click="handleNodeClick" ref="area"></Area>
            </el-form-item>
            <el-form-item label="	终端名称:">
                <el-input v-model="ruleForm.name" clearable placeholder="请输入终端名称"></el-input>
            </el-form-item>
            <el-form-item label="生产厂家:">
                <el-select
                    v-model="ruleForm.manufacture"
                    placeholder="请选择生产厂家"
                    multiple
                    collapse-tags
                    clearable
                    class="select"
                >
                    <el-option
                        v-for="item in manufactorList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="检测结果:">
                <el-select v-model="ruleForm.testResults" placeholder="请选择检测结果" clearable class="select">
                    <el-option
                        v-for="item in testResultsList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="ml10" icon="el-icon-search" @click="Monitoring">查询</el-button>

                <el-button type="primary" icon="el-icon-download" @click="exportEvent">导出</el-button>
            </el-form-item>
            <el-form-item>
                <el-form-item>
                    <el-button @click="UploadDetection" type="primary" icon="el-icon-upload2">上传检测报告</el-button>
                </el-form-item>
            </el-form-item>
        </el-form>

        <vxe-table
            :data="totalData"
            :height="height"
            border
            :row-config="{ isCurrent: true, isHover: true }"
            size="mini"
            ref="Monitoringpoint"
            style="width: 100%"
            v-loading="isLoading"
            header-cell-class-name="table_header"
            @checkbox-change="handleSelectionChange"
        >
            <vxe-table-column align="center" type="checkbox" width="55"></vxe-table-column>

            <vxe-table-column
                v-for="(item, index) in tableHeaderMonitoring"
                align="center"
                :field="item.prop"
                :title="item.label"
                :min-width="item.width"
                :key="index"
                :formatter="formFilter"
                :show-overflow="true"
            ></vxe-table-column>
            <vxe-column title="操作" width="320" align="center">
                <template #default="{ row }">
                    <el-button
                        type="primary"
                        size="mini"
                        @click="download(row, 0)"
                        icon="el-icon-download"
                        :disabled="row.originalReport == null"
                    >
                        下载原始数据报告
                    </el-button>
                    <el-button
                        type="primary"
                        size="mini"
                        @click="download(row, 1)"
                        icon="el-icon-download"
                        :disabled="row.inspectionReport == null"
                    >
                        下载检测报告
                    </el-button>
                </template>
            </vxe-column>
        </vxe-table>
        <el-pagination
            background
            align="right"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="ruleForm.pageNum"
            :page-sizes="[20, 30, 40, 50, 100]"
            :page-size="ruleForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="mt10"
        ></el-pagination>
        <el-dialog
            :close-on-click-modal="false"
            :title="titles"
            :visible.sync="showBatchUpload"
            width="30%"
            :before-close="handleClose"
        >
            <el-upload
                multiple
                action="#"
                :http-request="TerminalUpload"
                :limit="999"
                accept="doc"
                :before-remove="beforeRemove"
                :before-upload="handleBeforeUpload"
                :on-error="handleUploadError"
                :file-list="fileList"
                :headers="headers"
                class="upload-file-uploader"
                ref="upload"
            >
                <el-button @click="fileType = ['doc']" type="primary" icon="el-icon-upload2">选择文件</el-button>
                <span :style="`color:#f58003`">　　(*传入的检测报告文件格式(终端编号-检测报告(yyyy-MM-dd).docx))</span>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="BatchUpload">上 传</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//   import {deptTree} from '@/api/admin/dept'
import { getTerminalPage, importReport, reportDownload } from '@/api/Process-supervision/Terminaldetection/index.js'

import Area from '@/views/components/Area/Area.vue'
import { dicData } from '@/assets/commjs/dictypeData'
export default {
    components: { Area },
    data() {
        return {
            headers: {
                Authorization: window.sessionStorage.getItem('cntoken')
            }, // 设置上传的请求头部
            vh: '',
            title: '',
            // 查询数据
            titles: '',
            ruleForm: {
                name: '',
                type: 1,
                id: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
                manufacture: [],
                testResults: '',
                pageNum: 1,
                pageSize: 20
            },
            total: 0,
            height: null,
            isLoading: false,

            multipleSelection: [],
            testResultsList: [
                {
                    id: 0,
                    name: '未展开'
                },
                {
                    id: 1,
                    name: '已展开'
                }
            ],
            fileList: [],
            fileType: [],
            uploadType: '',
            showBatchUpload: false,
            manufactorList: [],
            //台区台账表头
            tableHeaderMonitoring: [
                { prop: 'id', label: '终端编号', width: 120 },
                { prop: 'name', label: '上产厂家', width: 180 },
                { prop: 'orgName', label: '安装位置', width: 150 },
                { prop: 'inspectionUnit', label: '送检单位', width: 150 },
                { prop: 'testResults', label: '检测结果', width: 120 },
                { prop: 'nextInspectionTime', label: '下次监测时间', width: 170 }
            ],
            totalData: [],
            monitorStateList: [], //监测点状态
            monitorTypeList: [], //监测点类型
            potentialTransFormerTypeList: [], //电压互感器类型
            neutralGroundingModeList: [] //中性点接地方式
        }
    },
    created() {
        this.getclassificationData()
    },

    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.Monitoring()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.height = window.sessionStorage.getItem('appheight') - 217
        },
        //获取类型
        getclassificationData() {
            //监测点状态
            this.monitorStateList = dicData('Line_State', [])
            //监测点类型
            this.monitorTypeList = dicData('Line_Type', [])
            //电压互感器类型
            this.potentialTransFormerTypeList = dicData('Voltage_Transformer', [])
            //中性点接地方式
            this.neutralGroundingModeList = dicData('Neutral_Point', [])
            //监测点标签
            this.resultList = dicData('Monitoring_Labels', [])
            //生产厂家
            //生产厂家
            this.manufactorList = dicData('Dev_Manufacturers', [])
            this.manufactorList.forEach(item => {
                this.ruleForm.manufacture.push(item.id)
            })
        },

        //查询用户用电信息
        Monitoring() {
            getTerminalPage(this.ruleForm).then(res => {
                this.totalData = res.data.records
                this.isLoading = false
            })
        },
        // 数据过滤
        formFilter(row, column) {
            if (row.column.property == 'testResults') {
                return row.row.testResults == 0 ? '未展开' : '已展开'
            } else {
                return row.row[row.column.property]
            }
        },
        // 区域勾选
        handleNodeClick(data) {
            this.ruleForm.id = data.id
        },
        //数据上传
        upload() {
            if (this.multipleSelection.length == 0) {
                this.$message({
                    showClose: true,
                    message: '请选择台账!!!',
                    type: 'warning'
                })
                return
            }
            this.$message({
                showClose: true,
                message: '上传成功！！！',
                type: 'success'
            })
        },
        // 重置
        Reset() {
            // 查询数据
            this.ruleForm.searchValue = ''
        },

        //checkbox选择事件
        handleSelectionChange(row) {
            this.multipleSelection = row.records
        },

        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.ruleForm.pageSize = val
            this.Monitoring()
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.ruleForm.pageNum = val
            this.Monitoring()
        },
        // 上传报告
        TerminalUpload(params) {
            this.fileList.push(params.file)

            // form.append("files", params.file);
        },
        //导出
        exportEvent() {
            this.$refs.Monitoringpoint.exportData({
                filename: 'export', // 文件名字
                sheetName: 'Sheet1',
                type: 'xlsx', //导出文件类型 xlsx 和 csv
                useStyle: true,
                data: this.totalData, // 数据源 // 过滤那个字段导出 //
                columnFilterMethod: function (column, $columnIndex) {
                    return !(column.$columnIndex === 0 || column.$columnIndex === 7)
                }
            })
        },
        beforeRemove(file, fileList) {
            this.fileList = fileList
        },
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 校检文件类型
            if (this.fileType) {
                let fileExtension = ''
                if (file.name.lastIndexOf('.') > -1) {
                    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
                }
                const isTypeOk = this.fileType.some(type => {
                    if (file.type.indexOf(type) > -1) return true
                    return !!(fileExtension && fileExtension.indexOf(type) > -1)
                })
                if (!isTypeOk) {
                    this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
                    return false
                }
            }

            this.$message('正在上传文件，请稍候...')
            this.number++
            return true
        },
        // 上传检测报告
        UploadDetection() {
            this.fileType = ['doc']
            this.titles = '上传检测报告__支持批量上传'
            this.uploadType = 1
            this.showBatchUpload = true
        },
        // 关闭上传弹框
        handleClose() {
            this.fileList = []
            this.showBatchUpload = false
        },
        // 上传失败
        handleUploadError(err) {
            this.$message.error(err)
        },
        BatchUpload() {
            let form = new FormData()
            form.append('type', this.uploadType)
            this.fileList.forEach(item => {
                form.append('files', item)
            })
            importReport(form)
                .then(res => {
                    if (res.type == 'application/json') {
                        this.$message({
                            message: '上传成功!',
                            type: 'success'
                        })
                        this.handleClose()
                        this.Monitoring()
                    } else {
                        this.$message({
                            message: '上传失败!',
                            type: 'error'
                        })
                    }
                })
                .catch(response => {
                    // console.log(response);
                })
        },
        // 下载报告
        download(row, type) {
            reportDownload({
                id: row.id,
                type: type
            }).then(res => {
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
                })

                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = type == 1 ? row.inspectionName : row.originalName // 设置下载的文件名
                document.body.appendChild(link)
                link.click() //执行下载
                document.bodyNaNpxoveChild(link)
            })
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../styles/comStyle.less');
::v-deep .vxe-table .cell {
    text-align: center;
}
::v-deep .el-tabs--border-card > .el-tabs__content {
    padding: 0;
}

.pms {
    margin-left: 10px;
}
.obtain {
    margin-left: 1220px;
}
</style>
