<template>
  <ToolbarItemContainer
    :iconFile="handleIcon()"
    :title="handleTitle()"
    :needDialog="false"
    :iconWidth="isUniFrameWork ? '32px' : '21px'"
    :iconHeight="
      isUniFrameWork
        ? props.videoSourceType === 'album'
          ? '20px'
          : '25px'
        : '18px'
    "
    @onIconClick="onIconClick"
  >
    <div :class="['video-upload', 'video-upload-h5']">
      <input
        ref="inputRef"
        :title="TUITranslateService.t('视频')"
        type="file"
        data-type="video"
        accept="video/*"
        @change="sendVideoInWeb"
      >
    </div>
  </ToolbarItemContainer>
</template>
<script lang="ts" setup>
import {
  TUIChatService,
  TUIStore,
  StoreName,
  IConversationModel,
  SendMessageParams,
  SendMessageOptions,
  TUITranslateService,
} from '../../../../@aidesk/uikit-engine';
import { TUIGlobal } from '@tencentcloud/universal-api';
import vue from '../../../../adapter-vue';
import {isWeChat, isUniFrameWork, isTikTok, isApp} from '../../../../utils/env';
import ToolbarItemContainer from '../toolbar-item-container/index.vue';
import videoUniIcon from '../../../../assets/video-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, onMounted, onUnmounted } = vue;
const props = defineProps({
  // Video source, only valid for uni-app version, web version only supports selecting videos from files
  // album: Select from files
  // camera: Take a video using the camera
  videoSourceType: {
    type: String,
    default: 'album',
  },
});

const inputRef = ref();
const currentConversation = ref<IConversationModel>();

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversation,
  });
  TUIStore.watch(StoreName.CUSTOM, {
    applyRecord: onApplyRecord,
    applySelectVideo: onApplySelectVideo,
  });
});

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

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

const handleIcon = (): string => {
  switch (props.videoSourceType) {
    case 'album':
      return videoUniIcon;
    case 'camera':
      return cameraUniIcon;
    default:
      return videoUniIcon;
  }
};

const handleTitle = (): string => {
  if (props.videoSourceType === 'camera') {
    return TUITranslateService.t('录制');
  } else {
    return TUITranslateService.t('视频');
  }
};

const onIconClick = () => {
  let showPrompt = false;
  if (isApp) {
    try {
      if (props.videoSourceType === '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.videoSourceType === 'camera' ? PROMPT.RECORD : PROMPT.SELECT_VIDEO);
    return;
  }

  // uni-app send video
  if ((isWeChat || isTikTok) && TUIGlobal?.chooseMedia) {
    TUIGlobal?.chooseMedia({
      mediaType: ['video'],
      count: 1,
      sourceType: [props.videoSourceType],
      maxDuration: 60,
      success: function (res: any) {
        sendVideoMessage(res);
      },
    });
  } else {
    chooseVideo(props.videoSourceType);
  }
};

const chooseVideo = (videoSourceType: string) => {
  TUIGlobal?.chooseVideo({
    count: 1,
    sourceType: [videoSourceType],
    compressed: false,
    success: function (res: any) {
      sendVideoMessage(res);
    },
  });
}

// 申请录制视频
const onApplyRecord = (data: boolean) => {
  if (data) {
    chooseVideo('camera');
  }
}

// 申请选择相册里的视频
const onApplySelectVideo = (data: boolean) => {
  if (data) {
    chooseVideo('album');
  }
}

const sendVideoInWeb = (e: any) => {
  if (e?.target?.files?.length <= 0) {
    return;
  }
  const file = e.target.files[0];
  if (!file || !file.size) {
    return;
  }
  sendVideoMessage(e.target);
  e.target.value = '';
};

const sendVideoMessage = (file: any) => {
  if (!file) {
    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>
