<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 v-permission="['customerEdit']">
                <el-upload ref="uploadRef" :http-request="httpUploadFile" :limit="1" :show-file-list="false"
                    element-loading-text="正在上传">
                    <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="name" label="附件名称" />
                <el-table-column prop="size" label="附件大小" width="120" />
                <el-table-column prop="userName" label="上传人" width="120">
                    <template #default="scope">
                        <TextTranslation translationTypes="userName" :translationValue="scope.row.userName"></TextTranslation>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="上传时间" width="180" sortable />
                <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="showVisible(scope.row)">重命名</el-button>
                        <el-button link type="danger" size="large" @click="deteleFile(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 弹窗 -->
        <el-dialog v-model="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()">保存</el-button>
                        <el-button @click="renameDialogVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="pt-3">
                <el-input v-model.trim="renameVal" 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, defineExpose, inject, watchEffect } from 'vue'
import { URL_DETELEFILE, URL_REFFILENAME, URL_UPLOADFILE } from '../api';
import { confirmAction, downloadFile } from '@/utils/tools';
import { formatDate } from '@/utils/times';

const emits = defineEmits(['refreshData']);
const globalPopup = inject<GlobalPopup>('globalPopup')
const props = defineProps<{
    data: any
}>()
const attachmenttable = ref([])
const information = ref<any>({})
const uploadRef = <any>ref()
const renameDialogVisible = ref(false)
const transitionVal = ref<any>({})
const renameVal = ref('')

// 下载文件
function fileDownload(item: any) {
    downloadFile(`${item.path}`, item.name)
}

// 删除文件
function deteleFile(item: any) {
    const id = item.id
    confirmAction(`确定删除【${item.name}】文件吗？`).then(() => {
        post(URL_DETELEFILE, { id }).then((_res) => {
            globalPopup?.showSuccess('删除成功')
            emits('refreshData')
        })
    })
}

// 保存重命名
function saveEditClue() {
    if (!renameVal.value) {
        globalPopup?.showWarning('请输入文件名称')
        return
    }
    // const id = information.value.id
    const id = transitionVal.value.id
    post(URL_REFFILENAME, { name: renameVal.value, id: id }).then((res) => {
        renameDialogVisible.value = false
        globalPopup?.showSuccess(res.msg || '')
        emits('refreshData')
    }).catch((_err) => { })
}

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

// 显示弹窗
function showVisible(item: any) {
    renameVal.value = JSON.parse(JSON.stringify(item.name))
    transitionVal.value = JSON.parse(JSON.stringify(item))
    renameDialogVisible.value = true
}

watchEffect(() => {
    information.value = props.data
    attachmenttable.value = (props.data.files || []).map((item: any) => {
        return {
            ...item,
            createTime: formatDate(new Date(item.createTime))
        }
    })
});

// 生命周期钩子
onMounted(() => {
});
</script>
<style scoped lang="scss">
.attachment {
    .title {
        font-size: 18px;
        color: #606266
    }
}
</style>