'use strict';
const {
	getUserId
} = require('user-common')
exports.main = async (event, context) => {
	const db = uniCloud.database();
	const _ = db.command
	const $ = db.command.aggregate
	const user_id = await getUserId(event.token)
	let res = await db.collection("standardV2").aggregate().lookup({
		from: 'user_upload_file',
		let: {
			standard_id: '$_id'
		},
		pipeline: $.pipeline()
			.match(_.expr($.and([
				$.eq(['$standard_id', '$$standard_id']),
				$.eq(['$user_id', user_id])
			]))).sort({
				create_date: -1
			}).limit(10)
			.project({
				"_id": 0,
				"url": 1,
			})
			.done(),
		as: 'imageList'
	}).match({"classify_id": event.classify_id, "system_id": event.system_id, "brand_id": event.brand_id}).limit(100).end()
	const watermarkC = uniCloud.database().collection("user_watermark").field({'_id': false})
	let userWatermark = await watermarkC.where({
		user_id: user_id,
		system_id: event.system_id
	}).get()
	if (!userWatermark.data || userWatermark.data.length <= 0) { // 用户没有 获取模板
		userWatermark = await watermarkC.where({system_id: event.system_id}).get()
	}
	let userWatermarkData = userWatermark.data[0]
	let data = res.data
	const map = new Map()
	for (let i = 0; i < data.length; i++) {
		data[i].imageList = data[i].imageList.map(a => a.url)
		let key = data[i].type
		if (map.has(key)) {
			data[i].images = data[i].images.split(",")
			map.get(key).list.push(data[i])
		} else {
			data[i].images = data[i].images.split(",")
			map.set(key, {
				type: key,
				userWatermark: userWatermarkData,
				list: [data[i]]
			})
		}
	}
	return [...map.values()]
};
