<template>
  <ToolbarItemContainer
    :iconFile="imageToolbarForShow.icon"
    :title="imageToolbarForShow.title"
    :iconWidth="isUniFrameWork ? '32px' : '21px'"
    :iconHeight="isUniFrameWork ? '25px' : '18px'"
    :needDialog="false"
    @onIconClick="onIconClick"
    :isH5ToolShow="isH5ToolShow"
  >
  </ToolbarItemContainer>
</template>
<script lang="ts" setup>
import {
  IConversationModel,
  SendMessageOptions,
  SendMessageParams,
  StoreName,
  TUIChatService,
  TUIStore,
  TUITranslateService,
} from '../../../../@aidesk/uikit-engine';
import {TUIGlobal} from '@tencentcloud/universal-api';
import vue from '../../../../adapter-vue';
import {isApp, isUniFrameWork, isWeChat} from '../../../../utils/env';
import ToolbarItemContainer from '../toolbar-item-container/index.vue';
import imageUniIcon from '../../../../assets/image-uni.png';
import cameraUniIcon from '../../../../assets/camera-uni.png';
import {isEnabledMessageReadReceiptGlobal} from '../../../../utils/utils';
import {PROMPT} from '../../../../constant';
import state from "../../../../utils/state";

const { ref, computed, onMounted, onUnmounted } = vue;

const props = defineProps({
  // Image source: only valid for uni-app version, web version only supports selecting images from the album.
  // album: Select from album
  // camera: Take a photo using the camera
  imageSourceType: {
    type: String,
    default: 'album',
  },
  isH5ToolShow:{
    type: Boolean,
    default: false,
  }
});

const inputRef = ref();
const centerPopupRef = ref();
const currentConversation = ref<IConversationModel>();
const IMAGE_TOOLBAR_SHOW_MAP = {
  uni_album: {
    icon: imageUniIcon,
    title: TUITranslateService.t("图片"),
  },
  uni_camera: {
    icon: cameraUniIcon,
    title: TUITranslateService.t("拍照"),
  },
};

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversation,
  });
  TUIStore.watch(StoreName.CUSTOM, {
    applyTakePhoto: onApplyTakePhoto,
    applySelectImage: onApplySelectImage,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversation,
  });
  TUIStore.unwatch(StoreName.CUSTOM, {
    applyTakePhoto: onApplyTakePhoto,
    applySelectImage: onApplySelectImage,
  });
  // 清除这两个 key 对应的数据
  TUIStore.reset(StoreName.CUSTOM, ['applyTakePhoto', 'applySelectImage']);
});

const onCurrentConversation = (conversation: IConversationModel) => {
  currentConversation.value = conversation;
};

const imageToolbarForShow = computed((): { icon: string; title: string } => {
    return props.imageSourceType === 'camera'
      ? IMAGE_TOOLBAR_SHOW_MAP['uni_camera']
      : IMAGE_TOOLBAR_SHOW_MAP['uni_album'];
});

const onIconClick = () => {
  let showPrompt = false;
  if (isApp) {
    try {
      if (props.imageSourceType === 'camera') {
        let isCameraApplied = uni.getStorageSync('ai-desk-apply-camera');
        // 未申请过相机权限
        if (!isCameraApplied) {
          showPrompt = true;
        }
      } else {
        let isAlbumApplied = uni.getStorageSync('ai-desk-apply-album');
        // 未申请过相册权限
        if (!isAlbumApplied) {
          showPrompt = true;
        }
      }
    } catch (e) {
      showPrompt = false;
    }
  }

  // 在开关打开的情况下弹窗提醒
  if ((state.get('showPrompt') === 1) && showPrompt) {
    TUIStore.update(StoreName.CUSTOM, 'centerDialog', props.imageSourceType === 'camera' ? PROMPT.TAKE_PHOTO : PROMPT.SELECT_IMAGE);
    return;
  }

  // uni-app send image
  if (isWeChat && TUIGlobal?.chooseMedia) {
    TUIGlobal?.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['original', 'compressed'],
      sourceType: [props.imageSourceType], // Use camera or select from album.
      success: function (res: any) {
        if (res) {
          // tiktok 小程序选择出来的是 mediaType
          if (res.tempFiles[0].fileType === 'image' || res.tempFiles[0].mediaType === 'image') {
            sendImageMessage(res);
          } else if(res.tempFiles[0].fileType === 'video' || res.tempFiles[0].mediaType === 'video') {
            sendVideoMessage(res);
          }
        }
      },
    });
  } else {
    chooseImage(props.imageSourceType);
  }
};

const chooseImage = (sourceType: string) => {
  // uni-app H5/App send image
  TUIGlobal?.chooseImage({
    count: 1,
    sourceType: [sourceType], // Use camera or select from album.
    success: function (res) {
      if (res) {
        sendImageMessage(res);
      }
    },
  });
}

// 申请拍照
const onApplyTakePhoto = (data: boolean) => {
  if (data) {
    chooseImage('camera');
  }
}

// 申请从相册里选择照片
const onApplySelectImage = (data: boolean) => {
  if (data) {
    chooseImage('album');
  }
}

const sendImageMessage = (files: any) => {
  if (files.tempFiles[0].size === 0) {
    return;
  }
  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID
      || currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload: {
      file: files,
    },
    needReadReceipt: isEnabledMessageReadReceiptGlobal(),
  } as SendMessageParams;
  const sendMessageOptions: SendMessageOptions = {};
  TUIChatService.sendImageMessage(options, sendMessageOptions);
};
const sendVideoMessage = (file: any) => {
  if (file.tempFiles[0].size === 0) {
    return;
  }
  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID
      || currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload: {
      file,
    },
    needReadReceipt: isEnabledMessageReadReceiptGlobal(),
  } as SendMessageParams;
  const sendMessageOptions: SendMessageOptions = {};
  TUIChatService.sendVideoMessage(options, sendMessageOptions);
};
</script>

<style lang="scss" scoped>
@import "../../style/common";
</style>
