<template>
	<view>
		<view class="w-process-item" v-for="(prc, i) in _value" :key="prc.id" @click="showInstance(prc)">
			<avatar :size="30" :src="prc.startUser.avatar" :name="prc.startUser.name" />
			<text class="over-tip" style="font-size: 29rpx">{{prc.createTime.substring(0, 16)}} 提交的 -
				{{prc.name}}</text>
			<view @click.stop="remove(i)">
				<uni-icons v-if="!readonly" type="closeempty" size="20"></uni-icons>
			</view>
		</view>
		<view class="w-prcindex-add" v-if="!readonly" @click="selectProcess">+ {{formProps.placeholder || '添加关联流程'}}</view>
	</view>
</template>

<script setup>
	import { computed, nextTick, watch } from 'vue'
	import Avatar from '@/components/Avatar.vue'
	import { onUnload } from "@dcloudio/uni-app";

	const props = defineProps({
		formProps: {
			type: Object,
			default: () => {
				return {}
			}
		},
		modelValue: {
			type: Array,
			default: () => {
				return []
			}
		},
		readonly: Boolean
	})

	const _value = computed({
		get() {
			return props.modelValue
		},
		set(val) {
			emits('update:modelValue', val)
		}
	})

	const emits = defineEmits(['update:modelValue'])

	function showInstance(prc) {
		uni.navigateTo({
			url: `/pages/instance/instancePreview?instanceId=${prc.id}`
		})
	}

	function selectProcess() {
		uni.navigateTo({
			url: '/components/form/sub/ProcessSelect'
		})
	}

	uni.$on('selectProcess', (val) => {
		if (_value.value.findIndex(v => v.id === val.id) >= 0) {
			uni.showToast({
				icon: 'none',
				title: '不要重复添加哦'
			})
		} else {
			nextTick(() => _value.value = [..._value.value, val])
		}
	})

	function remove(i) {
		_value.value.splice(i, 1)
	}

	onUnload(() => uni.$off('selectProcess'))

	watch(_value, (newValue) => {
		emits('update:modelValue', newValue)
	})
</script>

<style lang="less" scoped>
	.w-prcindex-add {
		color: #5976EF;
		padding: 6rpx;
		//font-size: 32rpx;
		text-align: center;
	}

	.w-process-item {
		flex: 1;
		padding: 5px;
		margin-bottom: 3px;
		display: flex;
		align-items: center;
		border-radius: 5px;
		background-color: #F4F5F7;

		.over-tip {
			flex: 1;
			font-size: 27rpx
		}
	}
</style>