<template>
    <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        class="info-upload"
        :action="action"
        :headers="headers"
        :data="row.data?.()"
        :method="props.row.method"
        :multiple="props.row.multiple"
        :auto-upload="props.row.autoUpload"
        :name="props.row.name || 'file'"
        :show-file-list="props.row.showFileList"
        :drag="props.row.drag"
        :accept="props.row.accept || 'text'"
        :limit="props.row.limit"
        :on-change="handleChange"
        :on-preview="props.row.preview?.()"
        :on-remove="(file: any, fileList: any) => props.row.remove?.(file, fileList)"
        :on-success="(res: any, file: any, fileList: any) => props.row.success?.(res, file, fileList)"
        :on-error="(error: any, uploadFile: any, uploadFiles: any) => props.row.error?.(error, uploadFile, uploadFiles)"
        :on-exceed="onExceedHandler"
        :before-upload="beforeUpload"
    >
        <template
            v-if="props.row.trigger"
            #trigger
        >
            <el-button
                :disabled="props.row.disabled?.()"
                size="default"
                @click="submitUpload"
            >
                {{ $t(props.row.trigger || '') }}
            </el-button>
        </template>

        <div
            v-if="props.row.isDrag"
            style="display: flex; align-items: center; padding: 10px 40px"
        >
            <el-button
                type="primary"
                link
                :disabled="props.row.disabled?.()"
                size="small"
                @click="submitUpload"
            >
                {{ $t('clickUpload') }}
            </el-button>
            <span style="padding: 0 4px 0 2px">/</span>
            <span>{{ $t('dragToThisArea') }}</span>
        </div>
        <el-button
            v-if="props.row.showClear"
            class="delete-btn"
            plain
            @click="handleClearFiles"
        >
            <el-icon>
                <Delete />
            </el-icon>
        </el-button>
        <template v-if="props.row.tip || showTipBtn"
                  #tip
        >
            <div
                v-if="!showTipBtn"
                class="el-upload__tip"
            >
                {{ $t(props.row.tip) }}
            </div>
            <el-button
                v-else
                type="primary"
                text
                @click="props.row.tipBtnClick"
            >
                {{ $t(props.row.tipBtnText) }}
            </el-button>
        </template>
    </el-upload>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, PropType, watch } from 'vue'
import { __getItem, ObjectInterface } from '../../../script/index'
import { UploadInstance, UploadUserFile, UploadProps, UploadRawFile, genFileId } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { UploadInterface } from './index'

const props = defineProps({
    row: {
        type: Object as PropType<UploadInterface>,
        default: () => {
        }
    },
    modelData: {
        type: Object,
        default: () => {
        }
    }
})
const showTipBtn = ref(false)
if (props.row.showTipBtn) {
    props.row.showTipBtn(showTipBtn)
}
const action = computed(() => {
    const api = props.row.api
    const baseURL = JSON.parse(window?.sessionStorage?.getItem('serveConfig') || '{}')?.baseURL
    if (baseURL === '/') return api
    return `${baseURL || '/api'}${api}`
})
const uploadRef = ref<UploadInstance>()
const headers = reactive<ObjectInterface>({})

const fileList = ref<UploadUserFile[]>([])

// 初始化 fileList
watch(
    () => props.row?.model ? props.modelData?.[props.row.model] : undefined,
    (val) => {
        if (!val) {
            fileList.value = []
            return
        }
        // 支持字符串、对象、数组格式
        const list = Array.isArray(val) ? val : [val]
        fileList.value = list.map((item: any) => ({
            name: item.split('/').pop() || item,
            url: item,
            status: 'success' as const
        }))
    },
    { immediate: true }
)

const beforeUpload = () => {
    Object.assign(headers, props.row.headers)
    const token = __getItem('serveConfig')?.token
    headers[token] = __getItem('x-auth-token')
    return true
}

const handleClearFiles = (): void => {
    uploadRef.value!.clearFiles()
}
const submitUpload = (): void => {
    uploadRef.value!.submit()
}

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    props.row.on?.(uploadRef.value, uploadFiles, fileList)
}

const onExceedHandler = (files: File[], uploadFiles: UploadUserFile[]) => {
    if (!props.row.isReplace) return
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}
</script>
<style lang="scss" scoped>
.info-upload {
    width: 100%
}
:deep(.el-upload-list .el-upload-list__item .el-icon--close-tip) {
    display: none !important;
}

.delete-btn {
    margin-left: 10px;
}

:deep(.el-upload__tip) {
    margin-top: 0;
}
</style>
