<template>
    <!-- 全局文件下载 -->
    <view class="upload" :style="style">
        <view class="upload-list">
            <view class="upload-item" v-for="(item, index) in getFileList" :key="item.id">
                <view class="upload-item-left">
                    <view class="label">
                        <template v-if="['image', 'png', 'jpg', 'jpeg', 'gif'].includes(item[typeField].toLowerCase())">
                            <image src="/static/mocp/image/common/image.png" mode="widthFix" />
                        </template>
                        <template v-else-if="['video', 'mp4'].includes(item[typeField].toLowerCase())">
                            <image src="/static/mocp/image/common/video.png" mode="widthFix" />
                        </template>
                        <template v-else>
                            <image src="/static/mocp/image/common/pdf.png" mode="widthFix" />
                        </template>
                        <view class="u-line-1">{{ item.fileName }}</view>
                    </view>
                    <view class="tool" @tap="previewFile(item.fileUrl)"><up-icon name="eye" size="18" color="#4E5969"></up-icon></view>
                </view>
                <view class="upload-item-right" @tap="deleteFile(index)" v-if="showUpload">
                    <global-icon icon="delete-01" color="#F53F3F"></global-icon>
                </view>
            </view>
        </view>
        <template v-if="showUpload">
            <view class="upload-button" v-if="isLoading">
                <up-loading-icon text="上传中" textSize="14"></up-loading-icon>
            </view>
            <lsj-upload
                width="640rpx"
                :height="isLoading ? '0rpx' : '88rpx'"
                :option="getOptions"
                :size="30"
                :instantly="true"
                :distinct="true"
                @uploadEnd="onuploadEnd"
                @change="change"
            >
                <view class="upload-button">
                    <up-icon name="plus" size="16" color="#4E5969"></up-icon>
                    <text class="txt">上传文件</text>
                </view>
            </lsj-upload>
        </template>
        <up-modal
            :width="250"
            content="确认删除吗？删除后不可恢复!"
            :show="show"
            showCancelButton
            closeOnClickOverlay
            @confirm="confirm"
            @cancel="show = false"
            @close="show = false"
        ></up-modal>
    </view>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import { cloneDeep } from 'lodash'
import { httpInterceptor } from 'mocp/utils/http'
import { onBeforeUnmount } from 'vue'

const es = defineEmits(['update:modelValue', 'change', 'getFileList'])
const ps = defineProps({
    style: {
        type: Object,
        default: () => {
            return {}
        }
    },
    fileList: {
        type: Array,
        default: () => {
            return []
        }
    },
    typeField: {
        type: String,
        default: 'fileType'
    },
    url: {
        type: String,
        default: '/resource/uploadFile'
    },
    mapFieldName: {
        type: String,
        default: ''
    },
    mapFieldSplit: {
        type: String,
        default: ','
    },
    showUpload: {
        type: Boolean,
        default: true
    }
})
const fileList = ref([])
watch(
    () => ps.fileList,
    (value) => {
        fileList.value = cloneDeep(value)
    },
    { immediate: true }
)
const getFileList = computed(() => {
    return fileList.value.map((item) => {
        return { ...item, url: item.fileUrl }
    })
})
const getOptions = computed(() => {
    return httpInterceptor({ url: ps.url, name: 'file' })
})
// 删除文件
const show = ref(false)
const index = ref(-1)
const deleteFile = (_index) => {
    show.value = true
    index.value = _index
}
//确认删除
const confirm = () => {
    show.value = false
    fileList.value.splice(index.value, 1)
}
//预览图片
const previewFile = (fileUrl) => {
    uni.showLoading({
        title: '正在打开文件',
        mask: true
    })
    uni.downloadFile({
        url: fileUrl,
        success: function (res) {
            var filePath = res.tempFilePath
            uni.openDocument({
                filePath: filePath,
                showMenu: true,
                success: function (res) {
                    uni.hideLoading()
                    console.log('打开文件成功')
                },
                fail: function () {
                    uni.hideLoading()
                    uni.$mocpMessage.showToast('打开文件失败')
                }
            })
        },
        fail: function () {
            uni.hideLoading()
            uni.$mocpMessage.showToast('打开文件失败')
        }
    })
}
const isLoading = ref(false)
const onuploadEnd = (e) => {
    if (e.type == 'success') {
        const res = JSON.parse(e.responseText)
        console.log('接口响应结果:', res)
        if (res.code == 200) {
            res.data[ps.mapFieldName] = res.data.id
            fileList.value.push(res.data)
            uni.$mocpMessage.showToast(res.message || '上传成功')
        } else {
            uni.$mocpMessage.showToast(res.message || '请求错误')
        }
    } else {
        uni.$mocpMessage.showToast('上传失败')
    }
    isLoading.value = false
}
const change = (e) => {
    isLoading.value = true
}
watch(
    fileList,
    (value) => {
        let files = cloneDeep(value)
        if (ps.mapFieldName) {
            files = files.map((v) => v[ps.mapFieldName]).join(ps.mapFieldSplit)
        }
        es('update:modelValue', files)
        es('change', files)
        es('getFileList', cloneDeep(value))
    },
    { deep: true, immediate: true }
)
onBeforeUnmount(() => {
    uni.$emit('$upload-hide', {})
})
</script>
<style lang="scss" scoped>
.upload {
    &-button {
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f3f3f3;
        width: 640rpx;
        height: 88rpx;
        line-height: 88rpx;
        .txt {
            color: $mocp-text-5;
        }
    }
    &-item {
        height: 72rpx;
        line-height: 72rpx;
        margin-bottom: 16rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &-left {
            width: 100%;
            display: flex;
            align-items: center;
            background: #f3f3f3;
            box-sizing: border-box;
            padding: 0 20rpx 0 24rpx;
            border-radius: 4rpx;
            .label {
                flex: auto;
                display: flex;
                align-items: center;
                margin-right: 10rpx;
                color: $mocp-text-5;
                image {
                    width: 32rpx;
                    min-width: 32rpx;
                    margin-right: 20rpx;
                }
                .name {
                    flex: auto;
                    word-break: break-all;
                }
            }
        }
        &-right {
            width: 46rpx;
            text-align: right;
        }
    }
}
</style>
