<template>
	<view class="pig" :class="'pig--' + columns">
		<!-- 单图 -->
		<view
			v-if="columns === 1"
			class="pig-single"
			@tap.stop="onTap(0)"
		>
			<image class="pig-single-img" :src="cellSrc(visible[0], 750)" mode="aspectFill" />
		</view>

		<!-- 多图网格 -->
		<view v-else class="pig-grid">
			<view
				v-for="(img, idx) in visible"
				:key="idx"
				class="pig-cell"
				:class="'pig-cell--' + columns"
				@tap.stop="onTap(idx)"
			>
				<image class="pig-cell-img" :src="cellSrc(img, 360)" mode="aspectFill" />
				<view v-if="idx === visible.length - 1 && overflow > 0" class="pig-overflow">
					<text class="pig-overflow-text">+{{ overflow }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { gridColumnCount, gridDisplayImages } from '@/features/dynamics/post-media'

export default {
	name: 'PostImageGrid',
	props: {
		images: { type: Array, default: () => [] },
		max: { type: Number, default: 9 }
	},
	computed: {
		pack() {
			return gridDisplayImages(this.images, this.max)
		},
		visible() {
			return this.pack.visible
		},
		overflow() {
			return this.pack.overflow
		},
		count() {
			return this.visible.length
		},
		columns() {
			return gridColumnCount(this.count)
		}
	},
	methods: {
		oss(url, w = 400, h = 0) {
			if (this.$appKit && typeof this.$appKit.oss === 'function') {
				return this.$appKit.oss(url, w, h)
			}
			return url || ''
		},
		cellSrc(url, w) {
			return this.oss(url, w, w)
		},
		onTap(index) {
			this.$emit('tap-image', index)
		}
	}
}
</script>

<style scoped>
.pig {
	width: 100%;
}
.pig-single {
	width: 100%;
	height: 420rpx;
	border-radius: 20rpx;
	overflow: hidden;
	background-color: #eef2f8;
}
.pig-single-img {
	width: 100%;
	height: 100%;
}
.pig-grid {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	width: 100%;
	justify-content: flex-start;
}
.pig-cell {
	position: relative;
	border-radius: 12rpx;
	overflow: hidden;
	background-color: #eef2f8;
	margin-bottom: 8rpx;
}
.pig-cell--2 {
	width: 49%;
	height: 280rpx;
}
.pig-cell--2:nth-child(2n) {
	margin-left: 2%;
}
.pig-cell--3 {
	width: 32%;
	height: 210rpx;
	margin-right: 2%;
}
.pig-cell--3:nth-child(3n) {
	margin-right: 0;
}
.pig-cell-img {
	width: 100%;
	height: 100%;
}
.pig-overflow {
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: center;
	justify-content: center;
}
.pig-overflow-text {
	color: #ffffff;
	font-size: 40rpx;
	font-weight: 700;
}
</style>
