<template>
    <div class="attachment pl-4 pr-4 pt-3 pb-3 h-full flex flex-col">
        <div class="flex justify-between">
            <div class="title">附件</div>
            <div>
                <el-upload ref="uploadRef" :http-request="httpUploadFile" :limit="1" :show-file-list="false"
                    element-loading-text="正在上传" :loading="allLoading.uploadFileLoading">
                    <template #trigger>
                        <el-button type="primary">上传</el-button>
                    </template>
                </el-upload>
            </div>
        </div>
        <div class="flex-1 overflow-auto pt-3">
            <el-table :data="attachmenttable" border style="width: 100%;height: 200px;">
                <el-table-column prop="documentName" label="附件名称" />
                <el-table-column prop="size" label="附件大小" width="120" />
                <el-table-column prop="creatorName" label="上传人" width="120">
                    <template #default="scope">
                        <TextTranslation translationTypes="userName" :translationValue="scope.row.creatorName">
                        </TextTranslation>
                    </template>
                </el-table-column>
                <el-table-column prop="indate" label="上传时间" width="180" />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" size="large" @click="fileDownload(scope.row)">下载</el-button>
                        <el-button link type="primary" size="large" @click="operation(scope.row)">重命名</el-button>
                        <el-button link type="danger" size="large" @click="fileDetele(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 弹窗 -->
        <el-dialog v-model="allVisible.renameDialogVisible" width="800" :show-close="false" top="10vh">
            <template #header="{ close, titleId, titleClass }">
                <div class="flex justify-between items-center border-b pb-3 dialog-header">
                    <h4 :id="titleId">{{ '文件重命名' }}</h4>
                    <div>
                        <el-button type="primary" @click="saveEditClue()"
                            :loading="allLoading.saveLoading">保存</el-button>
                        <el-button @click="allVisible.renameDialogVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="pt-3">
                <el-input v-model.trim="fileFormVal.name" style="width: 100%" class="pb-3" clearable />
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { post, uploadFile } from '@/utils/request';
import { UploadRequestOptions } from 'element-plus';
import { ref, reactive, onMounted, onUnmounted, inject, watchEffect } from 'vue'
import { URLFILEDETELE, URL_REFNAME, URL_UPLOADFILE } from '@/pages/api';
import { downloadFile } from '@/utils/tools';

const globalPopup = inject<GlobalPopup>('globalPopup')
const emits = defineEmits(['refreshData']);
const props = defineProps<{
    data: any
}>()

type fileFormVal = {
    id?: string,
    name?: string
}

const uploadRef = ref<any>()
const information = ref<any>({})
const attachmenttable = ref([])
const fileTypeStr = ref('') // 文件重命名的类型
const fileFormVal = ref<fileFormVal>({})
const allLoading = reactive({
    uploadFileLoading: false,
    saveLoading: false
})
const allVisible = reactive({
    renameDialogVisible: false
})

function saveEditClue() {
    if (!fileFormVal.value.name) {
        globalPopup?.showWarning('请输入文件名称')
        return
    }
    allLoading.saveLoading = true
    post(URL_REFNAME, {
        fileId: fileFormVal.value.id,
        newName: fileFormVal.value.name + '.' + fileTypeStr.value
    }).then(() => {
        allVisible.renameDialogVisible = false
        globalPopup?.showSuccess('重命名成功')
        emits('refreshData');
    }).finally(() => {
        allLoading.saveLoading = false
    })
}

function operation(item: any) {
    fileTypeStr.value = item.documentName.split('.').pop()
    fileFormVal.value = {
        id: item.id,
        name: item.documentName.replace(/\.[^/.]+$/, '')
    }
    allVisible.renameDialogVisible = true
}

function fileDownload(item: any) {
    downloadFile(`${item.url}`, item.documentName)
}

function fileDetele(item: any) {
    post(URLFILEDETELE, { fileIds: item.id }).then(() => {
        globalPopup?.showSuccess('删除成功')
        emits('refreshData');
    })
}

// 上传附件
async function httpUploadFile(param: UploadRequestOptions) {
    const id = information.value.id
    const formData = new FormData();
    formData.append('file', param.file)
    formData.append('contactsId', id)
    allLoading.uploadFileLoading = true
    const res = await uploadFile(URL_UPLOADFILE, formData).finally(() => {
        allLoading.uploadFileLoading = false
        uploadRef.value.clearFiles()
    })
    if (res.code == 'ok') {
        globalPopup?.showSuccess(res.msg || '')
        emits('refreshData');
        return
    }
    globalPopup?.showError(res.msg || '')
    return res
}

watchEffect(() => {
    const { data } = props
    information.value = data
    attachmenttable.value = data.contactsDocumentList || []
});
</script>
<style scoped lang="scss"></style>
