<template>
    <!-- 最近上传 -->
    <view class="photo-class">
        <view class="title">
            <view @tap="onHandleLastUpload">最近上传</view>
            <view @tap="onHandleMyCollect">我的收藏</view>
        </view>
        <view>
            <up-grid :border="false" col="2">
                <up-grid-item v-for="(icon, index) in props?.imgList" :key="index">
                    <!-- <up-image width="40" height="40" :src="icon.iconUrl" />
                    <text class="grid-text">{{ icon.title }}</text>
                    <text class="count">5100张</text> -->

                    <view class="grid-item-box">
                        <up-image
                            width="100%"
                            height="120"
                            :src="icon.imgUrl"
                            mode="aspectFit"
                            @tap="onHandleImage(icon)"
                        >
                            <template #error>
                                <!-- <view style="font-size: 24rpx; height: 120px">加载失败</view> -->
                            </template>
                        </up-image>
                        <view class="collect">
                            <view>{{ icon.uploadTime }}</view>
                            <view @tap="onHandleCollect(icon)">
                                <up-icon
                                    size="18"
                                    :color="icon.collectStatus == 1 ? '#f56c6c' : '#999'"
                                    :name="icon.collectStatus == 1 ? 'heart-fill' : 'heart'"
                                />
                            </view>
                        </view>

                        <view class="photo-type" :style="setBackgroundColor(icon.uploadType)">
                            {{ imgType[icon.uploadType] }}
                        </view>
                    </view>
                </up-grid-item>
            </up-grid>
        </view>
    </view>

    <!-- 展示图片 -->
    <up-popup :show="showImg" mode="center" @close="showImg = !showImg" bgColor="transparent">
        <view class="img-show-box">
            <up-image width="100%" height="100%" :src="showImgUrl" mode="scaleToFill" style="" />
            <view class="upload-btn">
                <view @tap="onHandleYtUpload"> 原图下载 </view>
                <view @tap="onHandleSyUpload"> 水印下载 </view>
            </view>
        </view>
    </up-popup>

    <!-- 退出提示弹框 -->
    <up-modal
        title="温馨提示"
        :show="showModalCollect"
        :showCancelButton="true"
        @cancel="onCancelCollect"
        @confirm="onConfirmCollect"
        :content="collectContent"
    />
</template>

<script setup>
import { computed, ref, reactive } from 'vue'
import { useMemberStore } from '@/stores'
import { editCollectTypeApi, getGenerateWatermarkImgApi } from '@/services/comprehensiveQuery.js'

const memberStore = useMemberStore()
const token = memberStore?.token
const baseURL = import.meta.env.VITE_API_BASE_URL // 获取当前的url地址

const showModalCollect = ref(false)
const collectContent = ref('')

// 水印图查询参数
const watermarkQueryParams = reactive({
    uploadTime: '',
    proName: '',
    uploadTypeName: '',
    sourceType: '',
    sourceTypeName: '',
})

const collectEditParams = ref({
    id: '',
    collectType: '',
})
const props = defineProps({
    imgList: {
        type: Array,
        default: () => [],
    },
})

const imgType = reactive({
    1: '安全违章',
    2: '质量检查',
    3: '安全措施',
    4: '协调照片',
    5: '重要事项',
})

const emits = defineEmits(['handleMyCollect', 'handleLastUpload', 'handleGetImgList'])

const showImg = ref(false)
const showImgUrl = ref('')

// 收藏与取消收藏
const onHandleCollect = (icon) => {
    if (icon.collectStatus == 0) {
        collectContent.value = '是否确认把该图片加入我的收藏？'
        collectEditParams.value.collectType = 1
    } else {
        collectContent.value = '是否确认取消收藏？'
        collectEditParams.value.collectType = 2
    }
    collectEditParams.value.id = icon.id
    showModalCollect.value = true
}

// 取消按钮
const onCancelCollect = () => {
    showModalCollect.value = false
}
// 确定按钮
const onConfirmCollect = async () => {
    const res = await editCollectTypeApi(collectEditParams.value)
    if (res.code === 200) {
        uni.$u.toast('操作成功')
        emits('handleGetImgList')
        showModalCollect.value = false
    } else {
        uni.$u.toast(res.msg)
    }
}

// 点击图片
const onHandleImage = (icon) => {
    const {
        uploadTime,
        proName,
        uploadTypeName,
        sourceType,
        sourceTypeName,
        id,
        originalFilePath,
    } = icon

    Object.assign(watermarkQueryParams, {
        uploadTime,
        proName,
        uploadTypeName,
        sourceType,
        sourceTypeName,
        id,
        originalFilePath,
    })
    showImgUrl.value = icon.imgUrl
    showImg.value = true
}

// 定义样式
const setBackgroundColor = (type) => {
    if (type == 1) return { backgroundColor: '#f56c6c' }
    if (type == 2) return { backgroundColor: '#19be6b' }
    if (type == 3) return { backgroundColor: '#ff9900' }
    if (type == 4) return { backgroundColor: '#f56ccf' }
    if (type == 5) return { backgroundColor: '#00bfbf' }
}

// 原图下载
const onHandleYtUpload = () => {
    downloadImage(showImgUrl.value)
}

const downloadImage = async (imageUrl) => {
    try {
        // 显示加载中
        uni.showLoading({
            title: '下载中...',
        })

        // 第一步：下载文件到本地
        const { tempFilePath } = await uni.downloadFile({
            url: imageUrl,
        })

        // 第二步：保存到相册
        await uni.saveImageToPhotosAlbum({
            filePath: tempFilePath,
        })

        uni.hideLoading()
        uni.showToast({
            title: '保存成功',
            icon: 'none',
        })

        showImg.value = false
    } catch (error) {
        uni.hideLoading()
        uni.showToast({
            title: '保存失败',
            icon: 'none',
        })
        showImg.value = false
        // console.error('下载失败:', error)
    }
}
// 水印下载
const onHandleSyUpload = async () => {
    const res = await getGenerateWatermarkImgApi(watermarkQueryParams)
    if (res.code === 200) {
        downloadImage(`${baseURL}/imgTool/files${res.data}?token=${token}`)
    } else {
        uni.showToast({
            title: '水印图片获取失败',
            icon: 'none',
        })
    }

    // showImg.value = false
}

// 点击我的收藏
const onHandleMyCollect = () => {
    emits('handleMyCollect')
}
// 点击最近上传
const onHandleLastUpload = () => {
    emits('handleLastUpload')
}
</script>

<style lang="scss" scoped>
.photo-class {
    width: 100%;
    margin-top: 24rpx;
    & .title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 36rpx 0;

        & view:first-child {
            font-size: 17px;
            font-weight: bold;
        }

        & view:last-child {
            margin-right: 16rpx;
            color: #4a6fff;
            font-size: 14px;
            letter-spacing: 1rpx;
        }
    }

    .grid-item-box {
        position: relative;
        width: 95%;
        // height: 100rpx;
        margin-bottom: 10rpx;
        display: flex;
        flex-direction: column;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        border-bottom-right-radius: 16rpx;
        border-bottom-left-radius: 16rpx;

        .photo-type {
            position: absolute;
            padding: 0 10rpx;
            right: 20rpx;
            top: 10rpx;
            height: 48rpx;
            line-height: 48rpx;
            font-size: 12px;
            border-radius: 24rpx;
            color: #fff;
        }
    }

    .collect {
        padding: 16rpx 18rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
    }
}

.img-show-box {
    width: 100vw;
    height: 50vh;
    position: relative;

    .upload-btn {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        display: flex;
        align-items: center;

        & view {
            padding: 30rpx 0;
            width: 50%;
            color: #fff;
            text-align: center;
            letter-spacing: 2px;
            background-color: rgba(0, 0, 0, 0.3);
        }
        & view:first-child {
            margin-right: 1px;
        }
    }
}

::v-deep .grid-item-box .u-fade-enter-active,
.u-fade-leave-active {
    height: 120px;
}
</style>
