<template>
  <uni-easyinput :placeholder="placeholder" :disabled="disabled" :prefixIcon="prefixIcon" :suffixIcon="suffixIcon" :addonBefore="addonBefore" :addonAfter="addonAfter" 
 readonly  v-if="!usersInfo.length"/>
  <div class="flex" v-else>
    <div
      v-for="item in usersInfo"
      :key="item.id"
      :class="['user-box', disabled ? 'pointer-events-none' : '']"
      :disabled="disabled"
      @click="open(item)"
    >
      <img :src="item.imgUrl" v-if="item.imgUrl" style="width: 100%;height:100%"/>
      <div style="text-align: center;" v-else>
        <div>{{ item.name }}</div>
        <div style="margin-top: 7px;">点击签名</div>
      </div>
    </div>
  </div>
  <sign ref="signRef" :isCallSign="isCallSign"  @confirm="confirm" />
</template>

<script setup>
  import { ref, watch, inject, onMounted, computed, nextTick } from 'vue';
	import sign from "./sign.vue";
  import { getUserMulti, uploadApi,getRoleMulti} from '@/common/api/signature/index';
    	import config from '@/common/config/index.js' 
			import { USER_INFO_KEY } from "@/common/const/cache.js";
  const props = defineProps({
    disabled:{
      type: Boolean,
      default: false,
    },
    isCallSign: {
      type: Boolean,
      default: false,
    },
    prefixIcon: {
      type: String,
      default: "",
    },
    suffixIcon: {
      type: String,
      default: "",
    },
    addonBefore: {
    	type: String,
    	default: "",
    },
    addonAfter: {
    	type: String,
    	default: "",
    },
    modelValue: {
      type: String,
      default: ''
    },
    defaultValue: {
      type: String,
      default: '',
    },
    associateComponents: {
      type: Array,
      default: [],
    },
		signValueType: {
      type: Number,
      default: ''
    }
  });

  const emits = defineEmits(['update:modelValue']);
  
  const formModel = inject('formModel', null);
  const formProps = inject('formProps', null);

  const usersInfo = ref([]);
  const assoArr = ref([]);
  const value = ref('');
  const currentUser = ref();
  const assoComponents = ref([]);
  const signRef = ref();

  watch(
    () => formModel.value,
    async (val) => { 
			if (!props.isCallSign) {
				if (props.associateComponents?.length) {  
					assoComponents.value?.map((item) => { 
						if (val[item.field]!==undefined) {
							getAssoComponentInfo();
						}
					});
				} 
			}
    },
    {
      deep: true,
      immediate: true
    },
  );

  const placeholder = computed(() => {
    if (assoComponents.value?.length) {
      let str = '请先选择';
      assoComponents.value?.forEach((item, idx) => {
        if (idx + 1 === assoComponents.value.length) {
          str = str.concat(`"${item.label}"后再进行签名！`);
        } else {
          str = str.concat(`"${item.label}"、`);
        }
      });
      return str;
    }
    return '请选择签字人';
  });

  onMounted(async () => {
  //   const userIds = props.defaultValue.split(',');
  //   let res =null;
		// if(props.signValueType===1){
		// 	res=await getUserMulti([...new Set(userIds)].toString());
		// }else if(props.signValueType===0){
		// 	res=await getRoleMulti( props.defaultValue ); 
		// }
  //   if(res) usersInfo.value = res.data||[]
	
	  if (!props.isCallSign) { 
			if (props.associateComponents?.length) { 
				getSignAssoComponents(formProps?.value.schemas);
				assoArr.value = assoComponents.value?.map((item) => {
					return { type: item.component, field: item.field };
				});
			}
			getAssoComponentInfo();
		}
  });
  
  function open(item) {
		let userInfo = uni.getStorageSync(USER_INFO_KEY);
		let hasId = [userInfo.id];
		userInfo.roles.forEach((o) => {
			hasId.push(o.id);
		});
		if (hasId.includes(item.id)) {
			currentUser.value = item;
			signRef.value.open();
		} else {
			uni.showToast({
				title:'你不是' + item.name + '，不能签名！',
				duration:2000,
				icon:'none'
			}) 
		} 
  }

  async function getAssoComponentInfo() {
		usersInfo.value = [];
		let assoUsers= [];
		let assoRoles= [];
		
		assoArr.value.forEach((item) => {
			if (formModel.value[item.field]) {
				if (item.type == 'Role') {
					assoRoles.push(...formModel.value[item.field]?.split(','));
				} else {
					assoUsers.push(...formModel.value[item.field]?.split(','));
				}
			}
		});
		
		const defaultValue = props.defaultValue ? props.defaultValue?.split(',') : '';
		let userIds = [...assoUsers],
			roleIds = [...assoRoles];
		if (props.signValueType === 1) {
			userIds = [...new Set([...assoUsers, ...defaultValue])];
		}
		if (props.signValueType === 0) {
			roleIds = [...new Set([...assoRoles, ...defaultValue])];
		}
		
		// if (usersInfo.value.length === userIds.length + roleIds.length) {
		// 	const usersInfoIds = usersInfo.value.map((x) => x.id);
		// 	if ([...userIds, ...roleIds].every((x) => usersInfoIds.includes(x))) return;
		// }
		let infoData=[]
		if (userIds.length > 0){
			let res = await getUserMulti(userIds.toString());
			infoData = res.data||[]
		} 
		if (roleIds.length > 0) {
			let res = await getRoleMulti(roleIds.toString());
			let data=res.data||[] 
			infoData = [...infoData,...data];
		}
		usersInfo.value=infoData;
		if (typeof props.modelValue === 'string' && props.modelValue) {
			const valueObj = JSON.parse(props.modelValue); 
			if (props.modelValue && valueObj && Object.keys(valueObj).length) {
				for (let key in valueObj) {
					usersInfo.value.forEach((item) => {
						if (item.id === key) {
							item.imgUrl = valueObj[key];
						}
					});
				}
			}
		}
		if (usersInfo.value.length) {
			let val = {};
			usersInfo.value.forEach((item) => {
				val[item.id] = item.imgUrl || '';
			});
			emits('update:modelValue', JSON.stringify(val));
		}
		
		
		
		
		
		
 //    let assoUsers = [];
	// 	assoComponents.value=[]
 //    if (props.associateComponents?.length) {
 //      getSignAssoComponents(formProps?.value.schemas);
 //      assoArr.value = assoComponents.value?.map((item) => item.field);
 //    }
 //    assoArr.value.forEach((item) => {
 //      if (formModel.value[item]) {
 //        assoUsers.push(...formModel.value[item]?.split(','));
 //      }
 //    });
 //    const userIds = [...assoUsers];
	// if (props.defaultValue) {
	//   userIds.push(...props.defaultValue.split(','))
	// }
 //    let res =null;
	// 	if(props.signValueType===0){
	// 		res=await getRoleMulti( userIds.join(',') ); 
	// 	} else{
 //    	res=await getUserMulti([...new Set(userIds)].toString());
 //    } 
 //    if(res) usersInfo.value = res.data||[]
 //    if (props.modelValue && typeof props.modelValue === 'string') {
 //      const valueObj = JSON.parse(props.modelValue);
 //      if (props.modelValue && valueObj && Object.keys(valueObj).length) {
 //        for (let key in valueObj) {
 //          usersInfo.value.forEach((item) => {
 //            if (item.id === key) {
 //              item.imgUrl = valueObj[key];
 //            }
 //          });
 //        }
 //      }
 //    }
  };
  
  function getSignAssoComponents(list) {
    list.forEach((item) => {
      if (['Collapse','Segmented','TableLayout'].includes(item.component)) {
        for (const child of item.layout) {
          getSignAssoComponents(child.children);
        }
      } else if (props.associateComponents.includes(item.key)) {
        assoComponents.value.push(item);
      }
    });
  };
  
  async function confirm(signType, info) {
		
    let url = '';
    if (signType === 'write') {
      if (info) { 
				// #ifdef APP-PLUS 
				uni.uploadFile({
					url: config.baseUrl + '/system/oss/upload',  
					filePath: info,
					name: 'file',
					formData: { Authorization: "Bearer " + plus.storage.getItem('TOKEN__') },
					success: (uploadFileRes) => { 
						console.log(uploadFileRes,'urlurlurlurl')
						if (uploadFileRes.data) {
							let data=JSON.parse(uploadFileRes.data)
							if(data.code===10500){
								uni.showToast({
									icon:'none',
									title: data.msg,
									duration:3000
								});
							}else{
								url = JSON.parse(uploadFileRes.data).data.fileUrl;
								
								uni.showToast({
									title: '手写签名上传成功',
								});
								currentUser.value.imgUrl = url;
								const emitValue = {};
								usersInfo.value.forEach((item) => {
									emitValue[item.id] = item.imgUrl || '';
								});
								signRef.value.close();
								emits('update:modelValue', JSON.stringify(emitValue));
							} 
						} else {
							uni.showToast({
								title: '手写签名上传失败',
							});
						}
					}
				});
				return;
				// #endif
				
				// #ifndef APP-PLUS
				let res = await uploadApi(info); 
				if (res.data.fileUrl) {
				  url = res.data.fileUrl;
				  uni.showToast({
				    title: '手写签名上传成功',
				  });
				} else {
				  uni.showToast({
				    title: '手写签名上传失败',
				  });
				}
				// #endif 
      }
    } else {
      url = info;
    }
    currentUser.value.imgUrl = url;
    const emitValue = {};
    usersInfo.value.forEach((item) => {
      emitValue[item.id] = item.imgUrl || '';
    });
    signRef.value.close();
    emits('update:modelValue', JSON.stringify(emitValue));
  }
</script>
<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 110px;
    height: 80px;
    border: 1px dashed #ccc;
    border-radius: 5px;
    margin: 5px 7px 0 0;
    background-color: #f6f8fa;
    cursor: pointer;
    color: #6f7075;
    overflow: scroll;

    &:hover {
      border: 1px dashed #6d9fff;
    }
  }
  
  .flex {
    display: flex;
    flex-wrap: wrap;
  }

  .radio-box {
    display: flex;
    justify-content: center;
    margin-top: 15px;
  }
</style>