<template>
    <view class="uploader-container flex wrap">
        <u-upload
            @on-change="handleCallback"
            :action="action"
            :header="{ token: token, version: versions }"
            :deletable="deletable"
            :max-count="maxUpload"
            :showProgress="showProgress"
            @on-remove="remove"
            :multiple="mutiple"
            :width="previewSize"
            :height="previewSize"
            ref="upload"
            maxSize="10485760"
        />
    </view>
</template>

<script lang="ts" setup>
import { version } from '@/config/app'
import { useUserStore } from '@/stores/user'
import { toast } from '@/utils/util'
import { onMounted, ref } from 'vue'

const userStore = useUserStore()
/** Emit Start **/
const emit = defineEmits(['update:modelValue'])
/** Emit End **/

/** Props Start **/
const props = withDefaults(
    defineProps<{
        mutiple?: boolean // 默认不允许多选图片
        maxUpload?: number // 限制上传文件数量
        previewSize?: number // upload显示的大小
        deletable?: boolean // 是否可删除
        tips?: string //提示
        showProgress?: false // 是否显示进度条
    }>(),
    {
        mutiple: false,
        maxUpload: 1,
        previewSize: 160,
        deletable: true,
        tips: '上传图片',
        showProgress: false
    }
)
/** Props End **/

/** Data Start **/
const action = ref<string | null>('')
const token = ref<string | null>('')
const fileList = ref<Array<any>>([])
const versions = ref<string | null>(version)
const upload = ref()
/** Data End **/

/** Methods Start **/
/**
 * @param { params } 上传返回值
 * @return { void }
 * @description 上传，不管成不成功都返回数据｜提示
 */
const handleCallback = (params: any) => {
    toast(JSON.parse(params.data).msg)
    if (JSON.parse(params.data).code == 200) {
        fileList.value.push(JSON.parse(params.data).data.path)
        emit('update:modelValue', fileList.value)
    } else {
        uni.$emit('popOneLists')
    }
}

/**
 * @param { event } 索引值
 * @return { void }
 * @description 删除一个图片
 */
const remove = (event: number | string) => {
    fileList.value.splice(event, 1)
    emit('update:modelValue', fileList.value)
}
/** Methods End **/

/** Life Cycle Start **/
onMounted(() => {
    action.value = `${import.meta.env.VITE_APP_BASE_URL}/api/upload/image`
    token.value = userStore.token
})
</script>

<style lang="scss" scoped>
.uploader-container {
    .uplader-upload {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        padding-top: 30rpx;
        text-align: center;
        margin: 11rpx;
        border: 2px dashed #e5e5e5;
        background-color: #ffffff;

        > view {
            color: #bbb;
        }
    }
}
</style>
