<template>
    <div class="page">
        <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm"
            @keyup.enter="refreshList()" @submit.prevent>
            <!-- 搜索框-->
            <el-form-item prop="fileName" label="附件名称:">
                <el-input style="width: 200px;" v-model="searchForm.fileName" placeholder="请输入附件名称"
                    clearable></el-input>
            </el-form-item>
            <el-form-item prop="userName" label="上传人:">
                <el-input style="width: 200px;" v-model="searchForm.userName" placeholder="请输入上传人" clearable></el-input>
            </el-form-item>
            <el-form-item prop="userName" label="收藏分类:">
                <el-select v-model="searchForm.classification" clearable placeholder="请选择收藏分类">
                    <el-option v-for="(item, index) in dictList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
                <el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="jp-table">
            <vxe-toolbar ref="dataSetToolbar" :refresh="{ query: refreshList }" export print custom>
                <template #buttons>
                    <el-button v-if="hasPermission('attachment:add')" type="primary" icon="plus"
                        @click="add()">上传附件</el-button>
                </template>
                <template #tools>
                    <vxe-button type="text" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
                        class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
                </template>
            </vxe-toolbar>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="个人附件表" :name="0"></el-tab-pane>
                <el-tab-pane label="部门附件表" :name="1"></el-tab-pane>
                <el-tab-pane label="公司附件表" :name="2"></el-tab-pane>
            </el-tabs>
            <div class="jp-table-body">
                <vxe-table border="inner" auto-resize resizable height="auto" :loading="loading" size="small"
                    ref="dataSetTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
                    :print-config="{}" :import-config="{}" :export-config="{}" @sort-change="sortChangeHandle"
                    :sort-config="{ remote: true }" :data="dataList" :checkbox-config="{}">
                    <vxe-column type="seq" width="40"></vxe-column>
                    <vxe-column field="fileName" sortable title="附件名称">
                        <template #default="scope">
                            <div>
                                <el-link type="primary" :underline="false" @click="showFile(scope.row)">{{
                                    scope.row.fileName
                                    }}</el-link>
                            </div>
                        </template>
                    </vxe-column>
                    <vxe-column field="classification" sortable title="收藏分类">
                    </vxe-column>
                    <vxe-column field="fileDescription" sortable title="文件描述">
                    </vxe-column>
                    <vxe-column field="userName" sortable title="上传人">
                    </vxe-column>
                    <vxe-column v-if="activeName == '0'" field="collectUserName" sortable title="收藏人">
                    </vxe-column>
                    <vxe-column field="createTime" sortable title="上传/收藏时间">
                    </vxe-column>
                    <vxe-column fixed="right" align="center" width="320" title="操作">
                        <template #default="scope">
                            <el-button v-if="
                                activeName == '0'
                            " type="success" text @click="edit(scope.row.id)">编辑</el-button>
                            <el-button v-if="activeName == '0' && !scope.row.officeId && scope.row.collectType != 1"
                                type="primary" text @click="share(scope.row.id, '1')">部门共享</el-button>
                            <el-button v-if="activeName == '0' && scope.row.officeId && scope.row.collectType != 1"
                                type="primary" text @click="cancelShare(scope.row.id, '1')">取消部门共享</el-button>
                            <el-button v-if="activeName == '0' && !scope.row.companyId && scope.row.collectType != 1"
                                type="primary" text @click="share(scope.row.id, '2')">公司共享</el-button>
                            <el-button v-if="activeName == '0' && scope.row.companyId && scope.row.collectType != 1"
                                type="primary" text @click="cancelShare(scope.row.id, '2')">取消公司共享</el-button>
                            <el-button v-if="activeName == '0'" type="danger" text
                                @click="del(scope.row.id)">删除</el-button>
                            <el-button v-if="handleIsCollect(scope.row)" type="success" text
                                @click="handleCollection(scope.row)">收藏</el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
                <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
                    :total="tablePage.total" :page-sizes="[
                        10,
                        20,
                        100,
                        1000,
                        { label: '全量数据', value: 1000000 },
                    ]" :layouts="[
                        'PrevPage',
                        'JumpNumber',
                        'NextPage',
                        'FullJump',
                        'Sizes',
                        'Total',
                    ]" @page-change="currentChangeHandle">
                </vxe-pager>
            </div>
        </div>
        <v-dialog title="数据接口" :close-on-click-modal="false" v-model="dialogInterfaceVisible">
            <el-table :data="interfaceTable">
                <el-table-column property="type" width="120px" title="接口格式"></el-table-column>
                <el-table-column property="url" title="接口地址"></el-table-column>
                <el-table-column width="40px">
                    <template #default="scope">
                        <el-button text icon="copy-document" v-copy="scope.row.url"
                            style="padding-left: 10px"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-alert type="success" title="接口传递参数说明：/接口url?参数名=参数值, 如果不传递参数，则使用默认值"
                style="margin-top: 20px"></el-alert>

        </v-dialog>
        <el-image-viewer hide-on-click-modal v-if="showViewer" @close="closeViewer" :url-list="[url]" zIndex="9999" />
        <workCollectAccessoryForm @refreshList="refreshList" @onFreshDict="handleGetDict" ref="workCollectAccessoryRef">
        </workCollectAccessoryForm>
    </div>
</template>

<script>
import workCollectAccessoryService from "@/api/workCollectAccessory/index"
import workCollectAccessoryForm from './Form.vue'
import dictService from "@/api/sys/dictService"
import OSSSerivce, {
    openWindowOnUrl
} from '@/api/sys/OSSService'
export default {
    components: {
        workCollectAccessoryForm
    },
    data() {
        return {
            url: "",
            showViewer: false,
            activeName: 0,
            searchVisible: true,
            searchForm: {
                companyId: '',
                officeId: '',
                createById: '',
            },
            dataList: [],
            dataListBak: [],
            tablePage: {
                total: 0,
                currentPage: 1,
                pageSize: 10,
                orders: [],
            },
            isImportCollapse: false,
            dialogInterfaceVisible: false,
            interfaceTable: [],
            loading: false,
            userInfo: {},
            ossService: null,
            dictList: []
        };
    },
    activated() {
        this.userInfo = this.$TOOL.data.get("USER_INFO");
        this.ossService = new OSSSerivce()
        this.searchForm.createById = this.userInfo.id
        this.$nextTick(() => {
            // 将表格和工具栏进行关联
            const $table = this.$refs.dataSetTable;
            const $toolbar = this.$refs.dataSetToolbar;
            $table.connect($toolbar);
        });
        this.refreshList();
    },
    methods: {
        ifName(row) {
            if (this.commonJS.isEmpty(row.fileName)) {
                row.fileName = '---'
                return false
            }
            let suffix = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
            if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
                return true
            } else {
                return false
            }
        },
        // 关闭查看器
        closeViewer() {
            this.url = ''
            this.showViewer = false
        },
        onPreview(url) {
            this.url = url
            this.showViewer = true
        },
        // 预览文件
        showFile(row) {
            if (this.ifName(row)) {
                this.ossService.getTemporaryUrl(row.url).then((data) => {
                    this.onPreview(data)
                })
            } else {
                console.log(2);
                let obj = {
                    name: row.fileName,
                    url: row.url
                }
                openWindowOnUrl(obj)
            }

        },
        //获取字典值
        handleGetDict() {
            workCollectAccessoryService.getClassificationList({
                ...this.searchForm,
            }).then((data) => {
                let dictList = data.map(item => {
                    return {
                        label: item.classification,
                        value: item.classification,
                    }
                })
                if (this.activeName == 0) {
                    this.$refs.workCollectAccessoryRef.dictList = dictList
                }
                this.dictList = dictList
            });
        },
        // 判断用户是否已经收藏此文件
        handleIsCollect(row) {
            if (this.activeName != '0' && row.createById != this.userInfo.id) {
                const index = this.dataListBak.findIndex(item => {
                    return item.url == row.url
                })
                if (index == -1) {
                    return true
                } else {
                    return false
                }
            }
            return false
        },
        // 取消共享
        cancelShare(id, type) {
            this.$confirm(`确定取消共享此文件吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                workCollectAccessoryService
                    .share({
                        attachmentId: id,
                        companyId: "",
                        shareType: type
                    }).then(res => {
                        this.$message.success(res);
                        this.loading = false;
                        this.refreshList();

                    })
            });
        },
        // 共享附件
        share(id, type) {
            let companyId = ""
            if (type == 1) {
                companyId = this.userInfo.officeDTO.id
            } else {
                companyId = this.userInfo.companyDTO.id
            }
            this.$confirm(`确定共享此文件吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                workCollectAccessoryService
                    .share({
                        attachmentId: id,
                        companyId: companyId,
                        shareType: type
                    }).then(res => {
                        this.$message.success(res);
                        this.loading = false;
                        this.refreshList();
                    })
            });

        },
        handleCollection(row) {
            this.loading = true;
            workCollectAccessoryService
                .collection({
                    attachmentId: row.id
                }).then(res => {
                    this.$message.success(res);
                    this.loading = false;
                    // this.refreshList();

                    workCollectAccessoryService
                        .list({
                            current: this.tablePage.currentPage,
                            size: this.tablePage.pageSize,
                            orders: this.tablePage.orders,
                            createById: this.userInfo.id
                        })
                        .then((data) => {
                            this.dataListBak = [...data.records]
                        });
                })
        },
        // tab切换
        handleClick(tab, event) {
            let index = tab.index
            this.searchForm = {
                companyId: '',
                officeId: '',
                createById: '',
            }

            if (index == 0) {
                this.searchForm.createById = this.userInfo.id
            }
            if (index == 1) {
                this.searchForm.officeId = this.userInfo.officeDTO.id
            }
            if (index == 2) {
                this.searchForm.companyId = this.userInfo.companyDTO.id
            }
            this.refreshList();
        },
        // 获取数据列表
        refreshList() {
            this.loading = true;
            workCollectAccessoryService
                .list({
                    current: this.tablePage.currentPage,
                    size: this.tablePage.pageSize,
                    orders: this.tablePage.orders,
                    ...this.searchForm,
                })
                .then((data) => {
                    if (this.searchForm.createById) {
                        this.dataListBak = [...data.records]
                    }
                    this.dataList = data.records;
                    this.tablePage.total = data.total;
                    this.loading = false;
                    // 获取分类去重的数据
                    this.handleGetDict()
                });
        },
        // 当前页
        currentChangeHandle({ currentPage, pageSize }) {
            this.tablePage.currentPage = currentPage;
            this.tablePage.pageSize = pageSize;
            this.refreshList();
        },
        // 排序
        sortChangeHandle(column) {
            this.tablePage.orders = [];
            if (column.order != null) {
                this.tablePage.orders.push({
                    column: this.$utils.toLine(column.property),
                    asc: column.order === "asc",
                });
            }
            this.refreshList();
        },
        // 新增
        add() {
            this.$refs.workCollectAccessoryRef.init("add")
            this.handleGetDict()
        },
        // 编辑
        edit(id) {
            console.log(id);
            this.$refs.workCollectAccessoryRef.init("edit", id)
            this.handleGetDict()
        },
        // 查看
        view(id) {
            id =
                id ||
                this.$refs.dataSetTable.getCheckboxRecords().map((item) => {
                    return item.id;
                })[0];
            this.$router.push({
                path: `/database/datamodel/DataSetForm`,
                query: { method: "view", id: id, title: "数据模型配置" },
            });
        },
        // 删除
        del(id) {
            this.$confirm(`确定删除所选项吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                workCollectAccessoryService
                    .del({
                        attachmentId: id
                    }).then(res => {
                        this.$message.success(res);
                        this.loading = false;
                        this.refreshList();
                    })


            });
        },

        resetSearch() {
            this.$refs.searchForm.resetFields();
            this.refreshList();
        },
    },
};
</script>
