<template>
    <el-row :gutter="10">
        <!-- 分组 -->
        <el-col :span="4" :xs="24">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <span style="font-size:20px;">文件</span>
                        <div>
                            <el-button size="small" icon="el-icon-refresh" circle @click="handleRefresh" />
                        </div>
                    </div>
                </template>
                <div class="div">
                    <el-tree class="tree" :data="state.groupData" :property="defaultProps" ref="tree" node-key="id"
                        accordion :expand-on-click-node="true" @node-click="handleNodeClick">
                        <template #default="{ node, data }">
                            <el-icon v-if="!data.parentcode" :size="15" color="#409EFC">
                                <Folder />
                            </el-icon>
                            <span :title="node.label" class="custom-tree-node">
                                {{ data.name }}</span>
                        </template>
                    </el-tree>
                </div>
            </el-card>
        </el-col>
        <!-- 文件信息 -->
        <el-col :span="20" :xs="24">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <span style="font-size:20px;color: green;" v-show="state.selectNode.id">{{ state.selectNode.name
                        }}</span>
                        <el-button type="primary" v-show="state.selectNode.id" @click="handleUpLoadFile">文件上传
                        </el-button>
                    </div>
                </template>
                <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" ref="my_table"
                    :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange"
                    :header-cell-style="{ background: '#FF000000', color: '#000000' }" :row-style="{ height: '40px' }">
                    <el-table-column fixed type="index" width="50" align="center" />
                    <el-table-column fixed prop="filename" label="文件名" header-align="center" width="150" />
                    <el-table-column fixed prop="filetypename" label="类型" header-align="center" width="120" />
                    <el-table-column fixed prop="version" label="版本" header-align="center" width="120" />
                    <el-table-column fixed prop="uploadsize" label="大小" header-align="center" width="120" />
                    <el-table-column fixed prop="fileinfo" label="文件描述" header-align="center" width="*" />
                    <el-table-column fixed prop="uploadman" label="上传人" header-align="center" width="120" />
                    <el-table-column fixed label="上传时间" header-align="center" width="120">
                        <template #default="scope">
                            {{ tool.dateFormat(scope.row.uploadtime) }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="" align="left" width="100">
                        <template #default="scope">
                            <el-button type="text" @click="handleDownloadFile(scope.row)">下载</el-button>
                            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-config-provider :locale="locale">
                    <el-pagination v-model:currentPage="fileQueryParams.page" :default-page-size="fileQueryParams.rows"
                        v-model:page-size="fileQueryParams.rows" :page-sizes="[10, 15, 20, 50, 100]"
                        :small="state.pagination.small" :disabled="state.pagination.disabled"
                        :background="state.pagination.background" layout="total, sizes, prev, pager, next, jumper"
                        :total="state.pagination.total" style="text-align: center; margin-top: 10px; height: 30px"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </el-config-provider>
            </el-card>
        </el-col>
    </el-row>

    <el-dialog :title="uploadDialog.title" v-model="uploadDialog.visible" width="650px" center>
        <el-form ref="dataFormRef" :model="uploadDialogData" label-width="100px" :rules="state.rules">
            <el-form-item label="文件类型:">
                <el-input v-model="uploadDialogData.filetypename" placeholder="文件类型" disabled />
            </el-form-item>
            <el-form-item label="文件版本:" prop="version">
                <el-input v-model="uploadDialogData.version" placeholder="文件版本" />
            </el-form-item>
            <el-form-item label="文件密码:">
                <el-input v-model="uploadDialogData.uploadpass" placeholder="文件密码,无密码可不填写" />
            </el-form-item>
            <el-form-item label="文件描述:">
                <el-input v-model="uploadDialogData.fileinfo" placeholder="文件描述" :autosize="{ minRows: 5, maxRows: 5 }"
                    type="textarea" resize="none" />
            </el-form-item>
            <el-form-item label="文件信息:">
                <el-input v-model="uploadDialogData.filename" placeholder="文件信息" style="width: 380px;" disabled />
                <el-upload style="display:inline-block" action="#" :limit="1" class="upload-demo"
                    :on-exceed="handleExceed" :show-file-list="false" ref="upload" auto-upload="false"
                    :http-request="uploadFile">
                    <el-button icon="el-icon-upload" type="primary">选择文件</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleColse">取消</el-button>
                <el-button type="primary" @click="handleSubmitForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from "vue";
import FileAction from "@/api/filecenter";
import { FileTypeModel, FileModel, FileModelQueryParam, PageResult, Dialog } from "@/types";
import arrayToTree from "array-to-tree";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import type { ElUpload, UploadFile } from 'element-plus/es/el-upload/src/upload.type';
import tool from "@/until/tool";

const upload = ref<ElUpload>();
const dataFormRef = ref(ElForm);
const value = ref()
let locale = ref(zhCn);
const my_table = ref();
const tableHeight = ref(document.documentElement.clientHeight - 185);
const loading = ref(false);
const currentRow = ref();
const tree: any = ref(null);
let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;

const handleRefresh = () => {
    state.groupData = [] as FileTypeModel[];
    state.tableData = [] as FileModel[];
    state.fileQueryParams = { page: 1, rows: pageSize } as FileModelQueryParam;
    state.pagination.total = 0;
    state.selectNode = {} as FileTypeModel;
    queryFileType();
    queryFileList();
};

const state = reactive({
    pagination: {
        total: 0,
        small: false,
        background: true,
        disabled: false,
    },
    searchDisabled: false,
    groupData: [] as FileTypeModel[],
    fileQueryParams: { page: 1, rows: pageSize } as FileModelQueryParam,
    tableData: [] as FileModel[],
    selectNode: {} as FileTypeModel,

    fileFormData: new FormData(),
    uploadDialog: {} as Dialog,
    uploadDialogData: {} as FileModel,
    rules: {
        version: [{ required: true, message: "文件版本不能为空", trigger: "blur", },],
    },
});

const {
    groupData,
    pagination,
    fileQueryParams,
    tableData,
    selectNode,
    uploadDialog,
    uploadDialogData,
    fileFormData,
    rules
} = toRefs(state);

const defaultProps = {
    children: "children", //"children"内的每个对象解析为一个子项;
    label: "label", //所有"label"所在的对象解析为一个父项
    checkStrictly: true,
    expandTrigger: 'hover',
    emitPath: false,
};

const handleCurrentRowChange = (val: FileModel) => {
    currentRow.value = val;
};

const handleNodeClick = (node: FileTypeModel) => {
    state.selectNode = node;
    state.fileQueryParams.filetypecode = node.filetypecode;
    queryFileList();
};

const queryFileList = () => {
    loading.value = true;
    FileAction.QueryFileModelList(state.fileQueryParams)
        .then((result) => {
            if (result.status === 200) {
                const { res, flag, error } = result.data;
                if (flag === "1") {
                    console.log(res);
                    const pageData = res as PageResult<FileModel[]>;

                    state.tableData = pageData.list;
                    state.pagination.total = pageData.total;
                    loading.value = false;

                } else {
                    ElMessage.warning(error);
                    loading.value = false;
                }
            }
            else {
                loading.value = false;
            }
        })
        .catch((error) => {
            //请求失败时的操作
            ElMessage.error(error || "未知异常...");
            loading.value = false;
        });
}

const handleSizeChange = (val: number) => {
    state.fileQueryParams.rows = val;
    queryFileList();
    localStorage.setItem("PageSize", val.toString());
};

const handleCurrentChange = (val: number) => {
    state.fileQueryParams.rows = val;
    queryFileList();
    if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
};

onMounted(() => {
    window.onresize = function () {
        tableHeight.value = document.documentElement.clientHeight - 185;
    };
    queryFileType();
    queryFileList();
});

/**
 * 获取文件类型
 */
const queryFileType = () => {
    FileAction.QueryFileTypeModelList().then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                if (res !== null) {
                    let treeArray = res as FileTypeModel[];

                    state.groupData = arrayToTree(treeArray, {
                        parentProperty: "parentcode",
                        customID: "filetypecode",
                        childrenProperty: "children",
                    });
                }
            } else {
                ElMessage.error(error);
            }
        }
    });
}

/**
 * 文件上传
 */
const handleUpLoadFile = () => {
    state.uploadDialogData = {} as FileModel;
    state.uploadDialogData.filetypecode = state.selectNode.filetypecode;
    state.uploadDialogData.filetypename = state.selectNode.name;
    state.uploadDialogData.uploadman = localStorage.getItem("UserName") || "";
    state.uploadDialog = {
        title: '文件上传',
        visible: true,
        disabled: false,
    };
}

const handleExceed = (files: UploadFile[]) => {
    upload.value!.clearFiles();
    const file = files[0];
    upload.value?.uploadFiles.push(file);
    state.uploadDialogData.filename = file.name;
}

/**
 * 获取文件上传数据
 */
const uploadFile = (file: any) => {
    state.uploadDialogData.filename = upload.value?.uploadFiles[0].name || "";
    state.uploadDialogData.uploadsize = upload.value?.uploadFiles[0].size || 0;
    state.fileFormData = new FormData(),
        state.fileFormData.append("file", file.file);
}

/**
 * 文件上传
 */
const handleSubmitForm = () => {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            if(!state.uploadDialogData.filename)
            {
                ElMessage.error("文件不能为空");
                return;
            }

            FileAction.AddFileModel(state.uploadDialogData, state.fileFormData).then(result => {
                if (result.status === 200) {
                    console.log(result.data);
                    const { res, flag, error } = result.data;
                    if (flag === "1") {
                        ElMessage.success('上传成功');
                        state.uploadDialog.visible = false;
                        queryFileList();
                    } else {
                        ElMessage.error(error || "未知异常");
                    }
                }
            });
        }
    })
}

/**
 * 文件上传窗口关闭
 */
const handleColse = () => {
    dataFormRef.value.resetFields();
    state.uploadDialog = {
        title: '文件上传',
        visible: false,
        disabled: false,
    };
}

/**
 * 文件下载
 * @param row
 */
const handleDownloadFile = (row: FileModel) => {
    let a = document.createElement('a');
    a.href = row.filepath;
    a.click();
}

/**
 * 文件删除
 * @param row
 */
const handleDelete = (row: FileModel) => {
    ElMessageBox.confirm(
        ' 是否删除文件[' + row.filename + ']? ',
        '提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
            center: true,
        }
    )
        .then(() => {
            FileAction.DeleteFileModel(row).then(result => {
                if (result.status === 200) {
                    const { res, flag, error } = result.data;
                    if (flag === "1") {
                        ElMessage.success('删除成功');
                        queryFileList();
                    } else {
                        ElMessage.error(error);
                    }
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除成功!',
            })
        })
}
</script>

<style lang="scss" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 25px;
}

.div {
    height: calc(100vh - 140px);
}

.tree {
    overflow-y: scroll;
    overflow-x: auto;
    width: 100%;
    height: calc(100vh - 140px);
    overflow: auto;
}

::v-deep .el-tree-node.is-current>.el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
    font-weight: bold;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    padding-right: 0px;
    margin-left: 5px;
}

.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.el-card ::v-deep .el-card__header {
    padding: 10px 10px;
    background-color: white;
}

.el-card ::v-deep .el-card__body {
    padding: 1px;
    background-color: white;
}

.el-icon-my-export {
    background: url("~@/assets/meter0.png") center no-repeat;
    background-size: cover;
}

.text-wrapper {
    word-break: break-all;
    word-wrap: break-word;
    height: 80px;
    overflow-y: auto;
}
</style>
