<!--
author:        Kane Wang <wangkane@qq.com>
date:          2025-10-30 15:06:18
component:     NewRegulatory
Copyright © CPIC All rights reserved
-->
<template>
    <div class="wrapper">
        <div class="query-box-wrapper">
            <el-row :gutter="10">
                <el-col :span="1">
                    <span>名称</span>
                </el-col>
                <el-col :span="10">
                    <el-input
                        ref="regulatoryName"
                        v-model.trim.lazy="ui.newRegulatory.regulatory_name"
                        style="text-align:center;"
                    />
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="1">
                    <span>部门</span>
                </el-col>
                <el-col :span="4">
                    <el-input
                        ref="departmentName"
                        v-model.trim="ui.newRegulatory.department_name"
                    />
                </el-col>
                <el-col :span="2">
                    <span>发布、修订年份</span>
                </el-col>
                <el-col :span="4">
                    <el-input
                        ref="releaseYear"
                        v-model.lazy.number.trim="ui.newRegulatory.release_year"
                    />
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="1">
                    <span>备注</span>
                </el-col>
                <el-col :span="10">
                    <el-input
                        ref="comment"
                        v-model.lazy.trim="ui.newRegulatory.comment"
                        type="textarea"
                        :rows="3"
                    />
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="3">
                    <div class="button-wrapper-left">
                        <el-button
                            type="primary"
                            icon="document"
                            @click="showUploadFileDialog"
                        >
                            新增文档
                        </el-button>
                    </div>
                </el-col>
                <el-col :span="5" />
                <el-col :span="3">
                    <div class="button-wrapper-right">
                        <el-button
                            type="primary"
                            icon="document"
                            @click="onCreateNewRegulatory()"
                        >
                            提交
                        </el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-table
            width="100%"
            stripe
            border="true"
            :head-cell-style="headerCellStyle"
            :row-class-name="tableRowClassName"
            empty-text="请上传文件"
            :data="ui.newRegulatory.regulatory_files"
        >
            <el-table-column
                label="文件名"
                align="center"
            >
                <template #default="file">
                    <span>{{ file.row.regulatory_file_name }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="文件类型"
                align="center"
                width="200px"
            >
                <template #default="file">
                    <span>{{ file.row.file_type }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="200px"
            >
                <template #default="file">
                    <el-button
                        type="primary"
                        icon="search"
                        circle
                        @click="onPreviewUploadedFile(file.row.rowIndex)"
                    />
                    <el-button
                        type="danger"
                        icon="delete"
                        circle
                        @click="onDeleteUploadedFile(file.row.rowIndex)"
                    />
                </template>
            </el-table-column>
        </el-table>
        <div class="upload-dialog-wrapper">
            <el-dialog
                v-model="ui.showUploadDialog"
                title="上传文件"
                width="600px"
                :close-on-click-model="false"
                :close-on-press-escape="false"
                :show-close="true"
            >
                <el-upload
                    drag
                    :action="ui.urlFileUpload"
                    name="files"
                    :show-file-list="false"
                    :data="ui.uploadParameters"
                    :on-success="onUploadSuccess"
                    :before-upload="onBeforeUpload"
                >
                    <el-icon class="el-icon--upload">
                        <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或<em>点击上传</em>
                    </div>
                </el-upload>
            </el-dialog>
            <el-dialog
                v-model="ui.isPDF"
                :close-on-click-model="false"
                :close-on-press-escape="false"
                :show-close="true"
                align-center
                title="文件预览"
                width="1024px"
            >
                <VueOfficePdf
                    v-if="ui.isPDF"
                    :src="ui.fileURL"
                    style="height:calc(100vh - 100px);"
                    @error="errorHandle"
                />
            </el-dialog>
            <el-dialog
                v-model="ui.isDOCX"
                :close-on-click-model="false"
                :close-on-press-escape="false"
                :show-close="true"
                align-center
                title="文件预览"
                width="1024px"
            >
                <VueOfficeDocx
                    v-if="ui.isDOCX"
                    :src="ui.fileURL"
                    style="height:calc(100vh - 100px);"
                    @error="errorHandle"
                />
            </el-dialog>
            <el-dialog
                v-model="ui.isXLSX"
                :close-on-click-model="false"
                :close-on-press-escape="false"
                :show-close="true"
                align-center
                title="文件预览"
                width="1024px"
            >
                <VueOfficeExcel
                    :src="ui.fileURL"
                    style="height:calc(100vh - 100px);"
                    @error="errorHandle"
                />
            </el-dialog>
        </div>
    </div>
</template>
<script lang="ts">
import {reactive, ref}  from "vue";
import { type UploadProps, type UploadFile, type UploadFiles, ElMessage, ElMessageBox } from "element-plus";
import { type RegulatoryData, type RegulatoryFile} from "@/types/regulatory/regulatory.ts";
import { addNewRegulatory, type AddNewRegulatoryResponse, type Render} from "@/utils/regulatory_utils.ts";
import { type UploadedFile, type UploadFileResponse } from "@/types/upload_file.ts";
import {API_URL} from "@/utils/config.ts";
import { getFileType } from "@/utils/utils";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import VueOfficeExcel from "@vue-office/excel";

// 引入相关样式
import "@vue-office/docx/lib/index.css";
import "@vue-office/excel/lib/index.css";

interface UI{
    showUI: boolean;
    showUploadDialog: boolean;
    showPreviewDialog: boolean;
    urlFileUpload: string;
    uploadParameters: {
        fileName: string;
    };
    newRegulatory: RegulatoryData;
    showFileList: boolean;
    isPDF: boolean;
    isDOCX: boolean;
    isXLSX: boolean;
    fileURL: string;
};

export default {
    name: "NewRegulatory",
    components: {VueOfficePdf,
        VueOfficeDocx,
        VueOfficeExcel,},
    setup()
    {
        const ui: UI = reactive({
            showUI: true,
            showUploadDialog: false,
            showPreviewDialog: false,
            urlFileUpload: API_URL.URL_UPLOAD_FILE,
            uploadParameters: {
                fileName: "1234",
            },
            newRegulatory: {
                department_name: "",
                release_year: "",
                regulatory_name: "",
                comment: "",
                regulatory_files: [],
            },
            showFileList: false,
            isPDF: false,
            isDOCX: false,
            isXLSX: false,
            fileURL: "",
        });

        const regulatoryName = ref<any>( null );
        const departmentName = ref<any>( null );
        const releaseYear = ref<any>( null );
        const comment = ref<any>( null );


        const render: Render = function ( response: AddNewRegulatoryResponse ) :void
        {
            // if ( response.success === true )
            // { }
        };

        const headerCellStyle = reactive(
            {
                textAlign: "center",
            }
        );
        const cellStyle = reactive({
            textAlign: "center",
        });

        const showUploadFileDialog = (): void =>
        {
            ui.showUploadDialog = true;
        };

        /* 表格操作相关 */
        /**
         * 删除对应的上传文件记录。
         * @param rowId 行号
         */
        const onDeleteUploadedFile = ( rowId: number ): void =>
        {
            console.log( `点击的rowid：${rowId}。` );
            ElMessage.info( `选取的行号：${rowId}。` );

            ElMessageBox.confirm(
                "确认删除文件？",
                "删除文件",
                {
                    confirmButtonText: "确定",
                    type: "warning",
                    center: true,
                }
            )
                .then(()=>
                {
                    ui.newRegulatory.regulatory_files?.splice( rowId, 1 );
                })
                .catch(()=>{});
        };

        const onPreviewUploadedFile = ( rowId: number ): void =>
        {
            // ui.showPreviewDialog = true;
            ui.fileURL = encodeURI( ui.newRegulatory.regulatory_files[rowId]?.file_url + "/" + ui.newRegulatory.regulatory_files[rowId]?.regulatory_file_name );

            console.log( "完整路径：", ui.fileURL );

            ui.isDOCX = false;
            ui.isPDF = false;
            ui.isXLSX = false;

            switch ( ui.newRegulatory.regulatory_files[rowId].file_type )
            {
                case "WPS文档":
                    ui.isDOCX = true;
                    break;
                case "WPS表格":
                    ui.isXLSX = true;
                    break;
                case "PDF文档":
                    ui.isPDF = true;
                    break;
                default:
                    break;
            }
        };

        /**
         * 用来给 el-table 行设置样式。
         * 其中给row加一个参数rowIndex，用行号赋值。
         * @param element-plus给于的参数
         */
        const tableRowClassName = ({row, rowIndex,}: {row:any,
            rowIndex:number}): void =>
        {
            console.log( `行${row}设置行号${rowIndex}。` );

            row.rowIndex = rowIndex;
        };

        /**
         * 上传成功的响应函数。
         * @param response
         * @param uploadFile
         * @param uploadFiles
         */
        const onUploadSuccess: UploadProps["onSuccess"] = ( response: UploadFileResponse, uploadFile: UploadFile, uploadFiles: UploadFiles ): void =>
        {
            console.log( "上传制度文件响应：", response.fileList );
            console.log( `上传文件:${uploadFile}` );
            console.log( `上传多文件:${uploadFiles}` );

            ui.showUploadDialog = false;

            //  先判断成功标志位
            if ( response.success )
            {
                // 成功，把文件写入清单
                if ( response.fileList === null || response.fileList.length === 0 )
                {
                    // 上传文件路径有问题，提示一下
                    ElMessageBox.confirm(
                        "上传文件的保存路径有误，请联系开发人员。",
                        "上传文件错误",
                        {
                            confirmButtonText: "确定",
                            type: "warning",
                            center: true,
                        }
                    )
                        .then((): void => {})
                        .catch((): void => {});
                }

                const uploadedFile: RegulatoryFile = {
                    regulatory_file_name_original: response.fileList[0].originFileName ?? "",
                    regulatory_file_name: response.fileList[0].fileName ?? "",
                    local_file_path: response.fileList[0]?.absoluteFilePath ?? "",
                    file_type: getFileType( response.fileList[0]?.fileName ),
                    file_url: API_URL.URL_PREFIX + "/" + response.fileList[0]?.relativeFilePath,
                };

                ui.newRegulatory.regulatory_files?.push( uploadedFile );
                console.log( "文件列表", ui.newRegulatory.regulatory_files );
            }
            else
            {
                // 失败了，提示一下
                ElMessageBox.confirm(
                    response.message,
                    "上传文件错误",
                    {
                        confirmButtonText: "确定",
                        type: "warning",
                        center: true,
                    }
                )
                    .then((): void => {})
                    .catch((): void => {});
            }
        };

        const onBeforeUpload = ( uploadFile: UploadFile ): boolean =>
        {
            const result = true;

            console.log( "上传的文件名", uploadFile.name );

            return result;
        };

        const errorHandle = ()=>
        {
            ElMessage.error( "渲染文档出错！" );
        };

        /**
         * 创建新制度事件
         */
        const onCreateNewRegulatory = () =>
        {
            console.log( "制度对象：", ui.newRegulatory );

            // 防御验证
            if ( ui.newRegulatory.regulatory_name.length === 0 )
            {
                ElMessage.error( "制度名称名称不能为空！" );
                console.log( regulatoryName );
                regulatoryName.value.focus();

                return;
            }

            if ( ui.newRegulatory.department_name.length === 0 )
            {
                ElMessage.error( "部门名称不能为空！" );
                console.log( regulatoryName );
                departmentName.value.focus();

                return;
            }

            if ( ui.newRegulatory.release_year.length === 0 )
            {
                ElMessage.error( "发布年份不能为空！" );

                releaseYear.value.focus();

                return;
            }

            if ( ui.newRegulatory.regulatory_files.length === 0 )
            {
                ElMessage.error( "没有上传相关制度文件！" );

                console.log( ui.newRegulatory.regulatory_files );

                return;
            }

            addNewRegulatory( ui.newRegulatory, ()=>{});
        };

        return {
            ui,
            regulatoryName,
            headerCellStyle,
            cellStyle,
            onUploadSuccess,
            tableRowClassName,
            showUploadFileDialog,
            onDeleteUploadedFile,
            onPreviewUploadedFile,
            onCreateNewRegulatory,
            onBeforeUpload,
            errorHandle,
        };
    },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/public/_public.scss";

.wrapper {
    // max-width: 800px;
    min-width: 1024px;
    margin: 10px 10px 10px 10px;

    >*+* {
        margin-top: 10px;
    }
}

.query-box-wrapper
{
    @include query-box-wrap;
}

:deep(.el-input) .el-input__inner {
    text-align: center;
}

:deep(.el-dialog) {
    min-width: calc(100wh - 100px);
    max-width: calc(100wh - 100px);
}
</style>