<template>
  <my-layout class="bg-[#f2f3f4]">
    <layout-item>
      <div class="flex items-center p-15px bg-white border-b border-gray-200">
        <el-date-picker clearable v-model="dates" type="daterange" class="w-280px flex-grow-0" placeholder="全部日期" />
        <el-button :loading="loading" type="primary" class="ml-10px" @click="getList">查询</el-button>
      </div>
    </layout-item>
    <layout-main v-loading="loading" class="bg-white">
      <div class="my-10px px-15px">
        <div v-for="i in groups" :key="i.year">
          <div active-title-bar class="mb-10px">{{ i.year }}</div>
          <el-timeline>
            <el-timeline-item v-for="item in i.items" type="primary" :timestamp="item.date" placement="top">
              <el-card>
                <el-form>
                  <el-row>
                    <el-col :lg="6" :md="8" :xs="12">
                      <el-form-item class="mb-0" label="科室：">{{ item.deptName }}</el-form-item>
                    </el-col>
                    <el-col :lg="6" :md="8" :xs="12">
                      <el-form-item class="mb-0" label="医生：">{{ item.doctorName }}</el-form-item>
                    </el-col>
                    <el-col :lg="12" :md="8" :xs="24">
                      <el-form-item class="mb-0" label="诊断：">{{ item.diagnosisStr }}</el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item v-if="item.prescriptionType === 'medicalWinePurchase'" class="mb-0" label="药品：">
                        {{ item.wineStr }}
                      </el-form-item>
                      <el-form-item v-else class="mb-0" label="药品：">{{ item.drugStr }}</el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item class="mb-0" label="">
                        <div class="flex flex-grow justify-end">
                          <el-button plain type="primary" @click="viewDetail(item)">查看详情</el-button>
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </layout-main>
  </my-layout>
  <!-- <preview-modal :visible="previewVisible" :form="form" :diagnosisList="diagnosisList" :drugs="drugs"
    @close="previewVisible = false" /> -->
  <rx-paper-drawer :visible="previewVisible" :data="form" @close="previewVisible = false" />
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { useHlw } from "@/api/hlw";
import useModal from '@/hooks/useModal';

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import illnessSummary from "@/components/illness-summary/illness-summary.vue";
// import previewModal from './preview-modal.vue';
import RxPaperDrawer from "@/components/rx-paper-drawer/rx-paper-drawer.vue";

const props = defineProps({
  patient: {
    type: Object,
    default: () => ({})
  }
});

const dates = ref([]);
const list = ref([]);
const loading = ref(false);
const form = ref({});
const { close: cancelPreview, show: showPreview, visible: previewVisible, width: previewWidth } = useModal(800);

const groups = computed(() => {
  const map = new Map();
  list.value.forEach(item => {
    const year = dayjs(item.createTime).format('YYYY');
    if (!map.has(year)) {
      map.set(year, []);
    }
    map.get(year).push(item);
  });
  return Array.from(map.entries()).map(([year, items]) => {
    return {
      year,
      items: items.sort((a, b) => new Date(b.createTime) - new Date(a.createTime)),
    };
  });
});

function viewDetail(item) {
  form.value = item;
  showPreview();
}

async function getList() {
  if (props.patient && props.patient.patientId) {
    loading.value = true
    const query = { patientId: props.patient.patientId };
    if (dates.value && dates.value.length) {
      query.startDate = dates.value[0];
      query.endDate = dates.value[1];
    }
    const { data, success, message } = await useHlw({ type: 'getPatientPassDiagnosisRecord', ...query });
    list.value = data && Array.isArray(data.data) ? data.data.map(i => {
      const diagnosisStr = Array.isArray(i.diagnosisList) ? i.diagnosisList.map(d => d.name).join('、') : '';
      const drugStr = Array.isArray(i.drugs) ? i.drugs.map(d => `${d.drugName} ${d.specification || ''}`).join('、') : '';
      const wineStr = Array.isArray(i.wines) ? i.wines.map(w => `${w.name} x ${w.quantity} ${w.unit} ${w.details ? `(${w.details})` : ''}`).join('、') : '';
      return {
        ...i,
        date: dayjs(i.createTime).format('MM-DD HH:mm'),
        diagnosisStr,
        drugStr,
        wineStr
      }
    }) : [];
    if (!success) {
      ElMessage.error(message || '获取数据失败，请稍后重试！')
    }
    loading.value = false
  } else {
    list.value = [];
  }
  console.log('list.value: ', list.value)
}

async function getRx() {
  if (current.value && current.value.orderId) {
    loading.value = true
    const query = { orderId: current.value.orderId, doctorNo: current.value.doctorCode, status: 'PASS' };
    const { data, success, message } = await useHlw({ type: 'getOrderDiagnosis', ...query });
    rx.value = data && data.data ? data.data : null;
    loading.value = false
  } else {
    rx.value = [];
  }
}

onMounted(() => {
  getList()
})



</script>