<template>
    <div class="pd10">
        <el-button type="primary" icon="el-icon-top" @click="newlyAdded">上传资源</el-button>
        <el-button type="primary" icon="el-icon-bottom" @click="exportEvent">导出</el-button>
        <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="基本资源(推荐)" name="1">
                <vxe-table
                    align="center"
                    size="mini"
                    :height="vh"
                    ref="Monitoringpoint"
                    border
                    :data="BasicResource"
                    header-cell-class-name="table_header"
                    :row-config="{ isCurrent: true, isHover: true }"
                >
                    <vxe-table-column
                        min-width="200px"
                        field="description"
                        title="资源类目"
                        :formatter="formFilter"
                    ></vxe-table-column>
                    <vxe-table-column min-width="200px" field="name" title="资源名称"></vxe-table-column>
                    <vxe-table-column min-width="200px" field="description" title="资源描述"></vxe-table-column>
                    <vxe-table-column min-width="250px" title="资源下载">
                        <template v-slot="{ row }">
                            <el-button size="mini" type="primary" icon="el-icon-bottom" @click="DownloadFiles(row)">
                                下载文件
                            </el-button>
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="modify(row)">
                                修改
                            </el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteFile(row)">
                                删除
                            </el-button>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </el-collapse-item>
            <el-collapse-item title="报告发布" name="2">
                <vxe-table
                    align="center"
                    size="mini"
                    :height="vh"
                    border
                    :data="ReportIssue"
                    header-cell-class-name="table_header"
                    :row-config="{ isCurrent: true, isHover: true }"
                >
                    <vxe-table-column
                        min-width="200px"
                        field="type"
                        title="资源类目"
                        :formatter="formFilter"
                    ></vxe-table-column>
                    <vxe-table-column min-width="200px" field="name" title="资源名称"></vxe-table-column>
                    <vxe-table-column min-width="200px" field="description" title="资源描述"></vxe-table-column>
                    <vxe-table-column min-width="250px" title="资源下载">
                        <template v-slot="{ row }">
                            <el-button size="mini" type="primary" icon="el-icon-bottom" @click="DownloadFiles(row)">
                                下载文件
                            </el-button>
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="modify(row)">
                                修改
                            </el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteFile(row)">
                                删除
                            </el-button>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </el-collapse-item>
            <el-collapse-item title="辅助资源" name="3">
                <vxe-table
                    align="center"
                    size="mini"
                    :height="vh"
                    border
                    :data="AssistResource"
                    header-cell-class-name="table_header"
                    :row-config="{ isCurrent: true, isHover: true }"
                >
                    <vxe-table-column
                        min-width="200px"
                        field="type"
                        title="资源类目"
                        :formatter="formFilter"
                    ></vxe-table-column>
                    <vxe-table-column min-width="200px" field="name" title="资源名称"></vxe-table-column>
                    <vxe-table-column min-width="200px" field="description" title="资源描述"></vxe-table-column>
                    <vxe-table-column min-width="250px" title="资源下载">
                        <template v-slot="{ row }">
                            <el-button size="mini" type="primary" icon="el-icon-bottom" @click="DownloadFiles(row)">
                                下载文件
                            </el-button>
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="modify(row)">
                                修改
                            </el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteFile(row)">
                                删除
                            </el-button>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </el-collapse-item>
        </el-collapse>
        <el-dialog
            :close-on-click-modal="false"
            :title="title"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
        >
            <el-form ref="form" :rules="rules" :model="form" label-width="110px">
                <el-form-item label="资源名称:" prop="name">
                    <el-input style="width: 100%" v-model="form.name" placeholder="请输入资源名称" clearable></el-input>
                </el-form-item>

                <el-form-item label="资源类型:" prop="type" class="top">
                    <el-select v-model="form.type" placeholder="请选择资源类型" clearable style="width: 100%">
                        <el-option
                            v-for="item in Category"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="资源描述:" prop="description" class="top">
                    <el-input
                        style="width: 100%"
                        v-model="form.description"
                        type="textarea"
                        placeholder="请输入资源描述"
                        clearable
                    ></el-input>
                </el-form-item>
                <el-form-item class="top" label="上传资源:" style="text-overflow: ellipsis" prop="fileList">
                    <el-upload
                        class="upload-demo"
                        action="#"
                        :on-remove="beforeRemove"
                        :http-request="upload"
                        multiple
                        :limit="1"
                        :on-preview="preview"
                        :on-exceed="handleExceed"
                        :file-list="form.fileList"
                        accept=".docx,.doc,.xlsx"
                    >
                        <el-button size="small" type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="onsubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { queryData, uploadFile, deleteFile, downloadFile, updateFile } from '@/api/templateConfiguration'
import { dicData } from '@/assets/commjs/dictypeData'
export default {
    name: 'resourcemage',
    components: {},
    data() {
        return {
            flag: true,
            title: '',
            vh: undefined,
            activeName: 'first',
            device: '',
            activeName: '1',
            BasicResource: [],
            AssistResource: [],
            ReportIssue: [],

            Category: [],
            dialogVisible: false,
            form: {
                fileList: [],
                name: '',
                type: '',
                multipartFile: '',
                description: ''
            },
            rules: {
                name: [{ required: true, message: '请输入资源名', trigger: 'blur' }],
                fileList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
                description: [{ required: true, message: '请输入资源描述', trigger: 'blur' }],
                type: [{ required: true, message: '请选择资源类型', trigger: 'change' }]
            }
        }
    },
    created() {},
    mounted() {
        this.device = window.devicePixelRatio
        this.Category = dicData('Resource_Category', [])

        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.info()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 215 + 'px'
        },
        // 表单重置
        resetForm() {
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },
        info() {
            ;(this.BasicResource = []),
                (this.ReportIssue = []),
                (this.AssistResource = []),
                queryData({}).then(res => {
                    this.Category.forEach(val => {
                        res.data.forEach(item => {
                            if (val.id == item.type) {
                                if (val.code == 'base_resource') {
                                    // 基本资源
                                    this.BasicResource.push(item)
                                } else if (val.code == 'report_fa_resource') {
                                    // 报告发布
                                    this.ReportIssue.push(item)
                                } else if (val.code == 'help_resource') {
                                    // "辅助资源"
                                    this.AssistResource.push(item)
                                }
                            }
                        })
                    })
                })
        },
        handleClose() {
            this.dialogVisible = false
            this.form = {
                fileList: [],
                name: '',
                type: '',
                multipartFile: '',
                description: ''
            }
            this.resetForm()
        },
        //文件上传
        upload(params) {
            this.form.fileList.push(params.file)
        },
        handleExceed(files, fileList) {
            this.$message.warning(`只能上传1个文件`)
        },
        beforeRemove(file, fileList) {
            this.form.fileList = []
        },
        // 点击上传文件
        async preview(file) {
            let res = null
            if (this.form.fileList[0].url) {
                await downloadFile({ id: this.form.id }).then(val => {
                    res = val
                })
            } else {
                res = file
            }

            let blob = new Blob([res], {
                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
            })
            // createObjectURL(blob); //创建下载的链接
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a') // 创建a标签
            link.href = url
            link.download = this.form.fileList[0].name // 设置下载的文件名
            document.body.appendChild(link)
            link.click() //执行下载
            document.body.removeChild(link)
        },

        // 上传资源
        onsubmit() {
            let fileName = this.fileList[0].name
            let pos = fileName.lastIndexOf('.')
            let includes = fileName.substring(pos, fileName.length)
            console.log(includes)
            let fileLastArr = [".doc",".docx",".xls",".xlsx"]
            if (!fileLastArr.includes(includes)) {
                this.$message.error('当前不支持该格式文件')
                return false;
            }

            this.$refs['form'].validate(valid => {
                if (valid) {
                    let form = new FormData()
                    form.append('name', this.form.name)
                    form.append('type', this.form.type)
                    form.append('description', this.form.description)
                    if (this.form.fileList[0].url) {
                        form.append('multipartFile', '')
                    } else {
                        this.form.fileList.forEach(item => {
                            form.append('multipartFile', item)
                        })
                    }

                    if (this.title == '上传资源') {
                        uploadFile(form).then(res => {
                            if (res.code == 'A0000') {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                })
                                this.info()
                                this.handleClose()
                            }
                        })
                    } else if (this.title == '修改资源') {
                        form.append('id', this.form.id)

                        updateFile(form).then(res => {
                            if (res.code == 'A0000') {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                })
                                this.info()
                                this.handleClose()
                            }
                        })
                    }
                } else {
                    // console.log("error submit!!");
                    return false
                }
            })
        },
        // 删除
        deleteFile(row) {
            deleteFile({
                id: row.id
            }).then(res => {
                if (res.code == 'A0000') {
                    this.$message({
                        message: '删除成功!',
                        type: 'success'
                    })
                    this.info()
                }
            })
        },
        //上传资源
        newlyAdded() {
            this.title = '上传资源'
            this.dialogVisible = true
        },
        // 修改
        modify(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.form.fileList = [
                {
                    url: row.url,
                    name: row.fileName
                }
            ]
            this.title = '修改资源'
            this.dialogVisible = true
        },
        // 导出
        exportEvent() {
            this.$refs.Monitoringpoint.exportData({
                filename: '资源管理', // 文件名字
                sheetName: 'Sheet1',
                type: 'xlsx', //导出文件类型 xlsx 和 csv
                useStyle: true,
                // BasicResource: [],
                // AssistResource: [],
                // ReportIssue: [],
                data: [...this.BasicResource, ...this.AssistResource, ...this.ReportIssue], // 数据源 // 过滤那个字段导出
                columnFilterMethod: function (column, $columnIndex) {
                    return !(column.$columnIndex === 3)
                }
            })
        },
        // 数据过滤
        formFilter(row, column) {
            let title = ''
            this.Category.forEach(item => {
                if (item.id == row.row.type) {
                    title = item.name
                }
            })

            return title
        },
        DownloadFiles(row) {
            downloadFile({ id: row.id }).then(res => {
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
                })
                // createObjectURL(blob); //创建下载的链接
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = row.fileName // 设置下载的文件名
                document.body.appendChild(link)
                link.click() //执行下载
                document.body.removeChild(link)
            })
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../styles/comStyle.less');
::v-deep .el-table .cell {
    text-align: center;
}
::v-deep .el-tabs--border-card > .el-tabs__content {
    padding: 10px;
}
.block {
    position: absolute;
    right: 10px;

    bottom: 10px;
}
// ::v-deep .forms {
//   display: flex;
//   flex-wrap: wrap;
//   justify-content: space-between;
// .el-form-item {
//   display: flex;
//   width: 100%;
//   margin-bottom: 15px !important;
//   .el-form-item__content {
//     flex: 1 !important;
//     .el-select {
//       width: 100%;
//     }
//     .el-date-editor {
//       width: 100%;
//     }
//     .el-textarea {
//       width: 100%;
//     }
//   }
// }
//}
::v-deep .el-upload-list__item-name {
    width: 324px;
}
::v-deep .el-upload-list__item:first-child {
    margin-top: -3px;
}
</style>
