<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="false" class="flex-grow" :expand="expand">
          <date-range-filter v-model:dates="queryForm.dates" :showShortcuts="false" label="日期" :text="orderDatesText"
            :width="240" />
          <check-box-filter filterable v-model="queryForm.doctorCodes" label="医生" placeholder="搜索医生" :list="doctors" :width="240" />
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" @click="download">导出Excel</el-button>
          <el-button plain @click="clear">重置</el-button>
        </div>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table v-loading="loading" height="100%" border :data="tableData">
        <el-table-column prop="name" label="医生名字" :width="120" />
        <el-table-column prop="doctorNo" label="医生工号" :width="120" />
        <el-table-column prop="acceptDuration" label="平均接诊时长（秒）" :width="180" />
        <el-table-column prop="rxDuration" label="平均问诊开方时长（秒）" :width="200" />
      </el-table>
    </layout-main>
  </my-layout>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import { expandFilterBox, CheckBoxFilter, DateRangeFilter } from "@/components/filter-bar";
import { dayjs, ElMessage } from "element-plus";
import * as XLSX from "xlsx";
import { getAllDoctorNos, getDoctorTimeStats } from "@/api/hlw";
import BigNumber from "bignumber.js";

const queryForm = ref({
  dates: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
  doctorCodes: []
});
const params = ref({});
const canExpand = ref(false);
const expand = ref(false);
const loading = ref(false);
const doctors = ref([]);
const acceptStatsList = ref([]);
const rxStatsList = ref([]);
const orderDatesText = computed(() => queryForm.value.dates.length > 0 ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}` : "全部");

const tableData = computed(() => {
  const accept = acceptStatsList.value.reduce((acc, cur) => {
    const sumAccept = typeof cur.sumAccept === "number" ? cur.sumAccept : 0;
    const sum = typeof cur.sum === "number" ? Math.max(cur.sum, 1) : 1;
    const avgConsultTime = sumAccept > 0 ? new BigNumber(sumAccept).div(sum).div(1000).toNumber() : 0;
    if (cur._id) acc[cur._id] = avgConsultTime.toFixed(2)
    return acc;
  }, {});
  const rx = rxStatsList.value.reduce((acc, cur) => {
    const sumRx = typeof cur.sumRx === "number" ? cur.sumRx : 0;
    const sum = typeof cur.sum === "number" ? Math.max(cur.sum, 1) : 1;
    const avgRxTime = sumRx > 0 ? new BigNumber(sumRx).div(sum).div(1000).toNumber() : 0;
    if (cur._id) acc[cur._id] = avgRxTime.toFixed(2)
    return acc;
  }, {});
  return doctors.value.filter(i => (params.value.doctorCodes || []).includes(i.value)).map(i => {
    return {
      name: i.label,
      doctorNo: i.value,
      acceptDuration: accept[i.value] || '-',
      rxDuration: rx[i.value] || '-',
    }
  }).filter(i => i.acceptDuration > 0 || i.rxDuration > 0).sort((a, b) => (b.count || 0) - (a.count || 0));
})

function search() {
  params.value = {
    startDate: queryForm.value.dates[0],
    endDate: queryForm.value.dates[1],
    doctorCodes: queryForm.value.doctorCodes.length > 0 ? queryForm.value.doctorCodes : doctors.value.map(i => i.value),
  }
  // 查询逻辑
  getList()
}

function download() {
  const exportData = tableData.value.map(row => ({
    "医生名字": row.name,
    "医生工号": row.doctorNo,
    "平均接诊时长（分钟）": row.acceptDuration,
    "平均问诊开方时长（分钟）": row.rxDuration,
  }));
  const ws = XLSX.utils.json_to_sheet(exportData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "医生时效统计");
  XLSX.writeFile(wb, "医生时效统计.xlsx");
}

function clear() {
  queryForm.value = {
    dates: [],
    doctorCodes: []
  };
  search();
}

async function getList() {
  const { success, message, data } = await getDoctorTimeStats({ ...params.value });
  acceptStatsList.value = data && data.acceptList && Array.isArray(data.acceptList) ? data.acceptList : [];
  rxStatsList.value = data && data.rxtList && Array.isArray(data.rxtList) ? data.rxtList : [];

  if (!success) {
    ElMessage.error(message);
  }
}

async function getDoctors() {
  const { data } = await getAllDoctorNos();
  doctors.value =
    data && data.data && Array.isArray(data.data)
      ? data.data.map((i) => ({
        label: i.doctorName,
        value: i.doctorNo,
      }))
      : [];
}
onMounted(() => {
  getDoctors().then(() => {
    search();
  })
});
</script>
