<template>
  <div class="btn-content">
    <Popover
      color="rgba(107, 117, 138, 0.5)"
      :show="isShowPopover"
      @hover="handleMouseEnter"
      trigger="hover"
    >
      <template #content>
        <DeviceSelect :deviceType="DeviceType.SPEAKER"></DeviceSelect>
      </template>
      <template #trigger>
        <Button 
          :iconSrc="config.iconSrc"
          :color="config.color"
          :iconSize="props.iconSize || config.iconSize"
          :width="props.width || config.width"
          :height="props.height || config.height"
          :shape="config.shape"
          @click="handleClick"
        >
        </Button>
      </template>
    </Popover>
    <TKText
      v-if="config.showText"
      width="60px"
      :truncated="true"
      :textStyle="config.textStyle"
      :color="config.textColor"
      :size="config.textSize"
      :lineClamp='2'
    >
      {{getButtonText()}}
    </TKText>
  </div>
</template>

<script lang="ts">
export default {
  options: {
    virtualHost: true,
  },
};
</script>

<script lang="ts" setup>
import { computed, toRefs } from '../../../../adapter-vue';
import { TUICallKitServer, TUIGlobal, t } from '../../../../TUICallService/index';
import { DeviceType } from '../../../../TUICallService/const';
import Button from '../../base/Button/Button.vue';
import TKText from '../../base/TKText/TKText.vue';
import Popover from '../../base/Popover/Popover.vue';
import DeviceSelect from '../DeviceSelect/DeviceSelect.vue';
import { useDeviceList } from '../../../hooks';
import { useBtnConfig } from './hooks/useConfig';
import { ButtonProps } from './props/Button';
import { useCallInfoContext, usePopover } from '../../../hooks';

const isWeChat = TUIGlobal.isWeChat;
const props = defineProps(ButtonProps);
const { isEarPhone } = toRefs(useCallInfoContext());
const popoverValue = usePopover();
const isShowPopover = computed(() => popoverValue.value === 'speaker');
const configState = computed(() => (isEarPhone.value ? 'closedConfig' : 'basicConfig'))
const [{ deviceList, currentDeviceId }] = useDeviceList(DeviceType.SPEAKER);
const config = useBtnConfig('speaker', configState);
const btnText = computed(() => (isEarPhone.value ? t('ear piece') : t('speaker phone')));
const handleClick = async () => {
  if (isWeChat) {
    TUICallKitServer.setSoundMode();
  }
};
const getButtonText = () => {
  if (isWeChat) {
    return btnText.value;
  } else {
    const result = deviceList.value.find(item => item.deviceId === currentDeviceId.value);
    return result ? result.label : t('speaker phone');
  }
};
const handleMouseEnter = () => {
  popoverValue.value = 'speaker';
};
</script>

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