<template>
  <div class="wrap">
    <el-row :gutter="20">
      <el-col :span="showType ? 6 : 24"> 
        <patient-info :patientCallNumber="patientCallNumber" ></patient-info>
      </el-col>
      <el-col v-if="showType" :span="18">
        <div class="info-card">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="变更日志" name="six">
              <log :patientId="patientId" @getLogs="getLogs" />
            </el-tab-pane>

            <el-tab-pane label="工单" name="third">
              <div>
                <el-table
                  :data="tableData2"
                  stripe
                  border
                  :default-sort="{ prop: 'date', order: 'ascending' }"
                  @sort-change="handleSortChange"
                >
                <el-table-column  prop="workordercode" label="工单编号">
                  <template #default="scope">
                    <a style="color: blue" @click="openWorkHandle(scope.row)">{{ scope.row['workordercode'] }}</a>
                  </template>
                </el-table-column>
                <el-table-column  prop="workordercatename" label="工单类型"></el-table-column>
                <el-table-column  prop="content" label="工单内容"></el-table-column>
                <el-table-column  prop="dealusername" label="受理人"></el-table-column>
                <el-table-column  prop="createtime" label="受理时间"></el-table-column>
                <el-table-column  prop="limittime" label="办理时限"></el-table-column>
                <el-table-column  prop="workorderstatename" label="状态"></el-table-column></el-table>
            
                <el-pagination
                  style="float: right; margin-top: 15px;"
                  @size-change="handleSizeChange2"
                  @current-change="handleCurrentChange2"
                  :current-page="currentPage2"
                  :page-sizes="[10, 20, 30]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total2"
                >
                </el-pagination>
              </div>
            </el-tab-pane>

            <el-tab-pane label="标签变更历史" name="tagHistory">
              <div>
                <el-timeline @scroll="handleScroll" style="max-height: 500px; overflow-y: auto;padding: 10px;" v-if="tagChangeLogs.length">
                  <el-timeline-item
                    v-for="(log, index) in tagChangeLogs"
                    :key="index"
                    :timestamp="log.changeTime"
                    type="primary"
                  >
                    <div class="tag-change-item">
                      <div style="margin-bottom: 8px;">
                        <span style="color: #606266; font-size: 12px">{{ log.createTime }}</span>
                      </div>
                      <div style="margin-bottom: 8px">
                        <el-tag size="small" :type="log.type === '添加标签' ? 'success' : log.type === '取消标签' ? 'danger' : 'warning'">
                          {{ log.type }}
                        </el-tag>
                        <span style="margin-left: 10px">{{ log.content }}</span>
                      </div>
                      
                      <div style="margin-top: 8px">
                        <a v-if="log.workordercode" style="color: blue" @click="openWorkHandle({ workordercode: log.workordercode })">
                          {{ log.workordercode || '无' }}
                        </a>
                        <!-- <el-icon style="margin-left: 20px; cursor: pointer" @click="playRecording(log.recordingUrl)">
                          <Microphone />
                        </el-icon> -->
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <el-empty v-else description="暂无标签变更历史" />
                <!-- <div v-if="!tagChangeLogs.length" style="text-align: center; margin-top: 20px;">
                  暂无标签变更历史
                </div> -->
              </div>
            </el-tab-pane>
            <el-tab-pane label="通话记录" name="fourth">
              <div>
                <el-table
                  :data="tableData"
                  stripe
                  border
                  :default-sort="{ prop: 'date', order: 'ascending' }"
                  @sort-change="handleSortChange"
                >
                <el-table-column label="电话号码">
                  <template #default="scope">
                    {{ getOfffixNuber(scope.row.callType==1 ? scope.row.caller : scope.row.callee) }}
                  </template>
                </el-table-column>
                <el-table-column label="坐席工号">
                  <template #default="scope">
                    {{ scope.row.callType==2 ? scope.row.callerAgent : scope.row.calleeAgent }}
                  </template>
                </el-table-column>
                <el-table-column label="坐席分机号">
                  <template #default="scope">
                    {{ scope.row.callType==2 ? scope.row.caller : scope.row.callee }}
                  </template>
                </el-table-column>
                <el-table-column label="呼叫状态">
                  <template #default="scope">
                    {{ getCallSate(scope.row.callType, scope.row.isAnswer) }}
                  </template>
                </el-table-column>
                <el-table-column prop="answerTime" label="通话开始时间"></el-table-column>
                <el-table-column prop="hangupTime" label="通话结束时间"></el-table-column>
                <el-table-column label="通话时长">
                  <template #default="scope">
                    {{ getTimeLimit(scope.row.answerTime, scope.row.hangupTime) }}
                  </template>
                </el-table-column>
                 
                </el-table>
            
                <el-pagination
                  style="float: right; margin-top: 15px;"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-tab-pane>
    
            
          </el-tabs>
        </div>
      </el-col>
    </el-row>

    <page-modal :defaultInfo="defaultInfo" ref="pageModalRef" pageName="/patient/patient" @submit="submit"
      :modalConfig="modalConfigRef"></page-modal>

  </div>
</template>

<script setup>
import { ref, onMounted, watch, toRaw } from "vue";
import patientInfo from "../patientInfo/patientInfo";
// import medicalInfo from "../medicalInfo/medicalInfo";
// import inHospital from "../inHospital/inHospital";
// import visitLogs from '../visitLogs/visitLogs.vue'
import log from "../logs/log.vue";

import patientIcon from '@/assets/images/patientIcon.png'
import { useRoute,useRouter } from 'vue-router';
import { getPatientInfo } from '@/api/patient/patient';
import { userDecryptToAsterisk,userDecrypt } from '@/utils/aes'
import { nations, patientStatus, sex, patientSource, phoneStatus } from "@/utils/commonDic.js";
import { getStrById, areaTrees } from "@/utils/area.js";
import { ArrayToMap } from '@/utils/tools'
import PageModal from '@/components/page-modal'
import { usePageModal } from '@/hooks/use-page-modal'
import { modalConfig } from '../../config/modal.config'
import { ElMessage } from 'element-plus'
import { Avatar, Edit } from '@element-plus/icons-vue'
import { getPageListData } from '@/api/main/system/system';
import { getCallSate, getUnprefixNuber,getOfffixNuber } from '@/utils/index';
import { Microphone } from '@element-plus/icons-vue';
const router = useRoute();
const routerPath = useRouter();
// 通话记录开始
// 模拟表格数据
const { proxy } = getCurrentInstance();
const total = ref(0)
const tableData = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
function getCalllog(phone) {
  queryParams.value.phone = phone
  getPageListData('/call/calllog',queryParams.value).then((res)=>{
    tableData.value = []
    total.value = 0
    if (res.data.length>0) {
      tableData.value = res.data
      console.log(tableData.value)
      total.value = res.total
    }
  })
}
function getTimeLimit(startTime, endTime) {
  return proxy.getTimeDifference(startTime, endTime);
}


// 当前页码
const currentPage = ref(1)
// 每页显示条数
const pageSize = ref(10)

// 处理每页显示条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  queryParams.value.pageSize = newSize
  getCalllog(queryParams.value.phone)
}

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  queryParams.value.pageNum = newPage
  getCalllog(queryParams.value.phone)
}

// 处理表格排序变化
const handleSortChange = ({ prop, order }) => {
  console.log(`排序字段: ${prop}, 排序顺序: ${order}`)
  // 这里可以根据 prop 和 order 对 tableData 进行排序
}
// 通话记录结束

// 工单开始
const total2 = ref(0)
const tableData2 = ref([])
const queryParams2 = ref({
  listType: 0,
  pageNum: 1,
  pageSize: 10,
})
function getWorkorder(phone) {
  queryParams2.value.callnum = phone
  getPageListData('/order/workorder',queryParams2.value).then((res)=>{
    tableData2.value = []
    total2.value = 0
    if (res.data.length>0) {
      tableData2.value = res.data
      console.log(tableData2.value)
      total2.value = res.total
    }
  })
}
// 处理弹出框
function openWorkHandle(rowData) { 
  let type = 'djb'
  let query = {
    workordercode : rowData.workordercode,
    type,
    listType:0
  }
  sessionStorage.setItem('workQuery', JSON.stringify(query))
  routerPath.push({ path : '/workHandle' }) 
}
// 当前页码
const currentPage2 = ref(1)
// 每页显示条数
const pageSize2 = ref(10)

// 处理每页显示条数变化
const handleSizeChange2 = (newSize) => {
  pageSize.value = newSize
  queryParams2.value.pageSize = newSize
  getWorkorder(queryParams2.value.phone)
}

// 处理当前页码变化
const handleCurrentChange2 = (newPage) => {
  queryParams2.value.pageNum = newPage
  getWorkorder(queryParams2.value.phone)
}

// 工单结束

// 标签变更历史开始
const tagChangeLogs = ref([]);


const tagQueryParams = ref({ // 标签变更查询参数
  pageNum: 1,
  pageSize: 20,
});
const isLoading = ref(false); // 加载状态
const noMoreData = ref(false); // 是否还有更多数据

// 获取标签变更记录
function getTagChangeLogs() {
  if (isLoading.value || noMoreData.value) return;
  console.log('patientId.value',patientId.value)
  isLoading.value = true;
  tagQueryParams.value.patientId = patientId.value;
  getPageListData('/patient/taghistory', tagQueryParams.value).then((res) => {
    if (res.data && res.data.length > 0) {
      tagChangeLogs.value = [...tagChangeLogs.value, ...res.data];
      tagQueryParams.value.pageNum++;
    } else {
      noMoreData.value = true;
    }
    isLoading.value = false;
  }).catch(() => {
    isLoading.value = false;
  });
}

// 滚动加载更多
// 记录上次触发加载的时间戳
let lastLoadTime = 0;
const LOAD_THROTTLE_TIME = 500; // 节流时间500ms

function handleScroll() {
  const timelineEl = document.querySelector('.el-timeline');
  const now = Date.now();
  
  if (timelineEl && 
      timelineEl.scrollHeight - timelineEl.scrollTop <= timelineEl.clientHeight + 100 &&
      now - lastLoadTime > LOAD_THROTTLE_TIME &&
      !isLoading.value && !noMoreData.value) {
    lastLoadTime = now;
    getTagChangeLogs();
  }
}

// 播放录音
function playRecording(url) {
  // 假设已有录音播放逻辑，这里触发播放
  console.log('播放录音，URL：', url);
}
// 标签变更历史结束

const activeName = ref('six')
function handleClick() {
}



let detail = ref({});

const patientId = ref(router.query.patientId || router.query.id);

const props = defineProps({
  descColumn: {
    type: Number,
    default: 4,
  },
  patientCallNumber:{
    type:String,
    default:''
  },
  showType: {
    type: Number,
    default: 1,
  }
})
watch(props, (nweProps) => {
    // if (nweProps.patientCallNumber) {
    //   getTagChangeLogs(); // 监听props变化时获取标签变更记录
    // }
    if (nweProps.patientCallNumber) {
      customerDetail(nweProps.patientCallNumber)
      getCalllog(nweProps.patientCallNumber)
      getWorkorder(nweProps.patientCallNumber)
    }
});

onUpdated(() => {
  patientId.value = router.query.patientId || router.query.id;
  console.log(patientId.value);
});
const getPatientId = computed(() => {
  return router.query.patientId || router.query.id;
});
watch(getPatientId, async (newValue) => {
  console.log('newValue',newValue)
  patientId.value = newValue;
  initLableLogsParams();
  getDetail(newValue).then(() => { });
})

const initLableLogsParams = () => {
  noMoreData.value = false;
  isLoading.value = false;
  tagQueryParams.value.pageNum = 1;
  tagChangeLogs.value = [];
}

const stateLog = ref();
async function customerDetail(customerno) {
    const resultData = await getPageListData('/patient/patient',{phoneNumber:customerno});
    detail.value = resultData.data[0]
    console.log('customerDetail',detail.value);
}
const getDetail = async () => {
  const res = await getPatientInfo(patientId.value)
  detail.value = res.data
  console.log('getPatientInfo',detail.value);
  if (detail.value.phoneNumber) {
    getCalllog(userDecrypt(detail.value.phoneNumber))
    getWorkorder(userDecrypt(detail.value.phoneNumber));
  }
  
  getTagChangeLogs()
  
}
onBeforeMount(async () => {
  if (props.patientCallNumber) {
    customerDetail(props.patientCallNumber)
  } else{
    await getDetail(patientId.value);
  }
})
const statusMap = ArrayToMap(patientStatus, 'value');
const sourceMap = ArrayToMap(patientSource, 'value');
const phoneStatusMap = ArrayToMap(phoneStatus, 'value');
const sexMap = ArrayToMap(sex, 'value');
const nationsMap = ArrayToMap(nations, 'value');

const getLogs = (logs) => {
  // 获取当前状态对应的数据
  if (phoneStatusMap[detail.value.phoneStatus] && phoneStatusMap[detail.value.phoneStatus].showLog) {
    stateLog.value = logs.find((o) => {
      return o.type === '状态变更';
    })
    console.log(stateLog.value, 'stateLog.value');
  }

}

</script>

<style lang="scss" scoped>
  :deep(.el-descriptions__label){
    width: 80px;
    text-align: right;
    display: inline-block;
  }
  .cardInfo{
    width: 100%;
    line-height: 30px;
    background-color: #F3F9FF;
    display: flex;
    padding: 10px;
  }
.wrap {
  .info-header {
    padding: 30px;
    padding-right: 0px;
    width: 100%;
    .title-text {
      margin-left: 10px;
      font-size: 16px;
      font-weight: bold;
    }

    .title-time {
      margin-left: 10px;
      font-size: 14px;
      font-weight: normal;
      color: #606266;
    }

    .title-reson {
      color: #F56C6C;
      font-size: 14px;
      font-weight: normal;
      margin-left: 5px;
    }

  }

  .info-card {
    margin: 0px 30px 30px 30px;
  }
}
</style>