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

    <page-content
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      pageName="/call/calllog"
      :isCreate="false"
      @audioViewBtnClick="handleViewData"
      @recordCallBtnClick="handleRecordCall"
    >
    
      <template #recordAgentHandler="scope">
        {{ scope.row.callType ? scope.row.callerAgent : scope.row.calleeAgent }}
      </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-dialog title="录音" v-model="open" width="700px" append-to-body>
      <audio-player ref="pageModalRef" :filePath="filePath"></audio-player>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <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 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 handleViewData = (data) => {
        console.log(data.recordPath);
        filePath.value = data.recordPath;
        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) {
          console.log(data, 111);
          // const callNumber = getOfffixNuber(data.caller) ;
          const callNumber = data.caller;
          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);
      }

      return {
        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>
