<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-if="['pdf'].includes(item[typeField].toLowerCase())">
                            <image src="/static/mocp/image/common/pdf.png" mode="widthFix" />
                        </template>
                        <template v-else-if="['ppt', 'txt'].includes(item[typeField].toLowerCase())">
                            <image src="/static/mocp/image/common/ppt.png" mode="widthFix" />
                        </template>
                        <template v-else>
                            <image src="/static/mocp/image/common/unknown.png" mode="widthFix" />
                        </template>
                        <view class="u-line-1">{{ item[nameField] }}</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="getShowUpload">
                    <global-icon icon="delete-01" color="#F53F3F"></global-icon>
                </view>
            </view>
        </view>
        <view v-if="getFileList.length == 0 && !getShowUpload">暂无文件</view>
        <template v-if="getShowUpload">
            <view class="upload-button" v-if="isLoading">
                <up-loading-icon text="上传中" textSize="14"></up-loading-icon>
            </view>
            <lsj-upload
                width="640rpx"
                :height="isLoading || !(getFileList.length < 1 || multiple) ? '0rpx' : '88rpx'"
                :option="getOptions"
                :instantly="true"
                :distinct="true"
                @uploadEnd="onuploadEnd"
                @change="change"
            >
                <view class="upload-button" v-if="getFileList.length < 1 || multiple">
                    <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, ref, watch } from 'vue'
import { cloneDeep } from 'lodash'
import { httpInterceptor } from 'mocp/utils/http'
import { onBeforeUnmount } from 'vue'
import { previewFile } from 'mocp/utils/tool'

const es = defineEmits(['update:modelValue', 'change', 'getFileList'])
const ps = defineProps({
    //是否支持上传多个文件
    multiple: {
        type: Boolean,
        default: true
    },
    style: {
        type: Object,
        default: () => {
            return {}
        }
    },
    fileList: {
        type: [Array, String],
        default: () => {
            return []
        }
    },
    typeField: {
        type: String,
        default: 'fileExt'
    },
    nameField: {
        type: String,
        default: 'fileName'
    },
    url: {
        type: String,
        default: '/resource/uploadFile'
    },
    mapFieldName: {
        type: String,
        default: ''
    },
    mapFieldSplit: {
        type: String,
        default: ','
    },
    showUpload: {
        type: Boolean,
        default: true
    },
    limit: {
        type: Number,
        default: 10
    }
})
const fileList = ref([])
const showUpload = ref(true)
const getShowUpload = computed(() => {
    return ps.showUpload && showUpload.value
})
watch(
    () => ps.fileList,
    (value) => {
        if (value) {
            if (Array.isArray(value)) {
                fileList.value = cloneDeep(value)
            } else {
                fileList.value = JSON.parse(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 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.success(res.message || '上传成功')
        } else {
            uni.$mocpMessage.error(res.message || '请求错误')
        }
    } else {
        uni.$mocpMessage.error('上传失败')
    }
    isLoading.value = false
}
const change = () => {
    isLoading.value = true
}
watch(
    fileList,
    (value) => {
        if (value.length >= ps.limit) {
            showUpload.value = false
        } else {
            showUpload.value = true
        }
        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', {})
    uni.$off('$upload-show', {})
})
</script>
<style lang="scss" scoped>
.upload {
    flex: 1;
    &-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>
