<template>
    <div class="prepare-meeting">
        <div class="dashboard-item">
            <div class="header"><div>CM病例资料整理<p @click="showUpload(1)" :class="{'unoption': !(topObj.isPower == 1 && step == 2 && topObj.isRoute)}"><i class="el-icon-plus"></i>上传</p><p style="width: auto;padding:0 8px" @click="exportTimeLineData" :class="{'unoption': !(topObj.isPower == 1 && step == 2)}">导出原始文件</p></div></div>
            <div  class="scroll-box">
                <el-scrollbar tag="div" style="height:100%">
                    <div class="container">
                        <draggable @start="onStart(0)" @end="onEnd(0)" :disabled="topObj.isPower != 1 || isInMeeting" class="container" element="div" :list="cmFileUrl" :no-transition-on-drag="true">
                            <sourceCard @close="delSource" @preview="preview" v-for="item in cmFileUrl" :key="item.id" :item="item" :closable="!!((topObj.doctorInfo.id == item.doctorId) && !item.del && topObj.isRoute)" :num="0" custom-class="self-card"/>
                        </draggable>
                        <!-- <sourceCard @close="delSource" @preview="preview" v-for="item in cmFileUrl" :key="item.id" :item="item" :closable="false" :num="0" custom-class="self-card"/> -->
                    </div>
                    
                </el-scrollbar>
            </div>
        </div>
        <div class="dashboard-item">
            <div class="header"><div>参会文档<p @click="showUpload(2)" :class="{'unoption': !(topObj.isPower > 1 && topObj.isPower < 5 && step == 2 && topObj.isRoute)}"><i class="el-icon-plus"></i>上传</p></div></div>
            <div class="scroll-box">
                <el-scrollbar tag="div" style="height:100%">
                    <draggable @start="onStart(1)" @end="onEnd(1)" :disabled="!(topObj.isPower > 0 && topObj.isPower < 4) || isInMeeting" class="container" element="div" :list="otherFileUrl" :no-transition-on-drag="true">
                        <sourceCard @close="delSource" @preview="preview" :closable="!!((topObj.doctorInfo.id == s.doctorId) && !s.del && topObj.isRoute)" :num="0" :item="s" custom-class="self-card" v-for="s in otherFileUrl" :key="s.id"/>
                    </draggable>
                </el-scrollbar>
            </div>
        </div>
        <!--上传-->
        <el-dialog
            :visible.sync="sourceDialog"
            width="460px"
            custom-class="mdt-upload-dialog"
            top="35vh"
            >
            <div class="upload-box">
                <el-upload
                v-loading="upLoading"
                ref="upload"
                action="/api/timeline-service/file/uploadFileList"
                name="files"
                class="upload-demo"
                :file-list="fileList"
                :accept="accept"
                :auto-upload="false"
                :limit="1"
                :multiple="false"
                :on-change="changeFiles"
                :on-remove="clearFiles"
                :on-exceed="handleExceed"
                >
                <div class="upload-add-box">上传文件<div class="upload-add"><i class="el-icon-plus"></i>点击上传</div></div>
                <div slot="tip" class="el-upload__tip">{{accept == '.pdf,.PDF' ? '只能上传PDF文件' : '只能上传WORD/PDF文件'}}</div>
                </el-upload>
                <div class="upload-btn">
                <el-button :disabled="upLoading" plain size="mini" @click="sourceDialog = false"
                    >取消</el-button
                >
                <el-button type="primary" style="margin-left:8px" :loading="upLoading" :disabled="upLoading" size="mini" @click="sureUpload"
                    >确定</el-button
                >
                </div>
            </div>
        </el-dialog>
        <previewPdf ref="preview"/>
    </div>
</template>
<script>
import uploadImage from "aegle-sp-components/src/utils/mdtUpload.js";
import { cloneDeep } from 'lodash'
import mixin from 'aegle-sp-components/src/mixin/mdtDashbord.js'
import draggable from "vuedraggable";
import previewPdf from '../components/previewPdf.vue'
import sourceCard from '../components/source-card.vue'
import { getMeetingNode,getSourceList, uploadMdtSource, sortSource,delSource } from '@/request/mdt.js'
const accepts = {
    1: '.pdf,.PDF',
    2: '.pdf,.PDF,.doc,.docx'
}
export default {
    components: { sourceCard, draggable,previewPdf },
    props: {
        step: [Number, String],
    },
    inject: ['topObj'],
    mixins: [mixin],
    data () {
        return {
            accept: '.pdf,.PDF',
            fileList: [],
            upLoading: false,
            sourceDialog: false,
            disabled: false,
            dragList: [1,2,3,4,5,6,7,8,9,10,11,12],
            cmFileUrl: [],
            otherFileUrl: [],
            isCmUpload: 1,
            isInMeeting: false,
            defaultList: [],
            defaultCMList: []
        }
    },
    watch: {
        sourceDialog(v) {
            if(!v) this.clearFiles()
        }
    },
    created() {
        if(this.topObj?.mdtId) this.getSourceList()
    },
    methods: {
        //文件删除
        async delSource(d) {
            // this.$store.commit("changePoint", { pointLoading: true });
            const {data: data1, code: code1, msg: msg1 } = await getMeetingNode(this.topObj?.mdtId)
            if(code1 == 0){
                if(data1 == 3){
                    this.$message.error('已进入会议,不可编辑会前资料！')
                    this.isInMeeting = true;
                } else {
                    this.isInMeeting = false
                    const {code,msg} = await delSource({id: d.id, mdtId:this.topObj?.mdtId})
                    if(code == 0) {
                        this.$message.success('删除成功！')
                        await this.getSourceList()
                    } else {
                        this.$message.error(msg || '删除失败！')
                    }
                }
                // this.$store.commit("changePoint", { pointLoading: false });
            } else {
                // this.$store.commit("changePoint", { pointLoading: false });
            }
        },
        //获取文件列表
        async getSourceList() {
            const {code, data, msg} = await getSourceList(this.topObj?.mdtId)
            if(code == 0){
                this.cmFileUrl = data.cmFileUrl
                // this.otherFileUrl = data.otherFileUrl.map(item => {
                //     item.meetingFileName = item.doctorName + '-' + item.meetingFileName
                //     return item
                // })
                this.defaultCMList = data.cmFileUrl;
                this.otherFileUrl = data.otherFileUrl
            } else {
                this.cmFileUrl = [];
                this.otherFileUrl = [];
                this.$message.success(msg)
            }
        },
        onStart(type) {
            if(type){
                this.defaultList = cloneDeep(this.otherFileUrl)
            } else {
                this.defaultCMList = cloneDeep(this.cmFileUrl)
            }
            
            // getMeetingNode(this.topObj?.mdtId).then(res1 => {
            //     if(res1?.data == 3){
            //         this.$message.error('已进入会议,不可修改文档顺序！')
            //         this.isInMeeting = true
            //     } else {
            //         this.isInMeeting = false
            //     }
            // })
        },
        onEnd(type) {
            getMeetingNode(this.topObj?.mdtId).then(res1 => {
                if(res1?.data == 3){
                    this.$message.error('已进入会议,不可修改文档顺序！')
                    if(type) {
                        this.otherFileUrl = cloneDeep(this.defaultList)
                    } else {
                        this.cmFileUrl = cloneDeep(this.defaultCMList)
                    }
                    this.isInMeeting = true
                } else {
                    this.isInMeeting = false
                    const sortArr = type ? cloneDeep(this.otherFileUrl) : cloneDeep(this.cmFileUrl)
                    console.log(sortArr)
                    const sortList = sortArr.map((item,index) => {
                        return {
                            id: item.id,
                            sort: sortArr.length - 1 - index
                        }
                    })
                    sortSource({sortList,mdtId: this.topObj?.mdtId}).then(({code,msg}) => {
                        if(code == 0) this.getSourceList()
                    })
                }
            })
        },
        showUpload(n) {
            if(n == 1){
                if(!(this.topObj?.isPower == 1 && this.step == 2)) return;
                this.fileList = []
            } else {
                if(!(this.topObj?.isPower > 1 && this.topObj?.isPower < 5 && this.step == 2 && this.topObj.isRoute)) return
            }
            getMeetingNode(this.topObj?.mdtId).then(res1 => {
                if(res1?.data == 3){
                    this.$message.error('已进入会议,不可编辑会前资料！')
                } else {
                    this.isCmUpload = n;
                    this.accept = accepts[n];
                    uploadImage(this,this.accept,(files)=> {
                        const str = files[0].name.slice(files[0].name.lastIndexOf('.') + 1,files[0].name.length)
                        if(this.accept.indexOf(str) == -1) {
                            const str = this.isCmUpload == 1 ? '文件仅支持上传PDF格式!' : '暂不支持上传该类文档格式！'
                            this.$message.error(str)
                            return;
                        }
                        if(files[0].size > 30*1024*1024) {
                            this.$message.error("最大只能上传30M");
                            return false
                        }
                        this.sureUpload(files)
                    })
                    // this.sourceDialog = true;
                }
            })
        },
        async sureUpload(files) {
            console.log(files[0])
            // if (!this.fileList.length) {
            //     this.$message.error("请选择文件");
            //     return false;
            // }
            // if(this.fileList[0].size > 30*1024*1024) {
            //     this.$message.error("最大只能上传30M");
            //     return false
            // }
            const param = {
                id: (this.isCmUpload == 1 && this.cmFileUrl.length) ? this.cmFileUrl[0]?.id : '',
                mdtId: this.topObj?.mdtId,
                roleName: (this.isCmUpload == 1) ? 'CM' : '',
                sort: 0
            }
            let formData = new window.FormData()
            formData.append('files', files[0])
            console.log(formData.getAll('files'))
            this.upLoading = true;
            this.topObj.handleOption(1, { pointLoading: true,pointText: "上传中，请耐心等待~"})
            const {code,msg} = await uploadMdtSource(param,formData)
            this.topObj.handleOption(1, { pointLoading: false })
            this.upLoading = false;
            if(code == 0){
                if(this.isCmUpload == 1){
                    this.$message.success(this.cmFileUrl.length ? '该文件已上传成功！' : '该文件已上传成功！同步到时间轴可查看')
                } else {
                    this.$message.success('该文件已上传成功！');
                }
                this.getSourceList()
                // this.sourceDialog = false
                // this.clearFiles()
            } else {
                this.$message.error(msg);
            }
        },
        //选中文件改变
        changeFiles(file,fileList) {
            const str = file.name.slice(file.name.lastIndexOf('.') + 1,file.name.length)
            if(this.accept.indexOf(str) == -1) {
                const str = this.isCmUpload == 1 ? '文件仅支持上传PDF格式!' : '暂不支持上传该类文档格式！'
                this.$message.error(str)
                this.fileList = []
                return;
            }
            if(file.size > 30*1024*1024) {
                this.$message.error("最大只能上传30M");
                this.fileList = []
                return false
            }
            this.fileList = [file.raw]
        },
        //删除上传文件时触发
        clearFiles() {
            this.fileList = []
        },
        //覆盖原来选中的文件
        handleExceed(files,fileList) {
            const str = files[0].name.slice(files[0].name.lastIndexOf('.') + 1,files[0].name.length)
            if(this.accept.indexOf(str) == -1) {
                const str = this.isCmUpload == 1 ? '文件仅支持上传PDF格式!' : '暂不支持上传该类文档格式！'
                this.$message.error(str)
                return
            }
            if(this.fileList[0].size > 30*1024*1024) {
                this.$message.error("最大只能上传30M");
                return false
            }
            this.fileList = [files[0]]
        },
        //文件预览
        preview(d) {
            this.$refs.preview.open({src: d.pdfFileUrl})
        },
        // 导出时间轴文档
        exportTimeLineData() {
            if(!(this.topObj?.isPower == 1 && this.step == 2)) return;
            this.topObj.handleOption(7, {healthCardNo: this.topObj?.healthNum,mdtId: this.topObj?.mdtId
            })
            // this.$store.dispatch("exportOriginMaterial/openDrawer", {
            //     healthCardNo: this.topObj?.healthNum,
            //     mdtId: this.topObj?.mdtId
            // });
        }
    }
}
</script>
<style lang="less" scoped>
.prepare-meeting {
    height: 100%;
    display: flex;
    flex-direction: column;
    .dashboard-item {
        flex: 1;
        overflow: hidden;
        margin-top: 12px;
        background: #ffffff;
        border-radius: 2px;
        display: flex;
        flex-direction: column;
        /deep/ .el-scrollbar__wrap {
            overflow-x: hidden;
        }
        &:first-child {
            margin-top: 0;
        }
        .header {
            cursor: default;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex: 0 0 56px;
            height: 56px;
            font-size: 16px;
            font-family: PingFangSC, PingFangSC-Semibold;
            font-weight: 600;
            color: rgba(0,0,0,0.85);
            padding: 0 20px;
            >div {
                display: flex;
                align-items: center;
            }
            .el-button {
                text-decoration: underline;
            }
            p {
                cursor: pointer;
                margin: 0 0 0 10px!important;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 45px;
                height: 18px;
                border: 1px solid #3e98ff;
                border-radius: 2px;
                font-size: 12px;
                font-family: PingFangSC, PingFangSC-Regular;
                color: #3e98ff;
                i {
                    margin: 0!important;
                }
            }
            p.unoption {
                color: #bbb;
                border-color: #bbb;
                cursor: default;
                i {
                    color: #bbb;
                }
            }
        }
        .scroll-box {
            flex: 1 1 auto;
            height: 0;
            flex: 1;
            // height: calc(100% - 56px);
            overflow: hidden;
        }
        .container {
            padding: 0 20px 20px;
            display: flex;
            flex-wrap: wrap;
            .self-card {
                margin-right: 8px;
            }
        }
    }
}
/deep/ .mdt-upload-dialog {
    width: 460px;
    height: 292px;
    .el-dialog__header {
        padding: 32px 40px 4px;
    }
    .el-dialog__body {
        padding: 0 40px;
    }
    .el-dialog__footer {
        padding: 0 40px 32px;
    }
    .upload-add-box {
        font-size: 16px;
        font-family: PingFangSC, PingFangSC-Semibold;
        font-weight: 600;
        color: rgba(0,0,0,0.85);
    }
    .upload-add {
        width: 69px;
        height: 18px;
        border: 1px solid #3e98ff;
        border-radius: 2px;
        text-align: center;
        line-height: 16px;
        font-size: 12px;
        font-family: PingFangSC, PingFangSC-Regular;
        font-weight: 400;
        color: #3e98ff;
        cursor: pointer;
    }
    .el-upload__tip {
        font-size: 14px;
        font-family: PingFangSC, PingFangSC-Regular;
        font-weight: 400;
        color: rgba(0,0,0,0.80);
    }
}
</style>
