<script setup>
import LiveCallItem from '@/components/liveCall/LiveCallItem.vue'
import {getHistoryCallContent} from '@/api/workbench';
import {ElMessage} from "element-plus";

const dialogVisible = ref(false);
const recordLeftRef = ref(null);
const emit = defineEmits(['update:value'])
const props = defineProps({
  value: {
    type:String,
    default:''
  }
})

const open = (row) => {
  dialogVisible.value = true;
};

const leftHeadData = ref({
  // username: '张三',
  // phone: '13546812315',
  // orderName: '张三工单',
})
const detailLoading=ref(false)
const recordLeftObj = ref({});
const _value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("update:value", val);
  }
})
const convertArrayToMap=(array)=> {
  const map = new Map();
  array.forEach(item => {
    // 如果时间戳对应的键已经存在，则添加到现有数组中
    if (map.has(item.conversationTimestamp)) {
      map.get(item.conversationTimestamp).push(item);
    } else {
      // 否则，创建一个新的数组并添加元素
      map.set(item.conversationTimestamp, [item]);
    }
  });
  return map;
}

watch(() => props.value, async (newVal) => {
  if(newVal){

    getHistoryDetail(newVal)
  }
})
const getHistoryDetail=(newVal)=>{
  detailLoading.value=true
   getHistoryCallContent(newVal).then(res => {
     if (res.code === 1000) {
       detailLoading.value=false
       res.data?.forEach(item => {
         if( item.textVoList&& item.textVoList.length>0){
           item.textVoList = convertArrayToMap(item.textVoList);
         }
       })
       recordLeftObj.value = res.data
       if (res.data && res.data.length > 0) {
         leftHeadData.value.username = res.data[0].name || '--';
         leftHeadData.value.phone = res.data[0].callPhone || '--';
         leftHeadData.value.orderName = res.data[0].orderName || '--';
       }
     } else {
       ElMessage.error(res.msg);
     }
  })
}

const scrollToBottom = (scrollbarRef) => {
  if (scrollbarRef) {
    const container = scrollbarRef.$el.querySelector('.el-scrollbar__wrap');
    container.style.scrollBehavior = 'smooth'; // 添加平滑滚动效果
    container.scrollTop = container.scrollHeight;
  }
};

scrollToBottom(recordLeftRef.value)

defineExpose({
  open,
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="历史通话记录" width="700" class="box">
    <LiveCallItem ref="recordLeftRef" :recordArray="recordLeftObj" :headData="leftHeadData" style="width: 100%;" :detailLoading="detailLoading"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.box {
  /*height: 68vh;*/
}
</style>
