<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>
	  <view class="flex-sub padding" v-if="chatType===ChatType.GROUP" @tap="phoneCall">
	    <text class="cuIcon-phone text-grey text-xxl"></text>
	    <view class="text-center text-xs">语音通话</view>
	  </view>
	  <view class="flex-sub padding" v-if="chatType===ChatType.GROUP" @tap="videoCall">
	    <text class="cuIcon-record text-grey text-xxl"></text>
	    <view class="text-center text-xs">视频通话</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';
//#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";

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 = () => {
  //#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 = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择或者相机
    success: function (res) {
      upload(res.tempFilePaths[0], MessageType.image, '')
    }
  });
}
const upload = (path: string, messageType: string, fileName: string) => {
  // uni.showLoading({
  //   title: '上传中'
  // })
  
  var localUrl='';
  if(messageType === MessageType.file){
	  localUrl=path;
  }
  else if(messageType === MessageType.image){
	  localUrl='/static/mix-tree/shangctp.png';
  }
  else{
  	  localUrl='/static/mix-tree/shangctp.png';
  }
  console.log(path)
  
  const extendA = (messageType === MessageType.file) ? {url:localUrl, fileName: fileName} : {url:localUrl};
  
  let msgA: Message = {
    messageType: messageType,
    chatId: props.chatId,
    fromId: userId,
    content: '',
    type: props.chatType,
    extend:extendA
  }
  var currentTime = new Date().getTime();
  msgA.localtime=currentTime;
  msgA.timestamp=currentTime;
  msgA.mine=true;
  msgA.id=JSON.stringify(currentTime);
  useWsStore().sendfileMessage(msgA);
  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)
	  if(data.code==500){
		  MessageUtils.message('上传失败')
		  useWsStore().sendfileMsgFalse(msgA);
		  return;
	  }
      const extendB = (messageType === MessageType.file) ? {url: data.url, fileName: fileName} : {url: data.url};
      if(userId){
		  let msg: Message = {
		    messageType: messageType,
		    chatId: props.chatId,
		    fromId: userId,
		    content: '',
			localtime:currentTime,
		    type: props.chatType,
		    extend: extendB
		  }
        useWsStore().sendMessage(msg)
      }
    },
    fail: () => {
      //uni.hideLoading()
	  useWsStore().sendfileMsgFalse(msgA);
      MessageUtils.message('上传失败')
    },
  });
}

const phoneCall = () =>{
	console.log('phoneCall')
	uni.navigateTo({
	  url: `/pages/group/xuanzequanyuan?id=${props.chatId}&showVideo=false&isCaller=true`
	})
}
const videoCall = () =>{
	uni.navigateTo({
	  url: `/pages/group/xuanzequanyuan?id=${props.chatId}&showVideo=true&isCaller=true`
	})
}
</script>

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

</style>
