<template>
    <view class="doc-upload-wrapper">
        <view class="upload-box">
            <view class="bg-grey upload-box-child">
                <s-icon name="camera-fill" @click="chooseFile" size="30"></s-icon>
            </view>
        </view>
        <view class="preview" v-for="(item, index) in fileList" :key="index">
            <img @click="previewImgList(item.url)" :src="item.url" alt="">

            <view class="delete" v-if="showRemoveIcon">
                <s-icon name="close" @click="handleRemove(item)" color="#fff" size="14"></s-icon>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
        }
    },
    props: {
        // 传入的数据
        models: {
            type: Object,
            default: () => { }
        },
        // 当前选项对应的json数据
        record: {
            type: Object,
            default: () => { }
        },
        // 是否禁用输入
        disabled: {
            type: Boolean,
            default: false
        },
        // 图片上传成功后生成预览图片地址的处理函数
        uploadImgPreviewHandler: {
            type: Function,
            default: () => { }
        },
        // 图片上传成功后将会把接口返回的数据添加到models，这里进行中间处理
        uploadSuccessHandler: {
            type: Function,
            default: null
        },
        // 是否显示可移除上传文件图标
        showRemoveIcon: {
            type: Boolean,
            default: true
        },
        // 部分应用内发起的请求有需要区分baseUrl
        baseUrl: {
            type: String,
            default: ""
        },
        headers: {
            type: Object,
            default: () => { }
        },
        // 是否显示可移除图标
		suffixPath: {
			type: String,
			default: ""
		}
    },
    methods: {
        handleRemove(file) {
            const imageList = JSON.parse(this.models[this.record.model])
            const index = imageList.findIndex(k => k[this.record.options.id] === file.id)
            imageList.splice(index, 1)

            this.$emit("change", this.record.model, JSON.stringify(imageList));
        },
        previewImgList(url) {
            uni.previewImage({
                urls: [url],
                current: url
            });
        },
        chooseFile() {
            let self = this
            uni.chooseImage({
                success: async (chooseImageRes) => {
                    uni.showLoading({
                        title: "上传中"
                    })
                    const tempFilePaths = chooseImageRes.tempFilePaths;
                    const url = tempFilePaths[0]

                    const result = await self.uploadFilePromise(url)

                    let imageList = []

                    if (this.models[this.record.model] && Array.isArray(JSON.parse(this.models[this.record.model]))) {
                        imageList = JSON.parse(this.models[this.record.model])
                    }

                    imageList.push(result)

                    this.$emit("change", this.record.model, JSON.stringify(imageList));

                    uni.hideLoading()

                }
            });
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let uploadUrl = this.baseUrl ? `${this.baseUrl}${this.record.options.mobileAction}` : `${this.record.options.mobileAction}`

                let a = uni.uploadFile({
                    url: uploadUrl,
                    filePath: url,
                    header: this.headers,
                    name: 'file',
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        setTimeout(async () => {
                            if (this.uploadSuccessHandler) {
                                console.log("执行添加前的处理函数");
                                let result = null
                                if(this.record.options.resultField){
                                    result = await  this.uploadSuccessHandler(data[this.record.options.resultField])
                                    resolve(result)
                                }else{
                                    result = await  this.uploadSuccessHandler(data)
                                    resolve(result)
                                }
                            } else {
                                console.log("正常添加");
                                resolve(this.record.options.resultField ? data[this.record.options.resultField] : data)
                            }
                        }, 1000)
                    }
                });
            })
        },
        // 删除图片
        deletePic(event) {
            this.fileList.splice(event.index, 1)
        },
    },
    computed: {
        // 获取当前上传文件列表
        fileList() {
            if (this.record.model && this.models[this.record.model]) {

                const list = JSON.parse(this.models[this.record.model])

                if (list && list.length) {
                    return list.map(k => {
                        return {
                            name: k[this.record.options.fileName],
                            url: this.baseUrl + k.imageUrl + this.suffixPath,
                            id: k[this.record.options.id]
                        }
                    })
                }
            } else {
                return []
            }
        },
        // 预览图片处理函数
        previewImgUrl() {
            return (file) => {
                if (file && this.uploadImgPreviewHandler) {
                    return this.uploadImgPreviewHandler(file)
                } else {
                    return ""
                }
            }
        }
    },
    mounted() {

    }
}
</script>

<style lang="scss" scoped>
.doc-upload-wrapper {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .upload-box {
        width: 33%;
        padding: 15rpx;
        height: 160rpx;

        &-child {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10rpx;
        }
    }

    .bg-grey {
        background-color: #f4f5f7;
    }

    .delete {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 40rpx;
        height: 40rpx;
        position: absolute;
        top: 0;
        right: 0;
        border-radius: 50%;
        background-color: rgb(207, 19, 34);
    }

    .preview {
        position: relative;
        padding: 15rpx;
        width: 33%;
        height: 160rpx;
        border-radius: 10rpx;



        img {
            border-radius: 10rpx;
            width: 100%;
            height: 100%;
        }
    }
}
</style>