<template>
    <view class="van-uploader">
        <view class="van-uploader__wrapper">
            <!-- 预览样式 -->
            <view v-if="previewImage" class="van-uploader__preview" :data-index="index" @tap="onClickPreview" v-for="(item, index) in lists" :key="index">
                <image
                    v-if="item.isImage"
                    :mode="imageFit"
                    :src="item.url || item.path"
                    :alt="item.name || '图片' + index"
                    class="van-uploader__preview-image"
                    :style="'width: ' + utils.addUnit(previewSize) + '; height: ' + utils.addUnit(previewSize) + ';'"
                    :data-index="index"
                    @tap="onPreviewImage"
                />

                <view v-else class="van-uploader__file" :style="'width: ' + utils.addUnit(previewSize) + '; height: ' + utils.addUnit(previewSize) + ';'">
                    <van-icon name="description" class="van-uploader__file-icon" />
                    <view class="van-uploader__file-name van-ellipsis">{{ item.name || item.url || item.path }}</view>
                </view>

                <view v-if="item.status === 'uploading' || item.status === 'failed'" class="van-uploader__mask">
                    <van-icon v-if="item.status === 'failed'" name="warning-o" class="van-uploader__mask-icon" />
                    <van-loading v-else class="van-uploader__loading" />
                    <text v-if="item.message" class="van-uploader__upload-text">{{ item.message }}</text>
                </view>

                <view v-if="deletable && item.deletable" :data-index="index" class="van-uploader__preview-delete" @tap.stop.prevent="deleteItem">
                    <van-icon name="clear" class="van-uploader__preview-delete__icon" />
                </view>
            </view>

            <!-- 上传样式 -->
            <block v-if="isInCount">
                <view class="van-uploader__slot" @tap="startUpload">
                    <slot />
                </view>

                <!-- 默认上传样式 -->
                <view
                    v-if="showUpload"
                    :class="'van-uploader__upload ' + (disabled ? 'van-uploader__upload--disabled' : '')"
                    :style="'width: ' + utils.addUnit(previewSize) + '; height: ' + utils.addUnit(previewSize) + ';'"
                    @tap="startUpload"
                >
                    <van-icon :name="uploadIcon" class="van-uploader__upload-icon" />
                    <text v-if="uploadText" class="van-uploader__upload-text">{{ uploadText }}</text>
                </view>
            </block>
        </view>
    </view>
</template>
<script module="utils" lang="wxs" src="@/node_modules/@vant/weapp/dist/wxs/utils.wxs"></script>
<script>
import { VantComponent } from '../common/component';
import { isImageFile, isVideo, chooseFile, isPromise } from './utils';
import { chooseImageProps, chooseVideoProps } from './shared';
export default {
    data() {
        return {
            lists: [],
            isInCount: true,
            previewImage: '',
            imageFit: '',
            deletable: '',
            showUpload: '',
            disabled: false,
            uploadIcon: '',
            uploadText: ''
        };
    },
    props: Object.assign(
        Object.assign(
            {
                disabled: Boolean,
                multiple: Boolean,
                uploadText: String,
                useBeforeRead: Boolean,
                afterRead: null,
                beforeRead: null,
                previewSize: {
                    type: null,
                    value: 90
                },
                name: {
                    type: [Number, String],
                    value: ''
                },
                accept: {
                    type: String,
                    value: 'image'
                },
                fileList: {
                    type: Array,
                    value: [],
                    observer: 'formatFileList'
                },
                maxSize: {
                    type: Number,
                    value: Number.MAX_VALUE
                },
                maxCount: {
                    type: Number,
                    value: 100
                },
                deletable: {
                    type: Boolean,
                    value: true
                },
                showUpload: {
                    type: Boolean,
                    value: true
                },
                previewImage: {
                    type: Boolean,
                    value: true
                },
                previewFullImage: {
                    type: Boolean,
                    value: true
                },
                imageFit: {
                    type: String,
                    value: 'scaleToFill'
                },
                uploadIcon: {
                    type: String,
                    value: 'photograph'
                }
            },
            chooseImageProps
        ),
        chooseVideoProps
    ),
    methods: {
        formatFileList() {
            const { fileList = [], maxCount } = this;
            const lists = fileList.map((item) =>
                Object.assign(Object.assign({}, item), {
                    isImage: typeof item.isImage === 'undefined' ? isImageFile(item) : item.isImage,
                    deletable: typeof item.deletable === 'undefined' ? true : item.deletable
                })
            );
            this.setData({
                lists,
                isInCount: lists.length < maxCount
            });
        },
        getDetail(index) {
            return {
                name: this.name,
                index: index == null ? this.fileList.length : index
            };
        },
        startUpload() {
            const { maxCount, multiple, accept, lists, disabled } = this;
            if (disabled) {
                return;
            }
            chooseFile(
                Object.assign(Object.assign({}, this), {
                    maxCount: maxCount - lists.length
                })
            )
                .then((res) => {
                    let file = null;
                    if (isVideo(res, accept)) {
                        file = Object.assign(
                            {
                                path: res.tempFilePath
                            },
                            res
                        );
                    } else {
                        file = multiple ? res.tempFiles : res.tempFiles[0];
                    }
                    this.onBeforeRead(file);
                })
                .catch((error) => {
                    this.$emit('error', error);
                });
        },
        onBeforeRead(file) {
            const { beforeRead, useBeforeRead } = this;
            let res = true;
            if (typeof beforeRead === 'function') {
                res = beforeRead(file, this.getDetail());
            }
            if (useBeforeRead) {
                res = new Promise((resolve, reject) => {
                    this.$emit(
                        'before-read',
                        Object.assign(
                            Object.assign(
                                {
                                    file
                                },
                                this.getDetail()
                            ),
                            {
                                callback: (ok) => {
                                    ok ? resolve() : reject();
                                }
                            }
                        )
                    );
                });
            }
            if (!res) {
                return;
            }
            if (isPromise(res)) {
                res.then((data) => this.onAfterRead(data || file));
            } else {
                this.onAfterRead(file);
            }
        },
        onAfterRead(file) {
            const { maxSize } = this;
            const oversize = Array.isArray(file) ? file.some((item) => item.size > maxSize) : file.size > maxSize;
            if (oversize) {
                this.$emit(
                    'oversize',
                    Object.assign(
                        {
                            file
                        },
                        this.getDetail()
                    )
                );
                return;
            }
            if (typeof this.afterRead === 'function') {
                this.afterRead(file, this.getDetail());
            }
            this.$emit(
                'after-read',
                Object.assign(
                    {
                        file
                    },
                    this.getDetail()
                )
            );
        },
        deleteItem(event) {
            const { index } = event.currentTarget.dataset;
            this.$emit(
                'delete',
                Object.assign(Object.assign({}, this.getDetail(index)), {
                    file: this.fileList[index]
                })
            );
        },
        onPreviewImage(event) {
            if (!this.previewFullImage) {
                return;
            }
            const { index } = event.currentTarget.dataset;
            const { lists } = this;
            const item = lists[index];
            uni.previewImage({
                urls: lists.filter((item) => item.isImage).map((item) => item.url || item.path),
                current: item.url || item.path,
                fail() {
                    uni.showToast({
                        title: '预览图片失败',
                        icon: 'none'
                    });
                }
            });
        },
        onClickPreview(event) {
            const { index } = event.currentTarget.dataset;
            const item = this.lists[index];
            this.$emit('click-preview', Object.assign(Object.assign({}, item), this.getDetail(index)));
        }
    }
};
</script>
<style>
@import './index.css';
</style>
