<template>
	<view class="c-user" :class="{'c-row':props.row}" @click="emit('click',item)">
		<slot :user="item">
		<view v-if="props.avatar">
			<u-avatar :src="$w.url(item.avatar)" size="calc(3 * var(--rem))"></u-avatar>
		</view>
		<view v-if="props.name" class="w-lines" style="padding: calc(.2 * var(--rem)); flex-grow: 2; ">{{item.nickName}}</view>
		</slot>
		<view v-if="props.closeable" class="close" @click.stop.prevent="emit('close',item)" hover-class="w-hover">&times;</view>
	</view>
</template>

<script setup>
import { onLoad,onShow,onReady } from '@dcloudio/uni-app'
import { ref,watch,computed,onMounted } from 'vue'
import { useCacheStore } from '@/store'
import { searchUser } from '@/api/system/user'

const cacheStore = useCacheStore();

const key = "user";

const props = defineProps({
  id: {
    type: [String,Number],
    default: ""
  },
  closeable:{
	  type:Boolean,
	  default:false
  },
  row:{
	  type:Boolean,
	  default:false
  },
  name:{
	  type:Boolean,
	  default:true
  },
  avatar:{
	  type:Boolean,
	  default:true
  }
});

const emit = defineEmits(['close','click']);

const id = computed(() => props.id);

const cache = useCacheStore().cache;
if (!cache[key]) {
  cache[key] = {};
}

const item = computed(()=>{
	if(!cache[key][id.value]){
		return {};
	}
	return cache[key][id.value];
});



const loadData = async () => {
  if (!id.value) {
    return;
  }
  if (cache[key][id.value]) {
    return;
  }
  cache[key][id.value] = { loading: true };
  try {
    let r = await searchUser(id.value);
	// console.debug(r);
    cache[key][id.value] = r;
  } catch (e) {
    console.error(e);
    cache[key][id.value] = { error: true }
  }
}

const reload = async () => {
  delete cache[key][id.value];
  loadData();
}
onReady(()=>{
	console.debug("正在加载用户:",id.value);
	loadData();
});
watch(()=>id.value, ()=>{
	console.debug("监听加载用户:",id.value);
	loadData();
});
// #ifdef H5
onMounted(loadData);
// #endif

defineExpose({ reload });
</script>

<style lang="scss" scoped>
.c-user{
	position: relative;
	padding: var(--padding,0 .5em);
	display: flex;
	flex-direction: column;
	--rem: 1em;

	&.c-row {
		flex-direction: row;
		&>view {
			justify-content: flex-start;
		}
	}
	
	
	&>view {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size:  calc(.75 * var(--rem));
	}
	
	&>.close {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: calc(.5 * var(--rem));
		overflow: hidden;
		color:var(--w-bg-light);
		position: absolute;
		top: calc(-.5 * var(--rem));
		right: calc(-.2 * var(--rem));
		box-sizing: content-box;
		width: calc(2 * var(--rem));
		height: calc(2 * var(--rem));
		padding: 0;
		line-height: 1;
		border-radius: var(--rem);
		background-color: var(--w-bg-dark-1);
		
		&.w-hover {
			background-color: var(--w-bg-dark-2);
		}
	}
}
</style>
