<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="onSubmit">查询</el-button>

                <el-button type="primary" icon="el-icon-download" @click="exportEvent">导出</el-button>
            </el-form-item>
            <el-form-item>
                <el-upload
                    action="#"
                    :http-request="upAndDowndoad"
                    :before-upload="handleBeforeUpload"
                    :on-error="handleUploadError"
                    :on-success="handleUploadSuccess"
                    :show-file-list="false"
                    :headers="headers"
                    accept="xls"
                    class="upload-file-uploader"
                    ref="upload"
                >
                    <el-button @click="fileType = ['xls']" type="primary" icon="el-icon-folder-opened">
                        excel导入
                    </el-button>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="UploadOriginal" icon="el-icon-upload2">上传原始报告</el-button>
            </el-form-item>
        </el-form>

        <div class="mb10">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addFn">新增</el-button>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="modifyFn">修改</el-button>
            <el-button type="primary" size="mini" icon="el-icon-delete" @click="deleteFn">删除</el-button>
            <el-button type="primary" size="mini" icon="el-icon-download" @click="DownloadTemplate">下载模板</el-button>
        </div>
        <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>
        <newlyIncreased
            :title="title"
            v-if="dialogVisible"
            :list="list"
            @onSubmit="onSubmit"
            @handleClose="dialogVisible = false"
        />
        <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"
                :on-success="handleUploadSuccess"
                :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`">　　(*传入的原始数据文件格式(终端编号-原始数据报告.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,
    DownloadExport,
    delTerminal,
    reportDownload,
    batchTerminal,
    importReport
} from '@/api/Process-supervision/Terminaldetection/index.js'
import Area from '@/views/components/Area/Area.vue'
import { dicData } from '@/assets/commjs/dictypeData'
import newlyIncreased from './newlyIncreased'
export default {
    components: { Area, newlyIncreased },
    data() {
        return {
            WordColor: JSON.parse(window.localStorage.echartsColor).WordColor,
            excelUrl: '/api/process-boot/process/pmsTerminalDetection/batchTerminal', // 请求地址
            headers: {
                Authorization: window.sessionStorage.getItem('cntoken')
            }, // 设置上传的请求头部
            showBatchUpload: false,
            vh: '',
            title: '',
            titles: '',
            // 查询数据
            ruleForm: {
                name: '',
                type: 0,
                id: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
                manufacture: [],
                testResults: '',
                pageNum: 1,
                pageSize: 20
            },
            fileList: [],
            fileType: [],
            list: [],
            total: 0,
            height: null,
            isLoading: false,
            dialogVisible: false,
            multipleSelection: [],
            testResultsList: [
                {
                    id: 0,
                    name: '未展开'
                },
                {
                    id: 1,
                    name: '已展开'
                }
            ],
            uploadType: '',
            manufactorList: [],
            //台区台账表头
            tableHeaderMonitoring: [
                { prop: 'orgName', label: '所属单位', width: 120 },
                { prop: 'id', label: '终端编号', width: 120 },
                { prop: 'name', label: '终端名称', width: 120 },
                { prop: 'manufacture', label: '生产厂家', width: 180 },
                { prop: 'installPlace', label: '安装位置', width: 150 },
                { prop: 'inspectionUnit', label: '送检单位', width: 150 },
                { prop: 'testResults', label: '检测结果', width: 120 },
                { prop: 'inspectionTime', label: '检测时间', width: 150 },
                { prop: 'nextInspectionTime', label: '下次检测时间', width: 150 }
            ],
            totalData: [],
            monitorStateList: [], //监测点状态
            monitorTypeList: [], //监测点类型
            potentialTransFormerTypeList: [], //电压互感器类型
            neutralGroundingModeList: [] //中性点接地方式
        }
    },
    created() {},

    mounted() {
        this.getclassificationData()

        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.onSubmit()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.height = window.sessionStorage.getItem('appheight') - 252
        },
        //获取类型
        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)
            })
        },

        //查询用户用电信息
        onSubmit() {
            getTerminalPage(this.ruleForm).then(res => {
                this.totalData = res.data.records
                this.total = res.data.total
                this.isLoading = false
            })
        },
        // 数据过滤
        formFilter(row, column) {
            if (row.column.property == 'testResults') {
                return row.row.testResults == 0 ? '未展开' : '已展开'
            }
            if (row.column.property == 'manufacture') {
                let title = ''
                this.manufactorList.forEach(item => {
                    if (item.value == row.row.manufacture) {
                        title = item.label
                    }
                })
                return title
            } else {
                return row.row[row.column.property]
            }
        },
        // 区域勾选
        handleNodeClick(data) {
            this.ruleForm.id = data.id
        },
        // 下载报告
        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)
            })
        },
        // excl导入
        leadingIn() {},
        //数据上传
        upload() {
            if (this.multipleSelection.length == 0) {
                this.$message({
                    showClose: true,
                    message: '请选择台账!!!',
                    type: 'warning'
                })
                return
            }
            this.$message({
                showClose: true,
                message: '上传成功！！！',
                type: 'success'
            })
        },
        // 下载模板
        DownloadTemplate() {
            DownloadExport().then(res => {
                let blob = new Blob([res], {
                    type: 'application/vnd.ms-excel'
                })

                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = '终端入网检测录入模板' // 设置下载的文件名
                document.body.appendChild(link)
                link.click() //执行下载
                document.bodyNaNpxoveChild(link)
            })
        },
        //新增
        addFn(e) {
            this.title = '新增'
            this.dialogVisible = true
        },

        //修改数据
        modifyFn() {
            if (this.multipleSelection.length == 1) {
                this.title = '修改'
                this.list = this.multipleSelection[0]
                this.dialogVisible = true
            } else {
                this.$message({
                    message: '请选择1条数据进行修改!',
                    type: 'warning'
                })
            }
        },

        // 删除
        deleteFn() {
            if (this.multipleSelection.length > 0) {
                let list = []
                this.multipleSelection.forEach(item => {
                    list.push(item.id)
                })
                delTerminal(list).then(res => {
                    if (res.code == 'A0000') {
                        this.$message({
                            message: '删除成功!',
                            type: 'success'
                        })
                        this.onSubmit()
                    }
                })
            } else {
                this.$message({
                    message: '请选择1条数据进行删除!',
                    type: 'warning'
                })
            }
        },

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

        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.ruleForm.pageSize = val
            this.onSubmit()
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.ruleForm.pageNum = val
            this.onSubmit()
        },

        //导出
        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 === 10)
                }
            })
        },
        // 上传前校检格式和大小
        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
        },
        // 上传失败
        handleUploadError(err) {
            this.$message.error(err)
        },
        // 导出 excl
        upAndDowndoad(params) {
            // 获取文件 通过FormData将文件转化为二进制流的形式传给后端
            let form = new FormData()
            form.append('file', params.file)
            batchTerminal(form).then(res => {
                if (res.type == 'application/json') {
                    this.$message({
                        message: '上传成功,无错误数据!',
                        type: 'success'
                    })
                    this.onSubmit()
                } else {
                    this.onSubmit()
                    this.$message({
                        message: '上传成功,有错误数据  自动下载 请查看',
                        type: 'warning'
                    })
                    let blob = new Blob([res], {
                        type: 'application/vnd.ms-excel'
                    })
                    const url = window.URL.createObjectURL(blob)
                    const link = document.createElement('a') // 创建a标签
                    link.href = url
                    link.download = '模板错误信息' // 设置下载的文件名
                    document.body.appendChild(link)
                    link.click() //执行下载
                    document.bodyNaNpxoveChild(link)
                }
            })
        },
        // 上传报告
        TerminalUpload(params) {
            this.fileList.push(params.file)

            // form.append("files", params.file);
        },
        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.onSubmit()
                    } else {
                        this.$message({
                            message: '上传失败!',
                            type: 'error'
                        })
                    }
                })
                .catch(response => {
                    // console.log(response);
                })
        },
        // 上传成功回调
        handleUploadSuccess(res) {},
        // 上传原始报告
        UploadOriginal() {
            this.fileType = ['doc']
            this.titles = '上传原始报告__支持批量上传'
            this.uploadType = 0
            this.showBatchUpload = true
        },

        // 关闭上传弹框
        handleClose() {
            this.fileList = []
            this.showBatchUpload = false
        },
        beforeRemove(file, fileList) {
            this.fileList = fileList
        }
    }
}
</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: 0.625rem;
}
.obtain {
    margin-left: 76.25rem;
}
</style>
