<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 v-model="queryForm.pharmacistNos" label="药师" :list="pharmacistNoList" :width="200" />
        </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" show-summary height="100%" border :data="tableData" :summary-method="summaryMethod">
        <el-table-column prop="name" label="药师名字" :width="120" />
        <el-table-column prop="doctorNo" label="药师工号" :width="120" />
        <!-- <el-table-column prop="orderTimes" label="接收处方次数" :width="140" /> -->
        <el-table-column prop="auditCount" label="审核通过次数" :width="120" />
        <el-table-column prop="rejectCount" label="审核不通过次数" :width="120" />
        <el-table-column prop="count" label="已审处方数" :width="140" />
        <el-table-column prop="expiredCount" label="超时未审核处方数" :width="140" />
      </el-table>
    </layout-main>
  </my-layout>
</template>
<script setup>
import { computed, ref, onMounted } from "vue";
import { dayjs, ElMessage } from "element-plus";
import * as XLSX from "xlsx";
import { getPharmacistRxStats, getAllDoctorNos } from "@/api/hlw";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import { expandFilterBox, CheckBoxFilter, DateRangeFilter } from "@/components/filter-bar";


const queryForm = ref({
  dates: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
  pharmacistNos: []
});

const orderDatesText = computed(() => queryForm.value.dates.length > 0 ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}` : "全部");

const canExpand = ref(false);
const expand = ref(false);
const loading = ref(false);
const params = ref({})
const list = ref([]);
const pharmacistNoList = ref([]);
const tableData = computed(() => {
  const res = list.value.reduce((acc, cur) => {
    const { _id, ...rest } = cur;
    if (_id) acc[_id] = rest;
    return acc;
  }, {});
  return pharmacistNoList.value.filter(i => (params.value.pharmacistNos || []).includes(i.value)).map(i => {
    const data = res[i.value] || {};
    const auditCount = typeof data.auditCount === 'number' ? data.auditCount : 0;
    const rejectCount = typeof data.rejectCount === 'number' ? data.rejectCount : 0;
    const count = typeof data.count === 'number' ? data.count : 0;
    const expiredCount = typeof data.expiredCount === 'number' ? data.expiredCount : 0;
    // const orderTimes = auditCount + rejectCount;
    return {
      name: i.label,
      doctorNo: i.value,
      // orderTimes,
      auditCount,
      rejectCount,
      count,
      expiredCount,
    }
  }).filter(i => i.count > 0).sort((a, b) => (b.count || 0) - (a.count || 0));
})
const summaryRow = computed(() => {
  const sum = {
    // orderTimes: 0,
    auditCount: 0,
    rejectCount: 0,
    count: 0,
    expiredCount: 0,
  };
  tableData.value.forEach(item => {
    // sum.orderTimes += item.orderTimes || 0;
    sum.auditCount += item.auditCount || 0;
    sum.rejectCount += item.rejectCount || 0;
    sum.count += item.count || 0;
    sum.expiredCount += item.expiredCount || 0;
  });
  return sum;
});

function search() {
  params.value = {
    startDate: queryForm.value.dates[0],
    endDate: queryForm.value.dates[1],
    pharmacistNos: queryForm.value.pharmacistNos.length > 0 ? queryForm.value.pharmacistNos : pharmacistNoList.value.map(i => i.value),
  }
  // 查询逻辑
  getList()
}
function download() {
  const exportData = tableData.value.map(row => ({
    "药师名字": row.name,
    "药师工号": row.doctorNo,
    // "接收处方次数": row.orderTimes,
    "审核通过次数": row.auditCount,
    "审核不通过次数": row.rejectCount,
    "已审处方数": row.count,
    "超时未审核处方数": row.expiredCount
  }));
  exportData.push({
    "药师名字": "合计",
    "药师工号": "",
    // "接收处方次数": summaryRow.value.orderTimes,
    "审核通过次数": summaryRow.value.auditCount,
    "审核不通过次数": summaryRow.value.rejectCount,
    "已审处方数": summaryRow.value.count,
    "超时未审核处方数": summaryRow.value.expiredCount
  });
  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 summaryMethod({ columns, data }) {
  const sums = [];
  const countColumns = ['count', 'validCount', 'passCount', 'passInvalidCount', 'rejectCount']
  columns.forEach(({ property }, index) => {
    if (index === 0) {
      sums.push('合计');
    } else if (summaryRow.value[property] !== undefined) {
      sums.push(summaryRow.value[property]);
    } else {
      sums.push('');
    }
  });
  return sums;
}

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

async function getList() {
  const { success, message, data } = await getPharmacistRxStats({ ...params.value });
  const list1 = data && Array.isArray(data.data) ? data.data : [];
  const list2 = data && Array.isArray(data.rejectRes) ? data.rejectRes : [];
  const allList = [...list1, ...list2];
  const m = allList.reduce((m, cur) => {
    if (cur._id) {
      const obj = m.get(cur._id) || {};
      m.set(cur._id, {
        ...obj,
        ...cur,
      });

    }
    return m
  }, new Map())
  list.value = Array.from(m.values()).sort((a, b) => (b.count || 0) - (a.count || 0));
  if (!success) {
    ElMessage.error(message);
  }
}

async function getDoctors() {
  const { data } = await getAllDoctorNos({ jobs: ['pharmacist'] });
  pharmacistNoList.value =
    data && data.data && Array.isArray(data.data)
      ? data.data.map((i) => ({
        label: i.doctorName,
        value: i.doctorNo,
      }))
      : [];
}

onMounted(() => {
  getDoctors().then(() => {
    search();
  })
});

</script>
<style lang="scss" scoped>
.explain-box {
  background: #ffe564;
  color: #222;
  border-radius: 6px;
  margin-top: 10px;
  padding: 10px 20px;
  box-shadow: 0 2px 8px #00000010;

  .explain-content {
    font-size: 14px;
    line-height: 2;
  }
}
</style>
