<template>
    <div class="container">
        <div v-show="menuVisible"
             id="contextmenu"
             class="menu">
            <div v-if="selectTree.type === '1'" class="contextmenu__item" @click="addTree">新增</div>
            <div v-if="selectTree.type === '2'" class="contextmenu__item" @click="updateTree">修改</div>
            <div v-if="selectTree.type === '2'" class="contextmenu__item" @click="deleteTree">删除</div>
        </div>
        <el-dialog :title="dialogData.title" :visible.sync="dialogData.show" width="500px">
            <el-form>
                <el-form-item label="数据集编码" prop="datasetCode">
                    <el-input v-model="dialogData.form.datasetCode"/>
                </el-form-item>
                <el-form-item label="数据集名称" prop="datasetName">
                    <el-input v-model="dialogData.form.datasetName"/>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button type="primary" @click="submitTree">提交</el-button>
            </div>
        </el-dialog>
        <el-row :gutter="20">
            <!--文档数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input
                        v-model="datasetName"
                        clearable
                        placeholder="请输入数据集"
                        prefix-icon="el-icon-search"
                        size="small"
                        style="margin-bottom: 20px"
                    />
                </div>
                <div class="head-container">
                    <el-scrollbar style="height: calc(100vh - 130px)">
                        <el-tree
                            ref="tree"
                            :data="docTree"
                            :expand-on-click-node="false"
                            :filter-node-method="filterNode"
                            :props="defaultProps"
                            default-expand-all
                            highlight-current
                            node-key="value"
                            @node-click="handleNodeClick"
                            @node-contextmenu="handleContextMenu">
                        </el-tree>
                    </el-scrollbar>

                </div>
            </el-col>
            <!--目录数据-->
            <el-col :span="20" :xs="24" style="overflow-y: auto;height: calc(100vh - 80px);">
                    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px"
                             size="small"
                             style="height: 40px">
                        <el-form-item label="患者ID" prop="patientId">
                            <el-input
                                v-model="queryParams.patientId"
                                clearable
                                placeholder="请输入患者ID"
                                style="width: 240px"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="患者名称" prop="patientName">
                            <el-input
                                v-model="queryParams.patientName"
                                clearable
                                placeholder="请输入患者名称"
                                style="width: 240px"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="报告状态" prop="reportState">
                            <el-select v-model="queryParams.reportState"
                                       filterable
                                       placeholder="请选择报告状态" @change="handleQuery">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <el-date-picker
                                v-model="queryParams.creationTime"
                                end-placeholder="结束日期"
                                range-separator="-"
                                start-placeholder="开始日期"
                                style="width: 240px"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                @change="handleQuery"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button :loading="loading" icon="el-icon-search" size="mini" type="primary"
                                       @click="handleQuery">搜索
                            </el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table v-loading="loading" :data="docList" border style="width: 100%">
                        <el-table-column
                            type="index"
                            width="50">
                        </el-table-column>
                        <el-table-column label="患者ID" prop="patientId" show-overflow-tooltip
                                         width="120"></el-table-column>
                        <el-table-column label="患者名称" prop="patientName" show-overflow-tooltip
                                         width="120"></el-table-column>
                        <el-table-column :formatter="patientTypeFormatter" label="患者类型" prop="patientKind"
                                         show-overflow-tooltip width="120"/>
                        <el-table-column v-if="false" label="PDF文档类型" prop="pdfFileClassCode" show-overflow-tooltip
                                         width="120">
                            <template slot-scope="scope">{{
                                    scope.row.pdfFileClassCode === "01" ? '一般临床检验' : '血液学检验'
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column label="文档名称" prop="documentName" show-overflow-tooltip
                                         width="200"></el-table-column>
                        <el-table-column :formatter="reportStateFormatter" label="报告状态" prop="reportState" width="100"/>
                        <el-table-column label="创建时间" prop="creationTime" width="160"></el-table-column>
                        <el-table-column label="输入日期" prop="enterDate" width="160"></el-table-column>
                        <el-table-column label="更新日期" prop="uploadDate" width="160"></el-table-column>
                        <el-table-column label="体检号" prop="tjSn"/>
                        <el-table-column label="文档源地址" prop="documentAddress" show-overflow-tooltip
                                         width="200"></el-table-column>

                        <el-table-column fixed="right" label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button v-if="['1','2'].includes(scope.row.reportState)" size="small" type="text"
                                           @click="lookDoc(scope.row)">预览
                                </el-button>
                                <el-button v-if="['1','2'].includes(scope.row.reportState)" size="small" type="text"
                                           @click="exportDoc(scope.row)">导出
                                </el-button>
                                <el-button v-if="['3','4'].includes(scope.row.reportState)" size="small" type="text"
                                           @click="retryUpload(scope.row)">重试
                                </el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                    <pagination
                        v-show="total > 0"
                        :limit.sync="queryParams.size"
                        :page.sync="queryParams.current"
                        :total="total"
                        class="card-page"
                        style="margin: 0"
                        @pagination="getList"
                    />
            </el-col>
        </el-row>

    </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { addDateset, deleteDateset, getTree, updateDateset } from '@/api/document/app'
import { getDocList, retryUpload } from '@/api/document/document'
import WindowUtil from '@/utils/document/WindowUtil'
import HttpUtil from '@/utils/document/HttpUtil'

export default {
    name: "catalog",
    data() {
        return {
            // 遮罩层
            loading: true,
            dialogData: {
                show: false,
                title: '',
                form: {}
            },
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            //文档树选项
            docTree: [],
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 表单参数
            form: {},
            url: '',
            //目录表格数据
            docList: [],
            defaultProps: {
                children: "children",
                label: "label"
            },
            selectTree: {},
            menuVisible: false,
            datasetName: '',
            datasetCode: '',
            // 查询参数
            queryParams: {
                current: 1,
                size: 20,
                rowCode: "",//行
                creationTime: "",//创建时间
                patientKind: "",//患者类型代码 1门诊;2急诊;3住院;4体检;9其它
                pdfFileClassCode: "",//PDF文档类型 01一般临床检验 02血液学检验
                empiId: "",//主索引id
                patientName: "",//患者姓名
                pdfDocClassName: "",//PDF文档类型名称
                orgCode: "",//医疗机构代码
                yardCode: "",//院区代码
                patientId: "",//患者id
                documentName: "",//文档名称
                tjSn: "",//体检号
                documentAddress: "",//可访问文档地址
                reportCode: "",//检查报告但编号
                sysCode: "",//系统编码
                sourceId: "",//应用ID
                enterDate: "",//输入日期
                uploadDate: "",//更新日期
                reportState: "",//报告状态 0:未审核;1:已审核;2:已上传;3:待上传;4:不可调阅
                dataSetCode: "",//53个标准文档数据集
                startTime: '',
                endTime: ''
            },
            //选择报告状态
            options: [
                {value: '', label: "全部"},
                {value: '0', label: "未审核"},
                {value: '1', label: "已审核"},
                {value: '2', label: "已上传"},
                {value: '3', label: "待上传"},
                {value: '4', label: "不可调阅"},
            ]
        };
    },
    watch: {
        // 根据名称筛选树
        datasetName(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        const {query} = this.$route
        if (query && query.dataSetCode) {
            const dataSetCode = query.dataSetCode
            this.getDocTree(() => this.$refs.tree.setCurrentKey(dataSetCode));
            this.queryParams.dataSetCode = dataSetCode;
            this.getList();
        } else {
            this.getDocTree();
            this.getList();
        }

    },
    methods: {
        foo() {
            // 取消鼠标监听事件 菜单栏
            this.menuVisible = false
            document.removeEventListener('click', this.foo) // 关掉监听，
        },
        styleMenu(menu) {
            if (event.clientX > 1800) {
                menu.style.left = event.clientX - 100 + 'px'
            } else {
                menu.style.left = event.clientX + 1 + 'px'
            }
            document.addEventListener('click', this.foo) // 给整个document新增监听鼠标事件，点击任何位置执行foo方法
            if (event.clientY > 700) {
                menu.style.top = event.clientY - 30 + 'px'
            } else {
                menu.style.top = event.clientY - 10 + 'px'
            }
        },
        //查看文档
        lookDoc(row) {
            let sourceUrl = `${process.env.VUE_APP_REQUEST}/view/export?documentCode=${row.fileSn}`
            WindowUtil.openWindow(840, window.screen.height - 150, sourceUrl, '文档预览')
        },
        // 导出文档
        exportDoc(row) {
            let sourceUrl = `/view/export?documentCode=${row.fileSn}`
            HttpUtil.download(sourceUrl, `${row.fileSn}.pdf`)
        },
        /** 查询目录列表 */
        getList() {
            this.loading = true;
            if (this.queryParams.creationTime && this.queryParams.creationTime.length === 2) {
                this.queryParams.startTime = this.queryParams.creationTime[0] + ' 00:00:00'
                this.queryParams.endTime = this.queryParams.creationTime[1] + ' 23:59:59'
            }
            getDocList(this.queryParams).then((res) => {
                this.docList = res.data.list;
                this.total = res.data.total;
            }).finally(_=>{
                this.loading = false;
            })
        },
        /** 查询文档下拉树结构 */
        getDocTree(callback) {
            getTree().then((response) => {
                if (response.code === 200) {
                    let tree = response.data[0].children
                    this.docTree = [{
                        type: '3',
                        label: '全部',
                        value: "0",
                        children: tree.map(item => {
                            const data = {
                                type: '1',
                                label: item.sourceName,
                                value: item.sourceId
                            }
                            if (item.children) {
                                data.children = item.children.map(c => {
                                    return {
                                        type: '2',
                                        label: c.datasetName,
                                        value: c.datasetCode,
                                        sourceId: item.sourceId
                                    }
                                })
                            }
                            return data;
                        })
                    }]
                    this.$nextTick(() => {
                        if (callback) callback()
                    })
                }
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            let nodeId = data.type;
            if (nodeId === "1") {
                this.queryParams.sourceId = data.value;
                this.queryParams.dataSetCode = null;
            } else if (nodeId === '2') {
                this.queryParams.sourceId = null;
                this.queryParams.dataSetCode = data.value;
            }else {
                this.queryParams.sourceId = null;
                this.queryParams.dataSetCode = null;
            }
            this.handleQuery();
        },
        //树右键菜单事件
        handleContextMenu(e, data) {
            this.selectTree = data;
            this.menuVisible = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
            this.menuVisible = true // 显示模态窗口，跳出自定义菜单栏
            e.preventDefault() //关闭浏览器右键默认事件
            this.selectTree = data;
            const menu = document.querySelector('.menu')
            this.styleMenu(menu)
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.current = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.$refs.tree.setCurrentKey(null);
            this.handleQuery();
        },
        patientTypeFormatter(row) {
            switch (row.patientKind) {
                case '1':
                    return "门诊";
                case '2':
                    return '急诊';
                case '3':
                    return '急诊';
                case '4':
                    return '住院';
                default:
                    return '其它';
            }
        },
        reportStateFormatter(row) {
            switch (row.reportState) {
                case '0':
                    return "未审核";
                case '1':
                    return '已审核';
                case '2':
                    return '已上传';
                case '3':
                    return '待上传';
                case '4':
                    return '不可调阅';
                default:
                    return '其它';
            }
        },
        addTree() {
            this.dialogData = {
                show: true,
                title: '添加绑定数据集',
                form: {
                    sourceId: this.selectTree.value
                }
            }
        },
        updateTree() {
            this.dialogData = {
                show: true,
                title: '修改数据集',
                form: {
                    sourceId: this.selectTree.sourceId,
                    datasetCode: this.selectTree.value,
                    datasetName: this.selectTree.label
                }
            }
        },
        deleteTree() {
            this.$confirm(
                `是否删除数据集 ${this.selectTree.label}?`,
                '删除数据集',
                {
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            deleteDateset({
                                datasetCode: this.selectTree.value,
                                sourceId: this.selectTree.sourceId
                            }).then(res => {
                                if (res.code === 200) {
                                    instance.confirmButtonLoading = false
                                    this.dialogData.show = false
                                    this.getDocTree()
                                    done()
                                }
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        retryUpload(row) {
            this.$confirm(
                `是否重新上传此文档?`,
                '重试',
                {
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            retryUpload(row).then(res => {
                                if (res.code === 200) {
                                    this.$message.success('重试成功')
                                    instance.confirmButtonLoading = false
                                    done()
                                    this.getList()
                                } else {
                                    this.$message.error(res.msg)
                                }
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        submitTree() {
            if (this.dialogData.title === '添加绑定数据集') {
                addDateset(this.dialogData.form)
                    .then(res => {
                        if (res.code === 200) {
                            this.dialogData.show = false
                            this.getDocTree()
                        }
                    })
            } else {
                updateDateset(this.dialogData.form)
                    .then(res => {
                        if (res.code === 200) {
                            this.dialogData.show = false
                            this.getDocTree()
                        }
                    })
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.container {
    ::v-deep {
        .is-current {
            .el-dropdown {
                color: #FFFFFF;
            }
        }
        .el-scrollbar__wrap{
            overflow: auto;
        }
        .pagination-container{
            height: 45px;
        }
    }
}

.contextmenu__item {
    display: block;
    line-height: 34px;
    text-align: center;
}

.contextmenu__item:not(:last-child) {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.menu {
    position: absolute;
    background-color: #fff;
    width: 100px;
    /*height: 106px;*/
    font-size: 12px;
    color: #444040;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-radius: 3px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
    white-space: nowrap;
    z-index: 1000;
}

.contextmenu__item:hover {
    cursor: pointer;
    background: #66b1ff;
    border-color: #66b1ff;
    color: #fff;
}
</style>
