<template>
    <div class="main-container">
        <!-- 外部 -->
        <div slot="west">
            <div class="box">
                <!-- 选择内外部文件的侧边栏 -->
                <ibps-type-tree
                    :width="width"
                    :height="height"
                    :category-key="categoryKey"
                    :has-permission="true"
                    @node-click="handleNodeClick"
                    @expand-collapse="handleExpandCollapse"
                />
            </div>
            <ibps-container :margin-left="width + 'px'" class="page">
                <el-alert
                    v-if="!show"
                    :closable="false"
                    title="请选择点击记录分类菜单进行操作！"
                    type="warning"
                    show-icon
                    style="height: 50px"
                />
                <!-- 选择文件，展示在右边 -->
                <template v-else>
                    <ibps-crud
                        key="istree"
                        ref="crud"
                        :data="listData"
                        :toolbars="listConfig.toolbars"
                        :search-form="listConfig.searchForm"
                        :pk-key="pkKey"
                        :columns="listConfig.columns"
                        :loading="loading"
                        :pagination="pagination"
                        :display-field="tableTitle"
                        :index-row="false"
                        @sort-change="handleSortChange"
                        @action-event="handleAction"
                        @pagination-change="handlePaginationChange"
                    >
                        <template slot="position">
                            <ibps-user-selector
                                v-model="pos"
                                type="position"
                                readonly-text="text"
                                :multiple="true"
                            />
                        </template>
                        <template
                            v-if="scope.row.fu_jian_"
                            slot="file"
                            slot-scope="scope"
                        >
                            <ibps-attachment
                                v-model="scope.row.fu_jian_"
                                allow-download
                                download
                                multiple
                                accept="*"
                                store="id"
                                readonly
                            />
                        </template>
                        <template
                            v-if="scope.row.file_info_"
                            slot="wenjinachayue"
                            slot-scope="scope"
                        >
                            <div>
                                <!-- <img
                                    :src="wordPng"
                                    style="vertical-align: middle; height: 20px;"
                                > -->
                                <i class="el-icon-document" />
                                <el-tag
                                    type="info"
                                    style="cursor: pointer"
                                    @click="handleClickTag(scope.row)"
                                >{{ scope.row.file_info_ }}</el-tag>
                            </div>
                        </template>

                    </ibps-crud>
                </template>
            </ibps-container>

            <!-- 查看修订历史 -->
            <file-lookup
                v-if="dialogVisible"
                :visible="dialogVisible"
                :file-infos="fileArray"
                @colseVisible="colseVisible"
            />
        </div>

    </div>
</template>
<script>
import ActionUtils from '@/utils/action'
import IbpsAttachment from '@/business/platform/file/attachment/selector'
import curdPost from '@/business/platform/form/utils/custom/joinCURD.js'
import FixHeight from '@/mixins/height'
import IbpsTypeTree from '@/business/platform/cat/type/tree'
import BpmnFormrender from '@/business/platform/bpmn/form/dialog'
import closeFilePng from '@/assets/images/icons/closeFile.png'
import openFilePng from '@/assets/images/icons/openFile.png'
import wordPng from '@/assets/images/icons/word.png'
import fileTraining from '@/views/component/fileTraining'
import UpdateFile from './updateFile'
import DataTemplateFormrenderDialog from '@/business/platform/data/templaterender/form/dialog.vue'
import ibpsUserSelector from '@/business/platform/org/selector'
export default {
    components: {
        IbpsTypeTree,
        BpmnFormrender,
        UpdateFile,
        'ibps-attachment': IbpsAttachment,
        'file-lookup': fileTraining,
        DataTemplateFormrenderDialog,
        ibpsUserSelector
    },
    mixins: [FixHeight],
    data () {
        return {

            dialogFormVisibles: false,
            fileLookShow: false,
            sonData: '',
            showCaoZuoColumn: false,
            //   treeData: [],
            show: '',
            //   rightsArr: ['join', 'delete'],
            //   rowHandle: true,
            width: 210,
            oldorgId: null,
            height: document.clientHeight,
            loading: false,
            filterText: '',
            pkKey: 'id', // 主键  如果主键不是pk需要传主键
            formKey: 'ywyxjl', // 编辑dialog需要使用
            pkValue: '',
            templateKey: 'ywyxjlsc',
            visible: false,
            categoryKey: 'FILE_TYPE',
            tableTitle: '',
            listData: [],
            selectListData: [],
            bianlistData: {
                dataResult: [],
                pageResult: {
                    limit: 0,
                    page: 0,
                    totalCount: 0,
                    totalPages: 0
                }
            },
            //   listTreeData: [],
            listConfig: {
                // 工具栏
                toolbars: [{ key: 'search' }],
                // 查询条件
                searchForm: {
                    forms: []
                },
                // 表格字段配置
                columns: []
            },

            pagination: {
                limit: 20,
                page: 1
            },
            sorts: {},
            sqlWhere: {},
            searchWhere: {},
            pageKey: '',
            dialogFormVisible: false,
            defId: '',
            addDataCont: {},
            srcUrl: '', // 报表字段
            fileTypesDatas: {
                comAuthority: [],
                buMenAuthority: [],
                authority: []
            }, // 存放所点击列表的分类信息
            closeFilePng,
            openFilePng,
            wordPng,
            dialogVisible: false,
            fileInfos: {},
            // 本人修改
            fileArray: [],
            editDialogVisible: false,
            editPkValue: '',
            editToolbars: [{
                button_type: 'close',
                label: '关闭',
                key: 'close'
            },
            {
                button_type: 'save',
                label: '保存',
                key: 'save'
            }],
            pos: ''
        }
    },
    watch: {
        filterText (val) {
            this.$refs.tree.filter(val)
        },
        showCaoZuoColumn (val) {
            this.showCaoZuoColumn = val
        }
    },
    created () {
        this.listConfig.searchForm.forms = [
            { prop: 'wen_jian_bian_hao', label: '文件编号' },
            { prop: 'wen_jian_ming_che', label: '文件名称' }
        ]
        this.listConfig.columns = [
            { prop: 'wen_jian_bian_hao', label: '文件编号', sortable: 'custom', width: 150 },
            { prop: 'wen_jian_ming_che', label: '文件名称', minWidth: 150 },
            { prop: 'ban_ben_hao_', label: '版本', width: 65 },
            { prop: 'file_info_', label: '查阅', slotName: 'wenjinachayue', minWidth: 150 },
            { prop: 'fa_bu_xiu_ding_zu', label: '发布日期', sortable: 'custom', width: 150 }

        ]
    },
    methods: {

        colseVisible (val) {
            this.dialogVisible = val
        },
        getcolse () {
            this.dialogFormVisibles = false
        },
        // 外部文件更新
        updateDate (data) {
            this.sonData = data
            this.dialogFormVisibles = true
        },
        handleClose (done) {
            this.$confirm('确认关闭？')
                .then((_) => {
                    done()
                })
                .catch((_) => {})
        },
        handleExpandCollapse (isExpand, readonly = false) {
            this.width = isExpand ? 200 : 50
        },

        loadNode () {
            this.loading = true
        },
        getDatas () {
            const { fileType, sorts } = this.sqlWhere
            const sql = `select wj.id_, wj.wen_jian_ming_che, wj.wen_jian_bian_hao, wj.ban_ben_hao_, wj.fa_bu_xiu_ding_zu, wj.xin_wen_jian_fu_j, wj.wen_jian_lei_xing, wj.wen_jian_zhu_jian, wj.wen_jian_fen_lei_ , concat(file.file_name_,'.',file.ext_,'（大小：',                CASE                 WHEN file.total_bytes_ >= 1024 * 1024 THEN CONCAT(ROUND(file.total_bytes_ / (1024.0 * 1024), 2), ' M')                 WHEN file.total_bytes_ >= 1024 THEN CONCAT(ROUND(file.total_bytes_ / 1024.0, 2), ' K')                 ELSE CONCAT(file.total_bytes_, 'B')             END             ,'）') as file_info_ from t_wjylb wj  left join ibps_file_attachment file on file.id_ = wj.xin_wen_jian_fu_j  where wj.shi_fou_guo_shen_ ='有效' and  wj.fa_fang_ri_qi_ is not null and  wj.fa_fang_ri_qi_ <> '' and ( wj.wen_jian_wai_jian = '0' or  wj.wen_jian_wai_jian = '2') and  FIND_IN_SET (wj.fen_lei_id_,'${fileType}') `
            curdPost('sql', sql)
                .then((res) => {
                    const tableDatas = res.variables.data
                    this.selectListData = JSON.parse(JSON.stringify(tableDatas))
                    let filterDatas = []
                    this.bianlistData.pageResult.totalCount = tableDatas.length
                    this.bianlistData.pageResult.totalPages = Math.ceil(
                        tableDatas.length / this.pagination.limit
                    )
                    this.bianlistData.pageResult.limit = this.pagination.limit
                    this.bianlistData.pageResult.page = this.pagination.page
                    if (this.pagination.limit > tableDatas.length) {
                        filterDatas = JSON.parse(JSON.stringify(tableDatas))
                    } else {
                        for (let index = 0; index < 20; index++) {
                            filterDatas.push(tableDatas[index])
                        }
                    }
                    this.bianlistData.dataResult = filterDatas
                    ActionUtils.handleListData(this, this.bianlistData)
                })
                .catch((res) => {
                    this.loading = false
                    this.listData = []
                })
        },
        refreshData () {
            this.listData = []
            this.getSearcFormData()
            this.getDatas()
        },
        hasColumnByProp (columns, prop) {
            return columns.some((column) => column.prop === prop)
        },
        removeColumnByProp (columns, prop) {
            return columns.filter((column) => column.prop !== prop)
        },
        handleNodeClick (nodeId, nodeData, treeDatas) {
            // 判断是否显示外部文件更新按钮
            if (nodeData.depth !== 0) {
                const pathId = nodeData.path ? nodeData.path.split('.') : []
                const pathNameList = pathId.map((id) => {
                    const node = treeDatas.find((item) => item.id === id)
                    return node ? node.name : ''
                })
                if (pathNameList.includes('外部文件') && this.isSuper) {
                    this.showCaoZuoColumn = true
                    if (
                        !this.hasColumnByProp(
                            this.listConfig.columns,
                            'cao_zuo'
                        )
                    ) {
                        this.listConfig.columns.push({
                            prop: 'cao_zuo',
                            label: '操作',
                            slotName: 'caozuo',
                            width: 100
                        })
                    }
                } else {
                    this.showCaoZuoColumn = false
                    this.listConfig.columns = this.removeColumnByProp(
                        this.listConfig.columns,
                        'cao_zuo'
                    )
                }
            }
            this.show = 'detail'
            this.addDataCont = { fenLei: nodeData.name, fenLeiId: nodeId }
            const fileTypes = []
            // 避免重复请求
            if (this.oldorgId === nodeId) {
                return
            }
            // 判断是否存在下级菜单
            const noHadNext = !nodeData.children || !nodeData.children.length
            if (noHadNext && this.pageKey === 'wjkzgl-ywyxjlsc') {
                const chongfu = this.listConfig.toolbars.filter((el) => {
                    return el.key === 'add'
                })
                if (chongfu.length === 0 && this.depth !== 0) {
                    this.listConfig.toolbars.splice(1, 0, { key: 'add' })
                }
            } else {
                this.listConfig.toolbars = this.listConfig.toolbars.filter(
                    (el) => {
                        return el.key !== 'add'
                    }
                )
            }
            this.fileTypesDatas = {
                comAuthority: [],
                buMenAuthority: [],
                authority: [],
                shiJiSql: [],
                sheBeiSql: []
            }
            const processAuthority = (nodeId, authorityName) => {
                fileTypes.push(nodeId)
                if (!authorityName || !authorityName.chaYue) {
                    return
                }
                switch (authorityName.chaYue) {
                    case '公用查阅':
                        this.fileTypesDatas.comAuthority.push(nodeId)
                        break
                    case '部门查阅':
                        this.fileTypesDatas.buMenAuthority.push(nodeId)
                        break
                    case '受限查阅':
                        this.fileTypesDatas.authority.push(nodeId)
                        break
                }
            }
            // 递归获取所有子节点
            // 存在子节点时，需获取当前节点及所有子节点信息 - task3329
            const getTail = (item) => {
                const result = [item] // 将自身信息添加到结果中
                if (item.children && item.children.length > 0) {
                    // 如果有子节点，则递归获取子节点的信息
                    item.children.forEach((child) => {
                        result.push(...getTail(child)) // 将子节点信息添加到结果中
                    })
                }
                return result
            }

            const result = getTail(nodeData)
            result.forEach(({ id, authorityName }) => {
                const parsedAuthority = JSON.parse(authorityName)
                processAuthority(id, parsedAuthority)
            })
            this.oldorgId = nodeId
            this.sqlWhere = {
                fileType: fileTypes.join(',')
            }

            this.getDatas()
        },
        // 开启表单页面
        openTask (id) {
            this.dialogFormVisible = true
            this.defId = id
        },
        // 关闭编辑表单
        closeHandle (v) {
            this.dialogFormVisible = v
            this.refreshData()
        },
        /**
         * 获取格式化参数
         */
        getSearcFormData () {
            this.searchWhere = this.$refs['crud']
                ? this.$refs['crud'].getSearcFormData()
                : {}
            //   this.getDatas()
        },
        /**
         * 处理按钮事件
         */
        handleAction (command, position, selection, data, index, button) {
            switch (command) {
                case 'search': // 查询
                    this.refreshData()
                    break
                case 'remove':
                    if (!data || !data.length) {
                        this.$message({
                            message: '请选择数据再进行删除',
                            type: 'error'
                        })
                    }
                    // eslint-disable-next-line no-case-declarations
                    const ids = []
                    for (var i of data) {
                        ids.push(i.id_)
                    }
                    // eslint-disable-next-line no-case-declarations
                    const deleteParams = {
                        tableName: 't_ywyxjlb',
                        paramWhere: { id_: ids.join(',') }
                    }
                    curdPost('delete', deleteParams).then(() => {
                        this.$message({
                            message: '删除成功！',
                            type: 'warning'
                        })
                        this.refreshData()
                    })

                    break
                case 'add': // 添加
                    this.openTask('1072813170935988224')
                    break
                case 'colect': // 收藏或取消收藏
                    if (!data || !data.length) {
                        return this.$message({
                            message: '请先选择数据再进行操作~',
                            type: 'warning'
                        })
                    }
                    this.handleColect(data)
                    break
                default:
                    break
            }
        },
        /**
         * 处理排序
         */
        handleSortChange (sort) {
            this.sqlWhere.sorts = sort
            this.getDatas()
        },
        // 处理分页事件
        handlePaginationChange (page) {
            ActionUtils.setPagination(this.pagination, page)
            this.bianlistData.pageResult.limit = page.limit
            this.bianlistData.pageResult.page = page.page
            const filterDatas = []
            if (this.selectListData.length >= page.limit * page.page) {
                for (
                    let index = page.limit * page.page - page.limit;
                    index < page.limit * page.page;
                    index++
                ) {
                    filterDatas.push(this.selectListData[index])
                }
                this.bianlistData.dataResult = JSON.parse(
                    JSON.stringify(filterDatas)
                )
            } else {
                for (
                    let index = page.limit * page.page - page.limit;
                    index < this.selectListData.length;
                    index++
                ) {
                    filterDatas.push(this.selectListData[index])
                }
                this.bianlistData.dataResult = JSON.parse(
                    JSON.stringify(filterDatas)
                )
            }
            ActionUtils.handleListData(this, this.bianlistData)
        },
        async handleColect (data) {
            const addScDatas = []
            const delIds = []
            const scTableName = 't_wjscjl'
            for (const i of data) {
                // 如果是有sc_id_说明是已经收藏过的，再次点击按钮的时候就取消收藏
                if (i.sc_id_) {
                    delIds.push(i.sc_id_)
                } else {
                    addScDatas.push({
                        bian_zhi_ren_: this.userId,
                        bian_zhi_shi_jian: this.$common.getDateNow(19),
                        parent_id_: i.id
                    })
                }
            }
            if (addScDatas.length) {
                const addParams = {
                    tableName: scTableName,
                    paramWhere: addScDatas
                }
                await curdPost('add', addParams).then((res) => {})
            }
            if (delIds.length) {
                const deleteParams = {
                    tableName: scTableName,
                    paramWhere: { id_: delIds.join(',') }
                }
                await curdPost('delete', deleteParams).then(() => {})
            }
            this.refreshData()
        },
        handleClickTag (val) {
            this.fileArray = []
            // 查看文件修订历史记录
            const sql = `select * FROM t_wjylb where wen_jian_zhu_jian = '${val.wen_jian_zhu_jian}' or yuan_shi_id_ = '${val.wen_jian_zhu_jian}' and shi_fou_guo_shen_ = '有效' and wen_jian_wai_jian <> '1'`
            this.$common.request('sql', sql).then(async (res) => {
                const list = res.variables.data
                for (let i = 0; i < list.length; i++) {
                    const el = list[i]
                    const obj = {
                        id: el.wen_jian_zhu_jian,
                        wen_jian_ming_che: el.wen_jian_ming_che,
                        ban_ben_: el.ban_ben_,
                        xin_wen_jian_fu_j: el.xin_wen_jian_fu_j,
                        xiu_ding_nei_rong: el.xiu_ding_nei_rong,
                        yuan_yin_: el.xiu_ding_zuo_fei_,
                        fa_fang_ri_qi_: el.fa_fang_ri_qi_,
                        wen_jian_bian_hao: el.wen_jian_bian_hao,
                        bian_zhi_ren_: el.bian_zhi_ren_
                    }
                    await this.handleFileInfo(obj)
                }

                this.dialogVisible = true
            })
        },
        async handleFileInfo (val) {
            // 修订附件作废附件不再使用，修订在文件附件上操作
            const sql = `select * from ibps_file_attachment where id_= '${val.xin_wen_jian_fu_j}'`
            const res = await this.$common.request('sql', sql)
            this.fileInfos = {}
            const { data = [] } = res.variables || {}
            if (!data.length) {
                this.$message.warning('没有可查阅的文件，请查明原因！')
                return
            }

            this.fileInfos = {
                id: val.id,
                FILE_NAME_: val.wen_jian_ming_che,
                fileInfos: data[0],
                ban_ben_: val.ban_ben_,
                xiu_ding_nei_rong: val.xiu_ding_nei_rong ? val.xiu_ding_nei_rong : '',
                yuan_yin_: val.yuan_yin_ ? val.yuan_yin_ : '',
                wen_jian_bian_hao: val.wen_jian_bian_hao,
                fa_fang_ri_qi_: val.fa_fang_ri_qi_,
                bian_zhi_ren_: val.bian_zhi_ren_

            }
            this.fileArray.push(this.fileInfos)
        },
        handleUpdate (fileId, time) {
            const addParams = {
                tableName: 't_wjcyjl',
                paramWhere: [
                    {
                        bian_zhi_ren_: this.userId,
                        bian_zhi_shi_jian: this.$common.getDateNow(19),
                        parent_id_: fileId,
                        shi_chang_: time
                    }
                ]
            }
            curdPost('add', addParams).then((res) => {
                this.refreshData()
            })
        }

    }
}
</script>
<style lang="less" scoped>
.box {
    width: 230px;
}

.title {
    font-size: 14px;
    margin: 21px 5px 5px;
    padding: 0;
}

/deep/ .el-tree-node__content {
    display: block;
}

/deep/ .el-form-item__label {
    text-align: left;
}

/deep/ .el-dialog__footer {
    display: flex;
    justify-content: center;
}
</style>

