<template>
  <my-layout class="bg-[#f2f3f4]">
    <layout-item>
      <div class="flex items-center p-15px bg-white border-b border-gray-200">
        <el-select v-model="orderType" clearable placeholder="全部类型">
          <el-option v-for=" i in orderTypes" :key="i.value" :label="i.label" :value="i.value" />
        </el-select>
        <el-date-picker clearable v-model="dates" type="daterange" class="ml-10px w-280px flex-grow-0"
          placeholder="全部日期" />
        <el-button type="primary" class="ml-10px" @click="getList">查询</el-button>
      </div>
    </layout-item>
    <layout-main v-loading="loading" :scroll="false">
      <div class="flex h-full px-10px bg-white">
        <el-scrollbar class="w-280px flex-shrink-0">
          <div class="my-10px">
            <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="current && current._id === item._id ? 'primary':''"
                  :timestamp="item.date" placement="top">
                  <el-card class="mr-10px cursor-pointer" @click="current = item">
                    <div>{{ item.orderType }}</div>
                    <div>{{ item.deptName }} | {{ item.doctorName }}</div>
                    <div>{{ item.drugStoreName }}</div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-scrollbar>
        <div class="h-full flex-grow border-l border-gray-200 ml-10px">
          <illness-summary v-if="current" :rx="rx" :order="current">
            <template #footer>
              <div class="text-center py-12px bg-white relative z-1" common-shadow--r>
                <el-button plain class="w-100px" type="primary" @click="viewChatHistory()">聊天记录</el-button>
              </div>
            </template>
          </illness-summary>
        </div>
      </div>
    </layout-main>
  </my-layout>
  <chat-history-drawer :orderId="current ? current.orderId:''" :doctorCode="current ? current.doctorCode:''"
    :visible="chatVisible" @close="chatVisible = 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 MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import illnessSummary from "@/components/illness-summary/illness-summary.vue";
import chatHistoryDrawer from "@/components/chat-history-drawer/chat-history-drawer.vue";
const props = defineProps({
  patient: {
    type: Object,
    default: () => ({})
  }
});

const orderTypes = ref([
  { label: '全部类型', value: '' },
  { label: '在线复诊', value: 'im' },
  { label: '在线续方', value: 'pres' },
]);
const orderType = ref('');
const dates = ref([]);
const list = ref([]);
const current = ref(null);
const loading = ref(false);
const rx = ref(null);
const chatVisible = ref(false);

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)),
    };
  });
});

async function getList() {
  if (props.patient && props.patient.patientId) {
    loading.value = true
    const query = { patientId: props.patient.patientId,orderStatus:'finished' };
    if (orderType.value) {
      query.isPres = orderType.value === 'pres';
    }
    if (dates.value && dates.value.length) {
      query.startDate = dates.value[0];
      query.endDate = dates.value[1];
    }
    const { data, success, message } = await useHlw({ type: 'getPatientOrderList', ...query });
    list.value = data && Array.isArray(data.list) ? data.list.map(i => ({
      ...i,
      date: dayjs(i.createTime).format('MM-DD HH:mm'),
      orderType: i.preOrderId ? '在线续方' : '在线复诊',
    })) : [];
    if (!success) {
      ElMessage.error(message || '获取数据失败，请稍后重试！')
    }
    loading.value = false
    current.value = list.value.find(i => current.value && i._id === current.value._id) || list.value[0] || null;
  } else {
    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 = [];
  }
}

function viewChatHistory() {
  chatVisible.value = true;
}

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

watch(current, val => {
  getRx()
})

</script>