<template>
  <div class="app-container">
    <page-search
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick"
    />

    <page-content
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      pageName="/call/calllog"
      :isCreate="false"
      @sort-change="handleSortChange"
      @audioViewBtnClick="handleViewData"
      @recordCallBtnClick="handleRecordCall"
    >

      <template #noteSlot="scope">
        <span>{{ scope.row.note==2 ? '九院' : '八院' }}</span>
      </template>
    
      <template #recordAgentHandler="scope">
        {{ scope.row.callType==2 ? scope.row.callerAgent : scope.row.calleeAgent }}
        <!-- {{scope.row.calleeAgent }} -->
      </template>
      <template #recordCallerHandler="scope">
        {{ scope.row.callType==2 ? scope.row.caller : scope.row.callee }}
        <!-- {{scope.row.callee }} -->
      </template>
      <template #recordCallStateHandler="scope">
        {{ getCallSate(scope.row.callType, scope.row.isAnswer) }}
      </template>
      <template #timeLimit="{ row }">
        <span>{{ getTimeLimit(row.answerTime, row.hangupTime) }}</span>
      </template>
      <template #myd="{ row, options }">
        <span>{{
          row.myd
            ? options.options.find((o) => {
                return o.value === row.myd;
              })?.label ?? `按键${row.myd}`
            : '未评价'
        }}</span>
        <!-- <span>{{ row.myd + JSON.stringify(options)}}</span> -->
      </template>
      <template #recordCreatOrderHandler="scope">
        <el-button
          v-if="scope.row.callType === 1"
          size="small"
          type="primary"
          text
          @click="handleOrderCall(scope.row)"
          >{{ scope.row.workordercode ? '查看工单' : '创建工单' }}</el-button
        >
      </template>
    </page-content>
    <el-drawer title="通话录音" v-model="open" width="500px" :with-header="false" append-to-body direction="rtl">
      <audio-player v-if="open" :filePath="filePath" :recordId="clickId"/>
    
    </el-drawer>
    <el-dialog
      title="创建工单"
      v-model="openCreatOrder"
      center
      width="70%"
      :modal="false"
      :show-close="true"
    >
    
      <page-order
        :OrderSource="'话务'"
        :propRecordData="recordData"
        @refreshOrder="getDialogHandle"
      ></page-order>
    </el-dialog>
    <handle v-if="openViewOrder" v-model:dialogVisible="openViewOrder" :rowData="clRowData">
    </handle>
  </div>
</template>

<script>
  import { defineComponent, ref, computed, watch, getCurrentInstance } from 'vue';

  import PageSearch from '@/components/page-search';
  import PageContent from '@/components/page-content';
  // import audioPlayer from './cpns/audioPlayer';
  import audioPlayer from '@/components/callLogs/audioPlayer';

  import addOrder from '@/components/workOrder/add-order/add-order';
  import pageOrder from '@/components/page-order';

  import handle from '@/components/workOrder/handle';

  import { searchFormConfig } from './config/search.config';
  import { contentTableConfig } from './config/content.config';

  import { usePageSearch } from '@/hooks/use-page-search';
  import useSystemStore from '@/store/main/system/system';

  import useSocketStore from '@/store/modules/socket';
  import { Send } from '@/utils/telWebsocket';

  import { getPhoneFix } from '@/api/main/main';
  import { getPageListData } from '@/api/main/system/system';
  import { getCallSate, getUnprefixNuber,getOfffixNuber } from '@/utils/index';

  import { useRouter } from 'vue-router';

  export default defineComponent({
    name: 'CallRecord',
    components: {
      PageSearch,
      PageContent,
      audioPlayer,
      addOrder,
      pageOrder,
      handle,
    },
    setup() {
      const [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch();
      const { proxy } = getCurrentInstance();

      const pageModalRef = ref(audioPlayer);
      const recordData = ref({});
      const open = ref(false);
      const openCreatOrder = ref(false);
      const openViewOrder = ref(false);
      const filePath = ref('');
      const callPhoneFlag = ref(false);
      const scoketDatas = ref({});
      const clRowData = ref({});
      const router = useRouter();
      const lineState = computed(() => {
        return useSocketStore().lineState;
      });
      watch(lineState, (newValue, oldValue) => {
        if (newValue === '空闲') {
          callPhoneFlag.value = true;
        } else if (newValue === '签出') {
          callPhoneFlag.value = false;
        }
      });
      const clickId = ref(0);
      //查看详情
      const handleViewData = (data) => {
        console.log(data.recordPath);
        filePath.value = data.recordPath;
        console.log(data, 'data')
        clickId.value = data.id;
        console.log(clickId.value, 'clickId.value')
        open.value = true;
      };

      const getDialogHandle = () => {
        openCreatOrder.value = false;
          useSystemStore().getPageListAction({
            pageName: '/call/calllog',
            queryInfo: {
              pageNum: 1,
              pageSize: 10,
            },
          });
      };
      const handleOrderCall = (data) => {
        if (data.workordercode) {
          let query = {
            workordercode: data.workordercode,
            type: 'zhcx',
          };
          sessionStorage.setItem('workQuery', JSON.stringify(query));
          router.push({ path: '/workHandle' });
        } else {
          recordData.value = data;
          console.log(recordData.value)
          openCreatOrder.value = true;
        }
      };
      const handleRecordCall = (data) => {
        if (callPhoneFlag.value) {
          const callNumber = data.callType==1 ? data.caller : data.callee
          
          getPhoneFix(callNumber).then((data) => {
            if (data.state === 'success') {
              scoketDatas.value = {
                AgentId: useSocketStore().accountNumber,
                AgentExten: useSocketStore().extensionNumber,
                Type: 'MakeCall',
                DestinationNumber: data.data[0],
              };
              Send(scoketDatas.value, (data) => {
                console.log(data.Type);
                if (data.Type === 'MakeCall') {
                  console.log('外呼');
                  if (data.Result) {
                    proxy.$modal.msgSuccess('外呼成功');
                  } else {
                    proxy.$modal.msgSuccess('外呼失败');
                  }
                }
              });
            }
          });
        } else {
          console.log('你还没有签入');
        }
      };

      function getTimeLimit(startTime, endTime) {
        return proxy.getTimeDifference(startTime, endTime);
      }

      const handleSortChange = (sortInfo) => {
        console.log(sortInfo, 'handleSortChange');
        // pageContentRef.value.getPageData();
      };

      return {
        handleSortChange,
        clickId,
        getCallSate,
        router,
        getTimeLimit,
        clRowData,
        searchFormConfig,
        contentTableConfig,
        pageContentRef,
        handleResetClick,
        handleQueryClick,
        pageModalRef,
        recordData,
        open,
        openCreatOrder,
        openViewOrder,
        addOrder,
        pageOrder,
        filePath,
        getDialogHandle,
        handleViewData,
        handleRecordCall,
        handleOrderCall,
        lineState,
        scoketDatas,
        callPhoneFlag,
      };
    },
  });
</script>
