<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="医生" :list="doctors" :width="200" placeholder="搜索医生"/>
          <radio-filter v-model="queryForm.orderSource" :list="terminalOptions" label="终端" :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="count" label="提交处方订单数" :width="140" />
        <el-table-column prop="passCount" label="" :width="120">
          <template #header>
            <el-tooltip placement="top" effect="light" content="审核通过的处方数">
              <span class="inline-flex items-center">
                <span>生效处方数</span><el-icon class="ml-2px transform -translate-y-1px">
                  <QuestionFilled />
                </el-icon>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="passInvalidCount" label="" :width="140">
          <template #header>
            <el-tooltip placement="top" effect="light" content="审核通过之后废除的处方数">
              <span class="inline-flex items-center">
                <span>最终废除处方数</span><el-icon class="ml-2px transform -translate-y-1px">
                  <QuestionFilled />
                </el-icon>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
  </my-layout>
</template>
<script setup>
import { computed, ref, onMounted } from "vue";
import { getDoctorRxStats, getAllDoctorNos } from "@/api/hlw";
import useElPagination from "@/hooks/useElPagination";

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

import pagination from "@/components/pagination/pagination.vue";
import { dayjs, ElMessage } from "element-plus";
import * as XLSX from "xlsx";

const queryForm = ref({
  dates: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
  doctorCodes: "",
  orderSource: ''
});
const terminalOptions = [
  { value: "ALIPAY_MINI", label: "支付宝小程序" },
  { value: "MATEPAD", label: "门店pad" },
];

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 doctors = ref([]);
const tableData = computed(() => {
  const res = list.value.reduce((acc, cur) => {
    const { _id, ...rest } = cur;
    if (_id) acc[_id] = rest;
    return acc;
  }, {});
  return doctors.value.filter(i => (params.value.doctorCodes || []).includes(i.value)).map(i => {
    const data = res[i.value] || {};
    return {
      name: i.label,
      doctorNo: i.value,
      count: data.count || 0,
      passCount: data.passCount || 0,
      passInvalidCount: data.passInvalidCount || 0
    }
  }).filter(i => i.count > 0).sort((a, b) => (b.count || 0) - (a.count || 0));
})
const summaryRow = computed(() => {
  const sum = {
    count: 0,
    passCount: 0,
    passInvalidCount: 0
  };
  list.value.forEach(item => {
    sum.count += item.count || 0;
    sum.passCount += item.passCount || 0;
    sum.passInvalidCount += item.passInvalidCount || 0;
  });
  return sum;
});

function search() {
  params.value = {
    startDate: queryForm.value.dates[0],
    endDate: queryForm.value.dates[1],
    orderSource: queryForm.value.orderSource,
    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.count,
    "生效处方数": row.passCount,
    "最终废除处方数": row.passInvalidCount,
  }));
  exportData.push({
    "医生名字": "合计",
    "医生工号": "",
    "提交处方订单数": summaryRow.value.count,
    "生效处方数": summaryRow.value.passCount,
    "最终废除处方数": summaryRow.value.passInvalidCount,
  });
  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', 'passCount', 'passInvalidCount']
  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: [],
    doctorCodes: []
  };
  search();
}

async function getList() {
  const { success, message, data } = await getDoctorRxStats({ ...params.value });
  list.value = data && Array.isArray(data.data) ? data.data : []
  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>
<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>
