<template>
	<view>
		<view class="flex bg-white">
			<view class="flex-sub padding" @tap="chooseImage">
				<text class="cuIcon-pic text-grey text-xxl"></text>
				<view class="text-center text-xs">发送图片</view>
			</view>
			<!-- #ifndef APP-PLUS -->
			<!-- <view class="flex-sub padding" @tap="chooseVideo">
				<text class="cuIcon-video text-grey text-xxl"></text>
				<view class="text-center text-xs">发送视频</view>
			</view> -->
			<!-- <view class="flex-sub padding" @tap="chooseFile">
				<text class="cuIcon-file text-grey text-xxl"></text>
				<view class="text-center text-xs">发送文件</view>
			</view> -->
			<!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			<!-- <view class="flex-sub padding" @tap="chooseAppFile">
				<text class="cuIcon-file text-grey text-xxl"></text>
				<view class="text-center text-xs">发送文件</view>
			</view> -->
			<view v-if="chatType===ChatType.FRIEND" v-for="(item) in VimPlugin.chatViewPlugins()"
				class="flex-sub padding" @tap="item.handle(chatId)">
				<text class="text-grey text-xxl" :class="item.icon"></text>
				<view class="text-center text-xs">{{item.title}}</view>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script setup lang="ts">
	import Auth from '@/api/Auth';
	import FetchRequest from '@/api/FetchRequest';
	import MessageType from '@/utils/MessageType';
	import authorizeUtils from '@/store/authorizeUtils';
	//#ifdef APP-PLUS
	import filePicker from "@/uni_modules/file-picker"
	//#endif
	import { getFileType } from "@/utils/FileUtils";
	import MessageUtils from "@/utils/MessageUtils";
	import type Message from "@/mode/Message";
	import { useWsStore } from "@/store/WsStore";
	import { useUserStore } from "@/store/userStore";
	import VimPlugin from "@/plugins/VimPlugin";
	import ChatType from "@/utils/ChatType";
	import VimConfig from "@/config/VimConfig";
	import {
		reactive
	} from 'vue'
	const data = reactive({
		show: false,
	});

	const props = defineProps({
		chatId: {
			type: String,
			required: true,
			default: ''
		},
		chatType: {
			type: String,
			required: true,
			default: ''
		}
	})
	const userId = useUserStore().getUser()?.id

	const chooseFile = () => {
		//#ifdef H5
		uni.chooseFile({
			count: 1,
			extension: ['.zip', '.doc', '.docx', '.pdf', '.xls', '.xlsx'],
			success: function (res) {
				upload(res.tempFilePaths[0], MessageType.file, res.tempFiles[0].name)
			}
		});
		//#endif
		//#ifdef MP
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success(res : any) {
				// tempFilePath可以作为img标签的src属性显示图片
				upload(res.tempFiles[0].path, MessageType.file, res.tempFiles[0].name)
			}
		})
		//#endif
	}
	//#ifdef APP-PLUS
	const chooseAppFile = () => {
		filePicker({
			scope: "/Download",
			permission: false,
			mimetype: "*/*",
			success(res : any) {
				const fileType = getFileType(res.fileName).toLowerCase()
				if (fileType === "mp4") {
					upload(res.filePath, MessageType.video, res.fileName)
				} else if (fileType === "mp3") {
					upload(res.filePath, MessageType.voice, res.fileName)
				} else if (['jpg', 'png', 'gif'].some(item => item === fileType)) {
					upload(res.filePath, MessageType.image, res.fileName)
				} else {
					upload(res.filePath, MessageType.file, res.fileName)
				}
			},
			fail(err : any) {
				console.log(err);
			}
		})
	}
	//#endif
	const chooseVideo = async () => {
		//#ifdef H5
		let userAgent = navigator.userAgent
		if (userAgent.match(/huawei/i)) {
			if(data.show==false){
				uni.showModal({
					title: '相机权限说明',
					content: '用于拍照、录制视频等场景，是否允许此APP拍摄照片和录制视频，请您确认授权，否则无法使用该功能',
					cancelText:"禁止",
					confirmText:"允许",
					success: (res) => {
						data.show = true;
						uni.chooseFile({
							count: 1,
							extension: ['.mp4'],
							success: function (res) {
								upload(res.tempFilePaths[0], MessageType.video, res.tempFiles[0].name)
							}
						});
					},
					fail: () => {
				
					}
				})
			}else{
				uni.chooseFile({
					count: 1,
					extension: ['.mp4'],
					success: function (res) {
						upload(res.tempFilePaths[0], MessageType.video, res.tempFiles[0].name)
					}
				});
			}
		} else {
			uni.chooseFile({
				count: 1,
				extension: ['.mp4'],
				success: function (res) {
					upload(res.tempFilePaths[0], MessageType.video, res.tempFiles[0].name)
				}
			});
		}

		//#endif
		// //#ifdef H5
		// uni.chooseFile({
		// 	count: 1,
		// 	extension: ['.mp4'],
		// 	success: function (res) {
		// 		upload(res.tempFilePaths[0], MessageType.video, res.tempFiles[0].name)
		// 	}
		// });
		// //#endif
		//#ifdef MP
		wx.chooseMessageFile({
			count: 1,
			type: 'video',
			success(res : any) {
				// tempFilePath可以作为img标签的src属性显示图片
				upload(res.tempFiles[0].path, MessageType.file, res.tempFiles[0].name)
			}
		})
		//#endif
	}
	const chooseImage = async () => {
		//#ifdef H5
		let userAgent = navigator.userAgent
		if (userAgent.match(/huawei/i)) {
			if(data.show==false){
				uni.showModal({
					title: '相册权限说明',
					content: '便于您使用该功能上传您的照片/图片/视频及用户实名认证信息、发布房源时上传图片，请您确认授权，否则无法使用该功能',
					success: (res) => {
						data.show = true;
						uni.chooseImage({
							count: 1,
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], //从相册选择或者相机
							success: function (res) {
								upload(res.tempFilePaths[0], MessageType.image, '')
							}
						});
					},
					fail: () => {
				
					}
				})
			}else{
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择或者相机
					success: function (res) {
						upload(res.tempFilePaths[0], MessageType.image, '')
					}
				});
			}
			
		} else {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择或者相机
				success: function (res) {
					upload(res.tempFilePaths[0], MessageType.image, '')
				}
			});
		}
		//#endif
	}
	const upload = (path : string, messageType : string, fileName : string) => {
		uni.showLoading({
			title: '上传中'
		})
		uni.uploadFile({
			url: `${FetchRequest.getHost()}/${VimConfig.uploadType}/upload`, //仅为示例，非真实的接口地址
			filePath: path,
			name: 'file',
			header: {
				"Access-Control-Allow-Origin": "*",
				"Authorization": "Bearer " + Auth.getToken(),
			},
			formData: {
				'type': messageType
			},
			success: (res) => {
				uni.hideLoading()
				const data = JSON.parse(res.data)
				const extend = (messageType === MessageType.file) ? { url: data.url, fileName: fileName } : { url: data.url };
				if (userId) {
					let msg : Message = {
						messageType: messageType,
						chatId: props.chatId,
						fromId: userId,
						content: '',
						type: props.chatType,
						extend: extend
					}
					useWsStore().sendMessage(msg)
				}
			},
			fail: () => {
				uni.hideLoading()
				MessageUtils.message('上传失败')
			},
		});
	}
</script>

<style scoped>
	.text-xxl {
		font-size: 64upx;
	}
</style>