<template>
    <view class="certification-card">
        <view class="serve-box flex_c_s hr-solid">
            <view v-if="viewStatus">请上传{{ data.businessName }}资质证件</view>
            <view v-else>{{ data.businessName }}资质证件</view>
            <view v-if="viewStatus">{{ fileCount }}/3</view>
        </view>
        <view class="serve-img-contnt">
            <view class="serve-img" v-for="item in files" :key="item">
                <view class="img-close" @click="deleteImg(item)" v-if="viewStatus"></view>
                <view class="serve-is-img flex_c_c">
                    <image-viewer :src="item" :width="148" :height="200" :preview="true"></image-viewer>
                </view>

            </view>
            <view class="serve-up-img flex_c_c" @click="upImg" v-if="fileCount < 3 && viewStatus">
                <up-icon name="plus" color="#C9CDD4" size="16"></up-icon>
            </view>
        </view>
    </view>

</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { wxUploadFile } from '@/utils/wxRequest.js';

import ImageViewer from './image-viewer.vue'

const props = defineProps({
    data: Object,
    viewStatus: {
        type: Boolean,
        default: true
    },
})
const fileList = ref([]);
const maxImgCount = 3;

const { data } = props;
console.log("TCL: data", data)

const fileCount = computed(() => {
    return data.files ? data.files.length : 0;
});

const files = computed(() => {
    console.log(' data.files || []', data.files || []);
    return data.files || [];
});

const deleteImg = (url) => { 
    fileList.value = fileList.value.filter(item => item.url !== url);
    uni.$u.debounce(changeFile, 300)
};
const upImg = async () => {
    try {
        const res = await wxUploadFile('img', maxImgCount);
        fileCount.value < 3 ? fileList.value = [...fileList.value, ...res] : uni.showToast({
            title: `最多可上传${maxImgCount}个资质证件!`,
            icon: 'none',
        });
    } catch (error) {
        console.log("TCL: upImg -> error", error)
    } finally {
        uni.$u.debounce(changeFile, 300)
    }
}

// 存储上传的文件
const changeFile = () => {
    data.files = fileList.value.map(item => item.url);
}

</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>