<script setup lang="ts">
import { h } from 'vue';

import { ArrowDownOutlined, ArrowUpOutlined, FileTextOutlined } from '@ant-design/icons-vue';
import { fromHealthIndicator, fromHealthReport, type HealthIndicatorItemVO, type HealthIndicatorVO, type HealthReportDTO, type HealthReportVO } from '@/model/health-report.model';

import { usePagination } from 'alova/client';
import { getPatientHealthRecordsMethod } from '@/request/api/report.api';
import type { VxeGridInstance, VxeGridListeners, VxeGridProps } from 'vxe-table';
import type { HealthReportSymptomItemVo } from '@/model/health-report.model';
import { VxeUI } from 'vxe-pc-ui';

const props = defineProps<{ patient: { id: string }; healthAnalysisReports: any; type: string }>();

type SymptomItemVo = Record<
  `symptom-${HealthReportSymptomItemVo['id']}`,
  HealthReportSymptomItemVo & {
    trend: -1 | 0 | 1;
  }
>;

interface Model extends SymptomItemVo {
  id: string;
  duration?: string;
  influence?: string;

  tongueUpPictures?: string;
  tongueDownPictures?: string;
  facePictures?: string;
}

const grid = ref<VxeGridInstance>();
const { loading, page, isLastPage } = usePagination((page, size) => getPatientHealthRecordsMethod(page, size, { patientId: props.patient.id }), {
  initialData: { total: 0, data: [] },
  initialPage: 1,
  initialPageSize: 100,
  append: true,
  watchingStates: [() => props.patient.id],
}).onSuccess(({ data: { data } }) => {
  let dataArr = reactive<HealthReportVO[]>([]);
  // console.log(props.type, 'props.type');
  if (props.type === 'careProgress') {
    const healthAnalysisReports = props.healthAnalysisReports.map(fromHealthReport);
    dataArr = healthAnalysisReports;
  } else {
    dataArr = data;
  }
  // console.log(dataArr, 'dataArr获取的data');
   // 新加的倒序
  dataArr = [...dataArr].reverse();
  const rows = gridOptions.data as Model[];
  const symptomColumns = gridOptions.columns?.find((column) => column.field === 'symptom')?.children ?? [];

  // 清空现有数据
  rows.length = 0;

  let lastRow: Partial<Model> = {};
  for (const values of dataArr) {
    const { analysis, symptom, ...record } = values;
    const items: SymptomItemVo = {};
    for (const item of symptom.items) {
      const field = `symptom-${item.id}` as keyof SymptomItemVo;
      if (!symptomColumns.find((column) => column.field === field))
        symptomColumns.push({
          field,
          title: item.name,
          align: 'center',
          resizable: true,
          slots: { default: `symptom` },
        });
      const lastValue = lastRow[field]?.value;
      const value = item.value;
      items[field] = {
        ...item,
        trend: lastValue ? (lastValue > value ? -1 : lastValue < value ? 1 : 0) : 0,
      };
    }
    const row = Object.assign(record, symptom, items, {
      tongueUpPictures: analysis.tongue.pictures[0],
      tongueDownPictures: analysis.tongue.pictures[1],
      facePictures: analysis.face.pictures[0],
    });
    rows.push(row);
    lastRow = row;
  }
  // 新加的倒序
  rows.reverse();

  grid.value?.loadColumn(gridOptions.columns!);
});
const gridOptions = reactive<VxeGridProps<Model>>({
  // @ts-ignore
  loading,
  height: 'auto',
  headerAlign: 'center',
  headerCellConfig: {
    padding: false,
    height: 28,
  },
  cellConfig: {
    height: 126,
  },
  columns: [
    { field: 'date', title: '日期', width: '150px', align: 'center', slots: { default: 'records' } },
    {
      title: '舌象',
      children: [
        { field: 'tongueUpPictures', title: '舌面', width: '126px', slots: { default: 'picture' } },
        { field: 'tongueDownPictures', title: '舌底', width: '126px', slots: { default: 'picture' } },
      ],
    },
    {
      title: '面象',
      children: [{ field: 'facePictures', title: '面部', width: '126px', slots: { default: 'picture' } }],
    },
    {
      field: 'symptom',
      title: '症状',
      children: [],
    },
    { field: 'duration', title: '持续时间' },
    { field: 'influence', title: '对生活的影响' },
  ],
  data: [],
  scrollY: {
    gt: 0,
  },
});
const gridEvents: VxeGridListeners = {
  scrollBoundary({ direction, isBottom }) {
    if (isBottom && direction === 'bottom' && !isLastPage.value) page.value++;
  },
};

function open(row: Model) {
  const component = defineAsyncComponent(() => import('@/components/ReportPreview.vue'));
  const id = `drawer:report:preview`;
  const onDestroy = () => {
    VxeUI.drawer.close(id);
  };
  onDestroy();
  VxeUI.drawer.open({
    id,
    mask: true,
    lockView: false,
    padding: false,
    width: window.innerWidth - 256,
    escClosable: true,
    maskClosable: true,
    title: `健康分析报告`,
    slots: {
      default() {
        return h(component, {
          reportId: row.id.toString(),
          onDestroy,
        });
      },
    },
  });
}
</script>

<template>
  <vxe-grid ref="grid" v-bind="gridOptions" v-on="gridEvents">
    <template #records="{ row, column }">
      <div style="font-size: 16px">{{ row[column.field] }}</div>
      <a-button class="mt-2" :icon="h(FileTextOutlined)" type="primary" size="small" :disabled="!row.id" @click="open(row)">健康分析报告</a-button>
    </template>
    <template #symptom="{ row, column }">
      <div style="transform: translateX(12px)">
        <span>{{ row[column.field]?.label }}</span>
        <div class="inline-block ml-1 size-24px">
          <a-button v-if="row[column.field]?.trend > 0" :icon="h(ArrowUpOutlined)" shape="circle" size="small" class="trend-up" />
          <a-button v-else-if="row[column.field]?.trend < 0" :icon="h(ArrowDownOutlined)" shape="circle" size="small" class="trend-down" />
        </div>
      </div>
    </template>
    <template #picture="{ row, column }">
      <a-image v-if="row[column.field]" class="w-full h-full" :src="row[column.field]" />
    </template>
  </vxe-grid>
</template>

<style scoped lang="scss">
.trend-up {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.trend-down {
  color: #87d068;
  border-color: #87d068;
}
</style>
