<template> 
<view v-if="!defaultValue">
	<uni-icons type="ant-design:file-text-outlined" size="58" color="#555" class="icon"
		custom-prefix="antfont" ></uni-icons>
</view>
	<view class="uni-file-picker__lists-box" v-else>
		<view class="uni-file-picker__item"  v-for="(item ,index) in fileList" :key="index"  > 
			<view class="files__name"   @tap="prviewImage(item,index)">
				<image src="/static/img/defaultFile.png" mode="aspectFit" style="width: 20px;height: 23px;margin-right: 4px;"></image>
				<view class="namebox">{{item.name}}</view>
			</view>
			<view style="right: 3px; position: absolute; top:0;bottom:0;display: flex;align-items: center;">
				
				<uni-icons type="ant-design:eye-outlined" size="18" class="icon" style="margin-right: 6px;"
					custom-prefix="antfont" @tap="prviewImage(item,index)"></uni-icons>
				
				<uni-icons type="ant-design:download-outlined" size="18" class="icon" 
					custom-prefix="antfont" @tap="download(item)"></uni-icons>
			</view>
		</view> 
	</view>  
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue'; 
  import { getFileList } from '@/common/api/system/dictionary/index.js';
 	import config from '@/common/config/index.js';  
	import {base64Encode} from '@/utils/helper/tools.js'
  const props = defineProps({
    defaultValue: String, 
  });

  const fileList = ref('');
 
  watch(
    () => props.defaultValue,
    async (val) => {
      if (val) { 
        let res = await getFileList( props.defaultValue );
        if (res.data && !res.code) { 
        	fileList.value = res.data.map(o => {
        		return {
        			name: o.fileName,
        			id: o.id, 
        			fileType: o.fileType,
        			url: (o.fileUrl.includes('http://') || o.fileUrl.includes('https://')) ?
        				o.fileUrl : (config.baseUrl + o.fileUrl)
        		}
        	}) 
        }
      }
      if (!val) {
        fileList.value = '';
      }
    },
    {
      immediate: true,
    },
  );
 function isImgTypeFromFileName(type) {
   let imgType = [".bmp", ".jpg", ".jpeg", ".png", ".gif", ".svg", ".ico"];
   return imgType.includes(type);
 } 
 function download(item) { 
				// let system = uni.getSystemInfoSync().platform;  
				let newUrl = ''; 
				if(!item.url.includes(`https://`) && !item.url.includes(`http://`)) {
					newUrl =  config.baseURL + item.url
				}else{
					newUrl = item.url
				}
				// #ifdef H5
				let tempLink=document.createElement('a');
				tempLink.style.display='none';
				tempLink.href=newUrl;
				tempLink.setAttribute('download',item.name);
				tempLink.setAttribute('target','_blank');
				document.body.appendChild(tempLink);
				tempLink.click();
				document.body.removeChild(tempLink)
				// #endif
				
				// #ifndef H5 
				uni.downloadFile({
					url:newUrl,
					success:function(res){
						let path=res.tempFilePath 
						uni.openDocument({
							filePath: path,//encodeURI(path),
							showMenu: true,
							success: function(res) {},
							fail: (res) => {
								uni.showToast({
									title: '该文件类型不支持下载',
									icon: 'none',
									duration: 2000
								})
							}
						});  
					}
				})
				// #endif
			}
		
function prviewImage(item, index) {
 	if( isImgTypeFromFileName(item.fileType)){
 		let urls = []
 		fileList.value.forEach(i => {
 			urls.push(i.url)
 		})
 
 		uni.previewImage({
 			urls: urls,
 			current: index
 		});
 	}else{ 
 		let newUrl = '';
 		if(!item.url.includes(`https://`) && !item.url.includes(`http://`)) {
 			newUrl =  config.baseUrl + item.url
 		}else{
 			newUrl = item.url
 		} 
 		const fileType=['.doc', '.xls', '.ppt', '.docx', '.xlsx', '.pptx']
 		// #ifdef MP
 		//在线地址
 		if (item.url.includes(`https://`)||item.url.includes(`http://`) ) {
 			if(fileType.includes(item.fileType)){
 				 download(item)
 			}else{
 				uni.navigateTo({
 					url: "/pages/my/filePreview?link=" +  newUrl 
 				})
 			}
 		} else {
 			//本地缓存--打开可以显示文件名字非乱码
 			let fs = uni.getFileSystemManager();
 			//console.log('wxfile://${item.fileName}====',item.url,`wxfile://${item.fileName}`) 
 			try {
 				let result = fs.saveFileSync(
 						item.url,
 						`${wx.env.USER_DATA_PATH}/${item.fileName}`
 				);
 				//console.log('result',result)
 				uni.openDocument({
 						filePath: `${wx.env.USER_DATA_PATH}/${item.fileName}`,
 						showMenu: false, //右上角是否有可以转发分享的功能
 						success: function(res) {
 								console.log('打开文档成功');
 						},
 				})
 			}
 			catch (err) {
 				//console.log('saveFileSync fail', err);
 			} 
 		}
 		// #endif
 		
 		// #ifndef MP
 		newUrl = config.previewUrl + base64Encode(newUrl)
 		uni.navigateTo({
 			url: "/pages/my/filePreview?link=" +  newUrl 
 		})
 		// #endif
 		//encodeURIComponent(Base64.encode(newUrl));  
 	}
 }
</script>
<style lang="less" scoped>
	.uni-file-picker__item{
		position: relative;
	}
  .files__name{
		display: flex;
		align-items: center;
	}
	.namebox{
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: calc(100% - 80px);
	}
</style>
