<template>
    <div>
        <div style="display: flex;justify-content: flex-end; margin-bottom: 20px;" v-if="$reportPermission(reportId,[0,1])">
            <el-dropdown trigger="click" split-button type="primary" size="small" @command="handleCommand($event)" >
               <P @click="handleClick(1)" >添加后续事项</P>
                <el-dropdown-menu slot="dropdown" class="text-align_center">
                    <el-dropdown-item command="1">添加后续事项</el-dropdown-item>
                    <el-dropdown-item command="2">批量添加后续事项</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <el-table
            :data="tableData"
            :height="tableHeight"
            ref="table"
            border
            style="width: 100%">
                <el-table-column prop="followUpName" label="名称"  align="center"></el-table-column>
                <el-table-column prop="remark" label="描述"  align="center"></el-table-column>
                <el-table-column prop="timeLimit" label="期限" align="center"></el-table-column>
                <el-table-column prop="agent" label="处理人" align="center"></el-table-column>
                <el-table-column prop="assistPerson" label="协办人" align="center"></el-table-column>
                <el-table-column prop="createPersonName" label="创建人" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                <el-table-column prop="finishTime" label="完成时间" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center"></el-table-column>
                <el-table-column  label="操作" align="center" width="150px">
                    <template slot-scope="scope">
                        <div>
                            <el-dropdown trigger="click" split-button type="primary" size="small" @command="handleCommand1($event,scope.row)" >
                                <p @click="edit(scope.row)">{{ scope.row.status=='进行中'&& $reportPermission(reportId,[0,1])?'编辑':'查看'}}</p>
                                <el-dropdown-menu slot="dropdown" class="text-align_center">
                                    <el-dropdown-item command="1" v-if="scope.row.status=='进行中'&& $reportPermission(reportId,[0,1])">登记结果</el-dropdown-item>
                                    <el-dropdown-item command="2" v-else>查看结果</el-dropdown-item>
                                    <el-dropdown-item command="3" divided class="color-red" v-if=" $reportPermission(reportId,[0,1])">删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </template>
                </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: center; margin-top: 20px;">
            <el-pagination
                background
                layout="total,prev, pager, next,jumper"
                :total="total"
                @current-change="handleCurrentChange"
                :current-page="queryParams.current" :page-size="queryParams.size">
            </el-pagination>
        </div>

        <el-dialog
            :title="title"
            :visible.sync="dialogVisible"
            width="1100px"
            :before-close="close"
            >
            <div>
                <addMatter :type="type" :reportId="reportId" :row="row" @dialog="getDialog"></addMatter>
            </div>
        </el-dialog>
        <el-dialog
            title="登记结果"
            :visible.sync="registerVisible"
            :width="registerForm.type==1?'1100px':'500px'"
            :before-close="closeRegister"
            >
            <div>
                <div style="display:flex;justify-content:flex-end;margin-bottom:10px">
                    <el-button type="primary" size="small" v-if="registerForm.type==2" @click="editRegister">{{ registerForm.edit?'保存':'编辑' }}</el-button>
                </div>
                
                <el-form :model="registerForm" label-width="100px">
                    <el-form-item label="结论：" prop="conclusion">
                        <el-input
                            v-if="registerForm.type==1 || registerForm.edit == true"
                            v-model="registerForm.conclusion"
                            type="textarea"
                            autocomplete="off"
                            placeholder="请输入结论"
                        ></el-input>
                        <span v-else>{{ registerForm.conclusion }}</span>
                    </el-form-item>
                    <el-form-item label="上传附件：">
                        <div v-if="registerForm.filesVOs" class="upload-file">
                            <div v-for="item in registerForm.filesVOs" style="margin:0;display:flex;justify-content:space-around;">
                                <p style="margin:0;width:calc(100% - 40px);overflow: hidden;white-space: nowrap;text-overflow:ellipsis;cursor: pointer">{{item.name?item.name+'.'+item.suffix:item.fileName}}</p> 
                                <Menu :data="item" @delFile="delFile"></Menu>
                            </div>
                        </div>
                        <el-upload v-if="registerForm.type==1 || registerForm.edit == true" ref="upload" class="upload-file" drag action="#" :auto-upload="false" :show-file-list="true" :on-change="onChange" multiple   :on-preview="handlePreview" :on-remove="handleRemove">
                            <i :class="!file ? 'el-icon-upload' : 'el-icon-refresh'"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip"></div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <p v-if="registerForm.type==1" style="margin-left:10px">后续事项：</p>
                <addMatter :type="type" :reportId="reportId" :sign="matterSign" @value="getMatter" v-if="registerForm.type==1"></addMatter>
            </div>
            <div slot="footer" class="dialog-footer" v-if="registerForm.type==1 || registerForm.edit == true">
                <el-button @click="closeRegister">取 消</el-button>
                <el-button type="primary" @click="submitRegister" :loading="btnLoading">确 定</el-button>
            </div>
            <div slot="footer" class="dialog-footer" v-else>
                <el-button @click="closeRegister">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import addMatter from './addMatter.vue'
import Menu from '@/views/workspace/components/menu/index.vue'
export default {
    components:{
        addMatter,
        Menu
    },
    props:['reportId'],
    data() {
        return {
            btnLoading:false,
            tableHeight:null,
            title:'',
            dialogVisible:false,
            row:null,
            registerVisible:false,
            matterSign:false,
            tableData:[],
            type:1,
            queryParams:{
                reportId:this.reportId,
                size:10,
                current:1,
            },
            total:0,
            registerForm:{},
            Already:[],
            file: [],
            
        }
    },
    mounted() {
      this.getList()
    },
    methods: {
        //设置表格高度
        setHeight() {
            const offsetTop = window.innerHeight - this.$refs.table.$el.offsetTop - 200
            const body = document.querySelector('.el-table__body')
            if (!body) {
                return false
            }
            const offsetBodyHeight = body.offsetHeight
            if (this.tableData.length && offsetBodyHeight < offsetTop) {
                this.tableHeight = offsetBodyHeight + 75
            } else if (!this.tableData.length) {
                this.tableHeight = null
            } else {
                this.tableHeight = offsetTop
            }
            this.tableHeight = this.tableHeight>300?this.tableHeight:300
        },
        //查询后续跟进事项
        getList(){
            this.$api.queryMatters(this.queryParams).then(response=>{
                if(response.code==200){
                    this.tableData = response.data.list
                    this.total = response.data.total
                }
            }).catch(error=>{
                this.tableData= [] 
            })
        },
        // 分页
        handleCurrentChange(val) {
            this.queryParams.current = val
            this.getList()
        },
        //新增后续跟进事项的选项
        handleCommand(e){
            switch(e){
                case '1':
                    this.handleClick(1)
                    break;
                case '2':
                    this.handleClick(2)
                    break;
            }
        },
        //打开新增后续跟进事项弹窗
        handleClick(type){
            if(type == 1){
                this.title = '添加后续跟进事项'
            }else if(type == 2){
                this.title = '批量添加后续跟进事项'
            }
            this.type = type
            this.dialogVisible = true
        },
        //表格下拉菜单
        handleCommand1(e,row){
            switch(e){
                case '1':
                    this.registerResult(row,1)
                    break;
                case '2':
                    this.registerResult(row,2)
                    break;
                case '3':
                    this.deleteRegister(row)
                    break;
            }
        },
        //打开编辑后续跟进事项弹窗
      edit(row) {
            this.title = '查看后续跟进事项'
            if (row.status == '进行中') {
              this.title = '编辑后续跟进事项'
            }
            this.type = 1
            this.row = JSON.parse(JSON.stringify(row))
            this.dialogVisible = true
        },
        //获取需要删除的事项
        deleteRegister(row){
            if(row){
                var ids = [row.id]
            }else{

            }
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteMatters(ids)
            }).catch(() => {          
            });
            
        },
        //删除事项
        deleteMatters(ids){
            this.$api.deleteMatters(ids).then(response=>{
                if(response.code == 200){
                    this.$message.success('删除成功')
                    this.getList()
                }
            }).catch(error=>{
                this.$message.error('删除失败')
            })
        },
        //关闭弹窗
        close(){
            this.row = null
            this.type = null
            this.dialogVisible = false
        },
        //获取弹窗状态
        getDialog(val){
            this.close()
            this.getList()
        },
        //上传附件
        onChange(file, fileList) {
            if(this.registerForm.filesVOs){
                var index3 = this.registerForm.filesVOs.findIndex(item=>{
                return item.name+'.'+item.suffix == file.raw.name
                })
                if(index3!=-1){
                
                this.Already.push(this.registerForm.filesVOs[index3].name)
                var index2 = fileList.reverse().findIndex(item=>{
                    return item.raw.name == file.raw.name
                })
                fileList.splice(index2,1)
                }else{
                this.inFile(file, fileList)
                }
            }else{
                this.inFile(file, fileList)
            }
            this.$nextTick(()=>{
            var b = ''
            if(this.Already.length>0){
                this.Already.forEach(item=>{
                b = b+item+','
                })
                this.$alert('文件'+b+'已存在', '提示', {
                confirmButtonText: '确定',
                type:'warning',
                callback: action => {
                    this.Already = []
                }
                });
                
            }
            })
        },
        //判断是否存在
        inFile(file, fileList){
            var index = this.file.findIndex(item=>{
                return item.name == file.raw.name
            })
            if(index!=-1){
                this.Already.push(this.file[index].name)
                var index2 = fileList.reverse().findIndex(item=>{
                return item.raw.name == file.raw.name
                })
                fileList.splice(index2,1)
            }else{
                this.file.push(file.raw) 
            }
        },
        //查看未上传的文件
        handlePreview(file) {
          var item={
              name:file.name,
              suffix:'',
              downLoad:true
            }
            var index = file.raw.type.lastIndexOf('/')
            var type = file.raw.type.substring(index+1,file.raw.type.length)
            var arr = ['png','jpeg','bmp','jpg']
            if(arr.includes(type)){
              var FileUrl =  URL.createObjectURL(file.raw)
              var isPicture = 1
            }else if(type == 'pdf'){
              var FileUrl = URL.createObjectURL(file.raw)
              var isPicture = 0
            }else{
              return false
            }
            const router = this.$router.resolve({
                path: '/checkFile',
                query: {
                    row: JSON.stringify(item),
                    FileUrl: FileUrl,
                    isPicture:isPicture
                }
            })
            window.open(router.href, '_blank');
        },
        //移除未上传的文件
        handleRemove(file, fileList) {
            var index = this.file.findIndex(item=>{
                return item.uid == file.raw.uid
            })
            if(index!=-1){
                this.file.splice(index,1)
            }
        },
        //移除已保存的文件
        delFile(id){
            var index = this.registerForm.filesVOs.findIndex(item=>{
                return item.id == id
            })
            if(index!=-1){
                this.registerForm.filesVOs.splice(index,1)
                if(this.registerForm.type == 2 && !this.registerForm.edit){
                    this.submitRegister()
                }
            }
        },
        //打开登记结果弹窗
        registerResult(row,type){
            this.type = 2
            this.registerForm = JSON.parse(JSON.stringify(row))
            this.registerForm.type = type
            this.registerVisible = true
        },
        //关闭登记结果弹窗
      closeRegister() {
            this.type = null
            this.registerForm = {}
            this.file = []
            if(this.registerForm.type==1 || this.registerForm.edit){
                this.$refs.upload.clearFiles()
            }
            
            this.registerVisible = false
        },
        //获取后续事项
        getMatter(val){
            this.matterSign = false
            this.btnLoading = true
            try{
                var keyList={
                    followUpName:'',
                    remark:'',
                    agent:'',
                    assistPerson:'',
                    timeLimit:''
                }
                var list = []
                val.forEach(item=>{
                var a = false
                for(let key in keyList){
                    if(item[key] !='' && item[key] != null){
                        a = true
                    }
                }
                if(a == true){
                    if(item.followUpName!='') {
                        list.push(item)              
                    }else{
                        throw new Error()
                    }
                }
                })
                if (list.length == 0) {
                  return false
                }
                this.registerForm.followUps = list
                this.submitRegister1()
            }catch(e){
                this.$message.error('后续事项名称不能为空')
                this.registerForm.followUps = [{}]
                this.btnLoading = false
            }  
        },
        //编辑事项结果
        editRegister(){
            this.$set(this.registerForm,'edit',!this.registerForm.edit)
        },
        //更新后续跟进事项结果
        submitRegister(){
            this.matterSign = true
            this.$nextTick(()=>{
                // this.btnLoading = true
                if(this.registerForm.followUps && this.registerForm.followUps.length>0){
                    this.registerForm.followUps = []
                } else {
                    this.submitRegister1()
                } 
            })
           
        },
      submitRegister1() {
            let formData = new FormData()
                if(this.file){
                    for (var i = 0; i < this.file.length; i++) {
                    formData.append("files", this.file[i]);
                    }
                }
                if(this.registerForm.type == 1){
                    this.registerForm.filesVOs = null
                }
                this.registerForm.followUpId = this.registerForm.id
                formData.append('register',JSON.stringify(this.registerForm))
                this.$api.register(formData).then(response=>{
                    if(response.code == 200){
                        this.btnLoading = false
                        this.getList()
                        if(this.registerForm.type != 2 || this.registerForm.edit){
                            this.closeRegister()
                        }
                        
                    }
                }).catch(error=>{
                    this.btnLoading = false
                })
        }
    },
}
</script>