import req from '@/request.js'
import utils from '@/utils.js'
// import sat from '@/api/satisfaction/satisfaction'
// import pilot from '@/api/pilotprojects'
const portal = window.context.portal
export const TableMixin = {
    data() {
        return {
            tableMaxHeight: 600,
            showMore: false,
            /* 文件上传需要变量 */
            fileList: [], // 文件上传
            accept:
                '.bmp,.jpg,.png,.tif,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.avif,.apng,.xls,.docx,.docm,.doc,.dotx,.pptx,.pptm,.ppt,.pdf,.xps,.potx,.txt,.xls,.xlsx,.xps,.zip,.rar,.7z',
            url: `${portal}/file/v1/uploadFileForConfig`,
            previewUrl: `${portal}/file/onlinePreviewController/v1/getFileById_`,
            header: {
                Authorization: `Bearer ${this.$store.state.login.currentUser.token}`
            },
            uploadData: {
                bizCode: '',
                bizId: '',
                bizType: ''
            },
            /* 文件上传需要变量 */
            disabledDetils: false, // 查看详情禁用,
            demandRunwaOoptionsSerch: [], // 所属跑道数据（搜索框）
            demandRunwaOoptionsForm: [], // 所属跑道数据（表单内）
            unitTreeData: [], // 责任单位选择级联数据
            // 反馈时限设置时间范围为选择当天之后时间
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now()
                }
            },
            // 选择当年及其之后
            pickerYearOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            hisData: [],
            currentUpadte: [],
            switchStatus: false,
            statusOptions: [],
            pilotLevelList: [],
            isAdvanced: false
        }
    },
    mounted() {
        this.calcTableHeight()
        this.$root.$on('resize', () => {
            this.calcTableHeight(500)
        })
    },
    created() {
        // 默认根据领域第一个值获取跑道数据
        this.getByDemandFiledData('ggbb_ssly', 1)
        //获取主责单位
        this.unitTreeData = JSON.parse(sessionStorage.getItem('responsibilityTree'))
    },
    methods: {
        // 获取字典值翻译
        getDictName(code, value) {
            return utils.getDictName(code, value)
        },
        /* 文件上传 --- start */
        handleUpload() {
            this.$confirm(
                '文件是否涉密？若文件涉密请通过内网邮件上传！',
                '文件上传提示',
                {
                    confirmButtonText: '立即上传',
                    cancelButtonText: '文件涉密,内网邮件上传',
                    type: 'warning'
                }
            )
                .then(() => {
                    this.$refs.upload.$el.click()
                })
                .catch(() => {
                    // 存在这个值为文件涉密内网上传作为查看判断依据
                    this.dialogForm.classified = '1'
                    // 单独为成校晾晒设置
                    this.dialogFormChilred.classified = '1'
                })
        },
        // 上传时
        handleUploadprogress() {
            this.loading = true
        },
        // 上传失败
        hanldeUploadError() {
            this.loading = false
        },
        // 上传成功之后
        beforeUpload(res, file, fileList) {
            this.loading = false
            if (res.success) {
                this.fileList = fileList
                let files = []
                fileList.forEach(item => {
                    if (item.response) {
                        files.push(item.response.fileId)
                    } else {
                        files.push(item.id)
                    }
                })
                this.dialogForm.ids = files
                // 存在这个值为文件涉密内网上传作为查看判断依据
                this.dialogForm.classified = '0'
                this.$message.success('附件上传成功')
            } else {
                this.$message.error('附件上传失败')
            }
        },
        // 文件下载
        handleDownload(file) {
            let id = file.id ? file.id : file.response.fileId
            window.open(portal + `/file/v1/downloadFile?fileId=${id}`, '_blank')
        },
        // 移除之前
        beforeRemove(file, fileList) {
            return this.$confirm(`确定删除 ${file.name}？`, this.$t('common.tips'), {
                confirmButtonText: this.$t('common.confirm'),
                cancelButtonText: this.$t('common.cancel'),
                type: 'warning'
            }).then(() => {
                let id = file.id || file.response.fileId
                // sat.deleteFileById(id, res => {
                //     if (res.state) {
                //         this.loading = false
                //         this.$message.success('附件删除成功')
                //         let arr = this.fileList.filter(item => {
                //             let fileId = item.id || item.response.fileId
                //             if (fileId !== id) {
                //                 return item
                //             }
                //         })
                //         this.fileList = arr
                //         let files = []
                //         this.fileList.forEach(item => {
                //             if (item.response) {
                //                 files.push(item.response.fileId)
                //             } else {
                //                 files.push(item.id)
                //             }
                //         })
                //         this.dialogForm.ids = files
                //         return true
                //     } else {
                //         this.$message.error('附件删除失败')
                //         return false
                //     }
                // })
            })
        },
        // 移除时
        handleUploadRemove() {
            this.loading = true
        },
        // 根据附件id删除附件
        handleRemove(file) {
            console.log(file)
            this.$confirm('确认删除？', this.$t('common.tips'), {
                confirmButtonText: this.$t('common.confirm'),
                cancelButtonText: this.$t('common.cancel'),
                type: 'warning'
            }).then(() => {
                let id = file.id || file.response.fileId
                // sat.deleteFileById(id, res => {
                //     if (res.state) {
                //         this.$message.success('附件删除成功')
                //         let arr = this.fileList.filter(item => {
                //             let fileId = item.id || item.response.fileId
                //             if (fileId !== id) {
                //                 return item
                //             }
                //         })
                //         this.fileList = arr
                //     } else {
                //         this.$message.error('附件删除失败')
                //     }
                // })
            })
        },
        // 文件预览
        handlePreview(file) {
            let id = file.id ? file.id : file.response.fileId
            let type = file.fileType || (file.extensionName
                ? file.extensionName
                : file.name.split('.')[1])
            this.$refs.filePreview.previewUrl =
                portal + `/file/onlinePreviewController/v1/getFileById_${id}`
            this.$refs.filePreview.open(type)
            // sat.getDownloadById(id, res => {})
        },
        // 图片预览
        handlePictureCardPreview(file) {
            this.$refs.imgPrivew.open(portal + `/file/v1/downloadFile?fileId=${id}`)
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 3 个文件，本次选择了 ${files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            )
        },
        /* 文件上传 --- end */
        // 查看详情
        handleLookDetiles(row) {
            this.dialog.title = '详情'
            // 协同单位转换
            if (
                row.cooperativeUnitName &&
                typeof row.cooperativeUnitName == 'string'
            ) {
                row.cooperativeUnitName = JSON.parse(row.cooperativeUnitName) || ''
            }
            if (row.propulsiveYear) {
                row.propulsiveYear = row.propulsiveYear.toString()
            }
            this.getByDemandFiledData('ggbb_ssly', row.demandField)
            if (row.demandRunway) {
                row.demandRunway = row.demandRunway.toString()
            }
            this.disabledDetils = true
            this.dialogForm = row
            this.dialogForm_ = row
            row.files &&
                row.files.length != 0 &&
                row.files.forEach(item => {
                    item.name = item.fileName
                })
            this.fileList = row.files || []
            this.isTag = true
            this.isShowBtn = false
            this.activeCollapse1 = ['1', '2', '3', '4']
            this.dialog.visible = true
            // 清除表单效验
            this.$refs.form.clearValidate()
        },
        // 根据id查询子表存在records的数据详情
        handleLookDetiles_(row, url) {
            this.loading = true
            this.disabledDetils = true
            this.isEdit = false
            this.dialog.title = '详情'
            this.dialog.visible = true
            // 清除表单效验
            this.$refs.form.clearValidate()
            let formData = new FormData()
            formData.append('id', row.id)
            req.post(portal + url, formData).then(res => {
                this.loading = false
                let data = (res && res.data) || {}

                if (data.blockageRunway) {
                    this.getByDemandFiledData('ggbb_ssly', data.blockageField)
                    data.blockageRunway = data.blockageRunway.toString() // 解决所属跑道回显问题
                }

                if (data.effectRunway) {
                    this.getByDemandFiledData('ggbb_ssly', data.effectField)
                    data.effectRunway = data.effectRunway + ''
                }
                this.dialogForm_ = data
                this.dialogForm = data
                if (this.dialogForm_.records && this.dialogForm_.records.length) {
                    this.hisData = this.dialogForm_.records.filter(
                        item => item.isHis == true
                    )
                    this.currentUpadte = this.dialogForm_.records.filter(
                        item => item.isHis == false
                    )
                    if (this.currentUpadte.length) {
                        this.$set(
                            this.dialogForm,
                            'propulsiveStatus',
                            this.currentUpadte[0].propulsiveStatus + ''
                        )
                        this.$set(
                            this.dialogForm,
                            'propulsiveDetailed',
                            this.currentUpadte[0].propulsiveDetailed
                        )
                        this.$set(
                            this.dialogForm,
                            'existingProblems',
                            this.currentUpadte[0].existingProblems
                        )
                    }
                    if (this.hisData.length) {
                        let dictData = utils.getDictItemsFromCache('xqzt')
                        let status = this.hisData[0].propulsiveStatus
                        dictData.forEach(item => {
                            if (item.value < status) {
                                item.disabled = true
                            }
                        })
                        this.propulsiveStatusOptions = dictData
                    }
                }
                data.records &&
                    data.records[0] &&
                    data.records[0].files &&
                    data.records[0].files.length != 0 &&
                    data.records[0].files.forEach(item => {
                        item.name = item.fileName
                    })
                this.fileList =
                    data.records && data.records[0] && data.records[0].files
                        ? data.records[0].files
                        : []
                this.activeCollapse1 = ['1', '2', '3']
            })
        },
        // 编辑
        handleDbClick(data) {
            this.dialog.title = '编辑'
            // 协同单位转换
            if (
                data.cooperativeUnitName &&
                typeof data.cooperativeUnitName == 'string'
            ) {
                data.cooperativeUnitName = JSON.parse(data.cooperativeUnitName) || ''
            }
            if (data.demandRunway) {
                data.demandRunway = data.demandRunway.toString()
            }
            this.getByDemandFiledData('ggbb_ssly', data.demandField)
            if (data.propulsiveYear) {
                data.propulsiveYear = data.propulsiveYear.toString()
            }
            this.fileList = data.files || []
            this.disabledDetils = false
            this.edit = true
            data.files &&
                data.files.length != 0 &&
                data.files.forEach(item => {
                    item.name = item.fileName
                })
            this.dialogForm = data
            this.dialog.visible = true
            // 清除表单效验
            this.$refs.form.clearValidate()
        },
        // 所属跑道选择
        hanldeCommonSelect(val, obj, key) {
            if (key == 'serch') {
                this.demandRunwaOoptionsSerch = obj.lowerDic['ggbb_sspd']
                this.searchForm = {
                    ...this.searchForm,
                    demandRunway: '',
                    effectRunway: '',
                    blockageRunWay: '',
                    projectRunway: ''
                }
            } else {
                this.demandRunwaOoptionsForm = obj.lowerDic['ggbb_sspd']
                this.dialogForm = {
                    ...this.dialogForm,
                    effectRunway: '',
                    demandRunway: '', // 除之外所属跑道清空字段
                    blockageRunWay: '', // 堵点卡点中所属跑道字段清空
                    projectRunway: ''
                }
            }
            if (key == 'formInfo') {
                this.parameter.pilotRunway = ''
            }
            if (key == 'project') {
                this.demandRunwaOoptionsSerch = obj.lowerDic['ggbb_sspd']
                this.querys[3].value = ''
            }

        },
        // 根据领域数据值返回跑道数据
        getByDemandFiledData(code, value) {
            let arr = utils.getDictItemsFromCache(code)
            arr.forEach(item => {
                if (item.value == value) {
                    this.demandRunwaOoptionsForm = item.lowerDic['ggbb_sspd']
                    this.demandRunwaOoptionsSerch = item.lowerDic['ggbb_sspd']
                }
            })
        },
        //处理责任单位数据
        changeCommonUnit(value, key) {
            this.$nextTick(() => {
                let nodesObj = this.$refs['cascader'].getCheckedNodes()
                if (nodesObj != []) {
                    this.dialogForm.responsibleUnitName = nodesObj[0].label
                    const data = nodesObj[0].data
                    if (key) {
                        this.dialogForm = {
                            ...this.dialogForm,
                            unitId: data.id,
                            unitName: data.name,
                            unitCode: data.code,
                            unitGrade: data.grade || ''
                        }
                    } else {
                        this.dialogForm = {
                            ...this.dialogForm,
                            responsibleUnitId: data.id,
                            responsibleUnitName: data.name,
                            responsibleUnitCode: data.code,
                            responsibleUnitGrade: data.grade || ''
                        }
                    }
                } else {
                    if (key) {
                        // this.parameter.unitId = ''
                        this.dialogForm.unitName = ''
                        // this.parameter.unitCode = ''
                        // this.parameter.unitGrade = ''
                    } else {
                        // this.parameter.responsibleUnitId = ''
                        this.dialogForm.responsibleUnitName = ''
                        // this.parameter.responsibleUnitCode = ''
                        // this.parameter.responsibleUnitGrade = ''
                    }
                }
            })
        },
        // 获取协同单位名称
        getCoordination(data) {
            if (!data) return
            // 这里为什么写两个转换，暂时没有找到原因
            if (typeof data == 'string') {
                data = JSON.parse(data)
            }
            if (typeof data == 'string') {
                data = JSON.parse(data)
            }
            let arr = []
            data.forEach(item => {
                arr.push(item.join('/'))
            })
            return arr.join('；')
        },
        // 判断需要改革办审核
        returnStatus(arr) {
            return arr && arr.length != 0 && arr[0].status == 3
        },
        // 处理填写的驳回意见
        sendRejectInfo(rejectInfo, api, status) {
            let params = null
            if (this.currentUpadte.length !== 0) {
                params = this.currentUpadte[0]
            } else {
                params = this.dialogForm
            }
            params.status = status || 2
            params.approvalComments = rejectInfo
            this.loading = true
            req
                .post(portal + api, params)
                .then(res => {
                    if (res.data.state) {
                        this.$message.success('驳回成功')
                    } else {
                        this.$message.error('驳回失败')
                    }
                    this.loading = false
                    this.handleDialogClose()
                    this.loadData(this.params)
                })
                .catch(() => {
                    this.loading = false
                    this.$message.error('驳回失败')
                })
        },
        // 处理审批意见回显格式化
        formatApprovalComments(value) {
            if (!value) return
            let arr = value.split('$_$')
            arr = arr.map((item, index) => (item = index + 1 + '. ' + item))
            return arr.join('<br/>')
        },
        // 撤销已经上报的数据
        handleCancel(row, url1, url2, status) {
            this.$confirm('是否确认撤销？', this.$t('common.tips'), {
                confirmButtonText: this.$t('common.confirm'),
                cancelButtonText: this.$t('common.cancel'),
                type: 'warning'
            }).then(() => {
                let formData = new FormData()
                formData.append('id', row.id)
                this.tableLoading = true
                req
                    .post(portal + url1, formData)
                    .then(res => {
                        let data = (res && res.data) || {}
                        let params = data.records[0]
                        params.status = status
                        params.approvalResults = 2
                        req.post(portal + url2, params).then(res => {
                            if (res.data.state) {
                                this.$message.success('撤销成功')
                            } else {
                                this.$message.error('撤销失败')
                            }
                            this.tableLoading = false
                            this.loadData(this.params)
                        })
                    })
                    .catch(() => {
                        this.tableLoading = false
                    })
            })
        },
        calcTableHeight(delay) {
            // 动态计算表格的高度，自适应当前容器
            setTimeout(() => {
                if (!this.$refs.contentPanel) {
                    return
                }
                // 容器高度 - 内边距
                let contentPanel = 0
                const contentPanelHeight =
                    this.$refs.contentPanel.clientHeight ||
                    this.$refs.contentPanel.$el.clientHeight
                let contentPanelPaddingT = getComputedStyle(this.$refs.contentPanel.$el)
                    .getPropertyValue('padding-top')
                    .replace('px', '')
                let contentPanelPaddingB = getComputedStyle(this.$refs.contentPanel.$el)
                    .getPropertyValue('padding-bottom')
                    .replace('px', '')
                let contentPanelPadding =
                    parseInt(contentPanelPaddingT, 10) +
                    parseInt(contentPanelPaddingB, 10)
                contentPanel = contentPanelHeight - contentPanelPadding

                //按钮高度 + 下外边距
                let btnPanelHeight = 10,
                    btnPanel,
                    btnPanelMarginB = 0
                if (this.$refs.btnPanel.clientHeight) {
                    btnPanelHeight = this.$refs.btnPanel.clientHeight
                    btnPanel = this.$refs.btnPanel
                } else if (
                    this.$refs.btnPanel.$el &&
                    this.$refs.btnPanel.$el.clientHeight
                ) {
                    btnPanel = this.$refs.btnPanel.$el
                    btnPanelHeight = this.$refs.btnPanel.$el.clientHeight
                }
                if (btnPanel) {
                    btnPanelMarginB = getComputedStyle(btnPanel)
                        .getPropertyValue('margin-bottom')
                        .replace('px', '')
                    btnPanelHeight = btnPanelHeight + parseInt(btnPanelMarginB, 10)
                }

                //分页高度 + 上外边距
                let paginationPanelHeight = 0,
                    paginationPanelMarginT = 0

                if (
                    this.$refs.paginationPanel.$el &&
                    this.$refs.paginationPanel.$el.clientHeight
                ) {
                    paginationPanelHeight = this.$refs.paginationPanel.$el.clientHeight
                    paginationPanelMarginT = getComputedStyle(
                        this.$refs.paginationPanel.$el
                    )
                        .getPropertyValue('margin-top')
                        .replace('px', '')
                }

                paginationPanelHeight =
                    paginationPanelHeight + parseInt(paginationPanelMarginT, 10)

                // console.log(contentPanel, btnPanelHeight, paginationPanelHeight)

                this.tableMaxHeight =
                    contentPanel - btnPanelHeight - paginationPanelHeight
            }, delay || 0)
        },
        // handleDbClick(row, column, event) {
        //   this.handleUpdate(row)
        // },
        commonPageClick() {
            if (this.showMore) {
                this.showMore = false
            }
        },
        // 试点层级
        setPilotLevelList() {
            // 获取试点层级
            this.pilotLevelList = utils.getDictItemsFromCache('sdcj')
            this.pilotLevelList.push({ value: undefined, name: '重置' })
        },
        // 试点层级筛选
        handleCommand(command, name) {
            this.searchForm[name] = command ? command : ''
            this.handleSearch(1)
        },

        // 不同页面不同审核状态
        setStatusOptions(code, minStatus) {
            let options = utils.getDictItemsFromCache(code)
            this.statusOptions = options.filter(item => item.value - 0 > minStatus)
        },
        // 展开高级搜索
        advanced() {
            this.isAdvanced = !this.isAdvanced
            this.$nextTick(() => {
                this.calcTableHeight(500)
            })
        },
        clearSearchForm() {
            this.advanced()
            this.isAdvanced = false
            this.searchForm = {}
            if (this.slefClearMethods) {
                this.slefClearMethods()
            }
            this.handleSearch(1)
        },
        // 撤回审核状态
        revokeReview(type, data) {
            this.$confirm('确认执行撤销操作吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
            }).then(() => {
                this.markLoading = true
                data.approvalResults = 2
                if (type) {
                    // 主表
                    // pilot.updateStatusById(data, res => {
                    //     if (res.state) {
                    //         this.$message.success('撤销操作成功')
                    //         this.handleSearch(1)
                    //     }
                    //     this.markLoading = false
                    // })
                } else {
                    // 子表
                    // pilot.districtAuditsById(data, res => {
                    //     if (res.state) {
                    //         this.$message.success('撤销操作成功')
                    //         this.handleSearch(1)
                    //     }
                    //     this.markLoading = false
                    // })
                }
            })
        },
        // 流程确认之后可以编辑
        handleSureEdit(row, url) {
            this.dialogEdit.title = '编辑'
            this.dialogEdit.visible = true
            this.loading = true
            let formData = new FormData()
            formData.append('id', row.id)
            req.post(portal + url, formData).then(res => {
                this.loading = false
                let data = (res && res.data) || {}
                this.getByDemandFiledData('ggbb_ssly', data.effectField)
                if (data.effectRunway) {
                    data.effectRunway = data.effectRunway + ''
                }
                this.dialogForm = data
                data.records &&
                    data.records[0] &&
                    data.records[0].files &&
                    data.records[0].files.length != 0 &&
                    data.records[0].files.forEach(item => {
                        item.name = item.fileName
                    })
                this.fileList = (data.records && data.records[0].files) || []
                if (data.records && data.records[0].effectForm) {
                    this.demandRunwayOptions = this.getDemandData(
                        data.records[0].effectForm
                    )
                }

                if (
                    data.records &&
                    data.records[0] &&
                    (data.records[0].specificDetails || data.records[0].effectForm)
                ) {
                    data.records[0].specificDetails = data.records[0].specificDetails.toString()
                }
                this.dialogFormChilred = (data.records && data.records[0]) || {}
                this.activeCollapse1 = ['1', '2']
            })
        },
        // 查看审批流程记录
        operationHistory(id) {
            this.$refs.RecordDialog.openDialog(id)
        },
    }
}
