<template>
    <!-- 图片 -->
    <cell-box>
        <div class="label">
            <slot></slot>
        </div>
        <ul>
            <li v-for="(item, index) in formItem.value" :key="item">
                <img :src="getFileUrl(item)" @click="$refs.previewer.show(index)">
                <x-icon
                    class="del"
                    type="ios-close"
                    icon="el-icon-error"
                    @click="del(item, index)"
                ></x-icon>
            </li>
            <li v-if="formItem.value.length < listItem.verify.limit[1]">
                <div class="add" @click="upload">
                    <x-icon type="ios-plus-empty" size="50"></x-icon>
                </div>
            </li>
            <li v-for="n in 10" :key="n"></li>
        </ul>
        <div v-transfer-dom>
            <previewer :list="previewerList" ref="previewer"></previewer>
        </div>
    </cell-box>
</template>

<script>
import { CellBox, Previewer, TransferDom } from 'vux'
import common from '@/common/formRender/mixin/common.js'
import { getFileUrl, getObjectKey } from '@/assets/utils/host.js'
import { chooseImage } from '@/assets/utils/wxTool.js'
import { ossUpload, ossDelete } from '@/assets/utils/ossTool.js'
import ossPaths from '@/assets/ossPaths.js'
export default {
    name: 'FormImg',
    directives: { TransferDom },
    components: { CellBox, Previewer },
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) }
    },
    mixins: [common],
    data () {
        return {
            getFileUrl,
            list: [] // 判断数量的文件列表
        }
    },
    computed: {
        previewerList: vm => vm.formItem.value.map(item => ({ src: getFileUrl(item) }))
    },
    created () {
        this.verifyInit()
    },
    mounted () {
        const [min, max] = this.listItem.verify.limit
        this.$el.querySelector('.item-title').innerHTML += `<span class="verify">${min} ~ ${max} 张图片</span>`
    },
    methods: {
        // 上传图片
        upload () {
            const { limit, onlyCamera } = this.listItem.verify
            const params = { count: limit[1] - this.list.length }
            if (onlyCamera) params.sourceType = ['camera']
            chooseImage(params).then(({ fileList, sourceType }) => {
                this.list.push(...fileList)
                ossUpload({
                    path: ossPaths.form,
                    file: fileList,
                    watermark: sourceType === 'camera'
                }).then(res => {
                    const list = res.map(item => JSON.stringify(item))
                    this.formItem.value.push(...list)
                    this.verify().catch(() => {})
                })
            })
        },
        // 删除图片
        del (item, index) {
            ossDelete({
                path: ossPaths.form,
                key: getObjectKey(item)
            }).then(() => {
                this.list.splice(index, 1)
                this.formItem.value.splice(index, 1)
                this.verify().catch(() => {})
            })
        },
        // 校验初始化
        verifyInit () {
            const rules = []
            const { required } = this.listItem.verify
            if (required) rules.push(this.required(this.listItem.title))
            rules.push(this.img(this.listItem))
            this.validator = new this.Schema({ value: rules })
        },
        // 图片校验（例如至少需要上传 2 张又不需要必填，则可以不上传，如果上传了则需要是 2 张以上）
        img (item) {
            return {
                validator: (rule, value, callback) => {
                    value.length && value.length < item.verify.limit[0]
                        ? callback(new Error(`至少上传 ${item.verify.limit[0]} 张图片`))
                        : value.length > item.verify.limit[1]
                            ? callback(new Error(`最多上传 ${item.verify.limit[1]} 张图片`))
                            : callback()
                }
            }
        },
        // 校验
        verify () {
            return new Promise((resolve, reject) => {
                if (this.formItem.value.length === this.list.length) {
                    resolve(this.validate({ value: this.formItem.value }))
                } else {
                    this.toast('请等待上传完成')
                    reject(new Error('请等待上传完成'))
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
.vux-cell-box {
    display: block;
}
ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 0 -10px -5px;
    li {
        padding: 5px 10px;
        position: relative;
        &:empty {
            padding: 0;
            width: 100px;
        }
        img, .add {
            width: 80px;
            height: 80px;
            border-radius: 6px;
            border: 1px solid #DCDFE6;
        }
        img {
            object-fit: cover;
            vertical-align: top;
        }
        .add {
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #fff;
        }
        .del {
            fill: #F56C6C;
            font-size: 24px;
            background-color: #fff;
            border-radius: 50%;
            position: absolute;
            top: 0px;
            right: 0px;
        }
    }
}
@media screen and (min-width: 360px) {
    ul li {
        &:empty { width: 105px; }
        img, .add { width: 85px; height: 85px; }
    }
}
@media screen and (min-width: 380px) {
    ul li {
        &:empty { width: 110px; }
        img, .add { width: 90px; height: 90px; }
    }
}
</style>
