<template>
    <BaseContainer>
        <!-- 搜索框 -->
        <template slot="search-container">
            <el-form :inline="true" size="mini">
                <el-form-item :label="$t('dictionary:template:keyDocList:FileName')">
                    <el-input clearable v-model="searchData.FileName"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">
                        {{ $t('common:button:search') }}
                    </el-button>
                    <el-button type="primary" icon="el-icon-refresh-left" size="mini" @click="handleReset">
                        {{ $t('common:button:reset') }}
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <div class="upload">
                        <input directory accept=".pdf" type="file" name="uploadFolder" class="select-file" title=""
                            @change="beginScanFiles($event)" />
                        <div class="btn-select">
                            {{ $t('dictionary:template:basicData:button:selectFile') }}
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </template>

        <template slot="main-container">
            <div class="drag" ref="drag" @dragover="handleDragover" @drop="handleDrop">
                <el-table ref="keyDocList" v-loading="loading" v-adaptive="{ bottomOffset: 80 }" :data="list"
                    width="100%" style="width: 100%;min-width: 300px" stripe height="100"
                    @sort-change="handleSortByColumn">
                    <el-table-column type="index" min-width="90" />
                    <el-table-column prop="FileName" :label="$t('dictionary:template:keyDocList:FileName')"
                        show-overflow-tooltip />
                    <el-table-column prop="CreateTime" :label="$t('dictionary:template:keyDocList:CreateTime')"
                        show-overflow-tooltip />
                    <el-table-column :label="$t('common:action:action')" align="left" fixed="right">
                        <template slot-scope="scope">
                            <el-button circle icon="el-icon-view"
                                :title="$t('dictionary:template:keyDocList:button:view')"
                                @click.stop="view(scope.row)" />
                            <el-button circle icon="el-icon-delete"
                                :title="$t('dictionary:template:keyDocList:button:del')" @click.stop="del(scope.row)" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页组件 -->
            <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
                @pagination="getList" />
        </template>

    </BaseContainer>
</template>
<script>
import { Upload } from '@/api/dictionary'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import { getSystemCriterionKeyFileList, addOrUpdateSystemCriterionKeyFile, deleteSystemCriterionKeyFile } from '@/api/dictionary'
import { readEntry } from '@/utils/index'
const searchDataDefault = () => {
    return {
        FileName: '',
        PageIndex: 1,
        PageSize: 20,
        Asc: false,
        SortField: ''
    }
}
export default {
    name: "KeyDocument",
    components: { BaseContainer, Pagination },
    props: {
        criterionId: {
            type: String,
            required: true
        },
        isCompleteConfig: {
            type: Boolean,
            required: true
        },
    },
    data() {
        return {
            searchData: searchDataDefault(),
            loading: false,
            list: [],
            total: 0,
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        handleDragover(e) {
            e.stopPropagation();
            e.preventDefault();
        },
        handleDrop(e) {
            e.stopPropagation();
            e.preventDefault();
            this.beginScanFiles(e, true)
        },
        beforeUpload(file) {
            // 检测文件类型是否符合要求
            if (this.checkFileSuffix(file.name)) {
                this.fileList = [];
                return true;
            } else {
                // this.$alert("必须是word/excel格式");
                this.$alert(this.$t("dictionary:attachment:export:alert:formatFile"));
                return false;
            }
        },
        async beginScanFiles(e, isDrop = false) {
            try {
                this.loading = true;
                let files = []
                if (isDrop) {
                    const items = e.dataTransfer.items;
                    const allFiles = []; // 用于存储所有找到的文件

                    // 遍历拖拽项
                    for (const item of items) {
                        const entry = item.webkitGetAsEntry(); // 获取文件系统入口
                        if (entry) {
                            const files = await readEntry(entry); // 递归读取入口内容
                            allFiles.push(...files);
                        }
                    }
                    files = allFiles
                } else {
                    files = [...e.target.files]
                }
                for (let i = 0; i < files.length; i++) {
                    let file = files[i]
                    if (!this.checkFileSuffix(file.name)) continue
                    const formData = new FormData();
                    formData.append("file", file);
                    let res = await Upload(formData, 5)
                    let data = {
                        FilePath: res.Result.FilePath,
                        FileName: file.name
                    }
                    await this.addKeyDoc(data)

                }
            } catch (err) {
                console.log(err)
                this.loading = false;
            }
        },
        checkFileSuffix(fileName) {
            var index = fileName.lastIndexOf('.')
            var suffix = fileName.substring(index + 1, fileName.length)
            if ('.pdf'.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
                return false
            } else {
                return true
            }
        },
        async getList() {
            try {
                this.searchData.SystemCriterionId = this.criterionId
                this.loading = true
                let res = await getSystemCriterionKeyFileList(this.searchData)
                this.loading = false
                if (res.IsSuccess) {
                    this.list = res.Result.CurrentPageData
                    this.total = res.Result.TotalCount
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        async addKeyDoc(row) {
            try {
                let { FileName, FilePath } = row
                let data = {
                    FileName,
                    FilePath,
                    SystemCriterionId: this.criterionId
                }
                this.loading = true
                let res = await addOrUpdateSystemCriterionKeyFile(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        async del(row) {
            try {
                this.loading = true
                let res = await deleteSystemCriterionKeyFile(row.Id)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                }
            } catch (err) {
                console.log(err)
                this.loading = false
            }
        },
        view(row) {
            this.$preview({
                path: row.FilePath,
                type: 'pdf',
                isLocal: true,
                title: row.FileName,
            })
        },
        // 查询
        handleSearch() {
            this.searchData.PageIndex = 1
            this.getList()
        },
        // 重置
        handleReset() {
            this.searchData = searchDataDefault()
            this.getList()
        },
        // 排序
        handleSortByColumn(column) {
            if (column.order === 'ascending') {
                this.searchData.Asc = true
            } else {
                this.searchData.Asc = false
            }
            this.searchData.SortField = column.prop
            this.searchData.PageIndex = 1
            this.getList()
        }
    }
}
</script>
<style lang="scss" scoped>
.upload {
    display: inline-block;
    height: 30px;
    width: 90px;
    padding: 2px 10px;
    line-height: 23px;
    position: relative;
    text-decoration: none;
    border-radius: 3px;
    overflow: hidden;
    text-align: center;
    background: #428bca;
    border-color: #428bca;
    color: #fff;

    .select-file {
        height: 30px;
        width: 90px;
        position: absolute;
        overflow: hidden;
        left: 0;
        top: 0;
        opacity: 0;
        font-size: 0;
    }

    .btn-select {
        //给显示在页面上的按钮写样式
        width: 90px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        cursor: pointer;
        border-radius: 24px;
        overflow: hidden;
        position: absolute;
        top: 0;
        left: 0;
        pointer-events: none; //pointer-events:none用来控制该标签的点击穿透事件
    }
}
</style>