<script setup lang="ts">
import { ref, defineAsyncComponent, watch } from 'vue';
import { getConditioningProcessMethod } from '@/request/api/care.api';
import type { ConditioningRecordListModel, OpenConditioningSchemeModel } from '@/model/care.model';
import { useWatcher } from 'alova/client';
import { patientMethod } from '@/request/api/patient.api';
import { VxeUI } from 'vxe-pc-ui';
import type { HealthReportSymptomItemVo } from '@/model/health-report.model';
import type { LineSeriesOption } from 'echarts/charts';
import { LineChart } from 'echarts/charts';

import type { GridComponentOption, LegendComponentOption, MarkLineComponentOption, TitleComponentOption, TooltipComponentOption } from 'echarts/components';
import { GridComponent, LegendComponent, MarkLineComponent, TitleComponent, TooltipComponent, VisualMapComponent } from 'echarts/components';

import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';

use([CanvasRenderer, LineChart, MarkLineComponent, GridComponent, VisualMapComponent, TitleComponent, TooltipComponent, LegendComponent]);

const type=ref('careProgress')
type FollowModel = Partial<ConditioningRecordListModel>;
const props = defineProps<{
  data: FollowModel;
  patientId?: string;
}>();

// 患者基本信息
const { data: patient } = useWatcher(() => patientMethod(props.data.patientId!), [() => props.data.patientId], {
  initialData: { ...props.data },
  immediate: true,
  middleware: (_, next) => {
    if (props.data.patientId) next();
  },
});


const careProcessList = ref<OpenConditioningSchemeModel>();
async function getCareProgress() {
  const res = await getConditioningProcessMethod(Number(props.data.id));
  careProcessList.value = res as OpenConditioningSchemeModel;
  // console.log('调养效果数据:', careProcessList.value?.patientConditioningScores);
}
onMounted(async () => {
  // console.log(props.data, 'props.data');
  if (props.data.id) {
    await getCareProgress();
  }
});
function openIndicatorRecordsPreview() {
  // console.log(patient.value, 'patient9999');
  const component = defineAsyncComponent(() => import('@/components/RecordsIndicatorPreview.vue'));
  const id = `modal:record-indicator:preview`;
  const onDestroy = () => {
    VxeUI.modal.close(id);
  };
  onDestroy();
  VxeUI.modal.open({
    id,
    remember: true,
    showMaximize: true,
    mask: false,
    lockView: false,
    padding: false,
    resize: true,
    width: Math.floor(window.innerWidth * 0.5),
    height: Math.floor(window.innerHeight * 0.5),
    escClosable: true,
    maskClosable: true,
    title: `指标信息更新记录`,
    slots: {
      default() {
        // console.log(patient.value, 'patient9999');
        return h(component, {
          patient: patient.value,
          onDestroy,
        });
      },
    },
  });
}

const panels = shallowReactive([
  {
    id: 'patient-health-records',
    title: '健康分析记录',
    component: defineAsyncComponent(() => import('@/widgets/PatientHealthRecordsWidget.vue')),
  },
]);

const activePanel = ref(panels[0].id);

const option = ref({
  title: { text: '评分', left: 'left', top: 0, textStyle: { fontSize: 14 } },
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: [] as string[],
    boundaryGap: false,
  },
  yAxis: {
    type: 'value',
    min: 20,
    max: 100,
  },
  series: [
    {
      type: 'line',
      data: [] as number[],
      smooth: true,
      symbol: 'circle',
      symbolSize: 12,
      itemStyle: { color: '#ff9900', borderColor: '#fff', borderWidth: 2 },
      lineStyle: { color: '#bfa' },
      label: { show: false },
      markPoint: {
        symbol: 'circle',
        symbolSize: 16,
        label: {
          show: true,
          color: '#fff',
          fontWeight: 'bold',
        },
        itemStyle: {
          color: '#ff4d4f',
        },
        data: [] as Array<{
          coord: [string, number];
          value: number;
          name: string;
          label: { show: boolean; formatter: string };
        }>,
      },
    },
  ],
  grid: { left: 40, right: 20, top: 40, bottom: 30 },
});

// 监听数据变化更新图表
watch(() => careProcessList.value?.patientConditioningScores, (newScores) => {
  if (newScores && newScores.length > 0) {
    option.value.xAxis.data = newScores.map(item => item.time4);
    option.value.series[0].data = newScores.map(item => item.score);
    option.value.series[0].markPoint.data = newScores.map((item) => ({
      coord: [item.time4, item.score],
      value: item.score,
      name: item.time4,
      label: { show: true, formatter: item.time4 },
    }));
  }
}, { immediate: true });

type SymptomItemVo = Record<
  `symptom-${HealthReportSymptomItemVo['id']}`,
  HealthReportSymptomItemVo & {
    trend: -1 | 0 | 1;
  }
>;
interface Model extends SymptomItemVo {
  id: string;
  duration?: string;
  influence?: string;
  healthAnalysisReportId?: number;
  tongueUpPictures?: string;
  tongueDownPictures?: string;
  facePictures?: string;
}
// 查看健康评估
function open(row: Model) {
  // console.log(row, '查看健康评估');
  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.healthAnalysisReportId.toString(),
          onDestroy,
        });
      },
    },
  });
}
</script>

<template>
  <div class="care-progress-card">
    <div class="header" v-if="careProcessList">
      <span class="title">{{
        careProcessList?.progress === '0'
          ? '待付款'
          : careProcessList?.progress === '1'
            ? '已作废'
            : careProcessList?.progress === '2'
              ? '用户取消'
              : careProcessList?.progress === '3'
                ? '未开始'
                : careProcessList.progress === '4'
                  ? '调理中'
                  : careProcessList?.progress === '5'
                    ? '已完结'
                    : ''
      }}</span>
      <span
        >姓名：<b>{{ careProcessList?.patientName }}</b></span
      >
      <span>疾病名称：{{ careProcessList?.diagnosis }}</span>
      <span>证型：{{ careProcessList?.symptom }}</span>
      <span>开具医生：{{ careProcessList?.createBy }}</span>
      <span>调养周期：{{ careProcessList?.estimatedStartDate }} ~ {{ careProcessList?.estimatedEndDate }}</span>
    </div>
    <div v-if="careProcessList?.isDelivery === 'Y'" class="delivery-info">
      <a-checkbox checked disabled style="color: #52c41a; margin-right: 8px" />
      <span>配送</span>
      <span>地址：{{ careProcessList?.provinceName }}{{ careProcessList?.cityName }}{{ careProcessList?.areaName }}{{ careProcessList?.detailAddress }}</span>
      <span style="margin-left: 16px">电话：{{ careProcessList?.phone }}</span>
    </div>
    <!-- 线上项目 -->
    <div v-for="item in careProcessList?.items" :key="item.id">
      <div class="project-section" v-if="item.patientConditioningOfflines">
        <div class="project-title">
          <span style="font-size: 14px; font-weight: bold">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span class="stat">数量：{{ item.totalMeasure }}</span>
          <span class="stat">还剩：{{ item?.remainCount }}</span>
          <span class="stat">已核销：{{ item?.finishCount }}</span>
        </div>
        <vxe-table :data="item?.patientConditioningOfflines" border>
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="operateTime" title="操作时间" />
          <vxe-column field="operateBy" title="操作人" />
          <vxe-column field="feedback" title="上次治疗反馈" />
          <vxe-column field="acuPointNames" title="穴位" />
        </vxe-table>
        <div class="mt-3">
          <div class="mb-1">
            预定频率：每 {{ item.frequencyType }}天 {{ item.frequencyMeasure }}
            {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit }}
          </div>
          <div>操作指南：{{ item.remark }}</div>
        </div>
      </div>
      <!-- 线上 -->
      <div class="yuanqi-tea" v-if="item?.patientConditioningOnlines">
        <div class="mb-2">
          <span class="mr-10">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span>数量：{{ item.totalMeasure }}</span>
        </div>
        <div class="mb-1">
          预定频率：每 {{ item.frequencyType }}天 {{ item.frequencyMeasure }}
          {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit }}
        </div>
        <div>操作指南：{{ item.remark }}</div>
      </div>
      <!-- 健康评估 -->
      <div  class="project-section mb-3" v-if="item?.healthAnalysisReports">
        <div class="project-title">
          <span style="font-size: 14px; font-weight: bold">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span class="stat">数量：{{ item?.totalMeasure }}</span>
          <span class="stat">还剩：{{ item?.remainCount }}</span>
          <span class="stat">已核销：{{ item?.finishCount }}</span>
        </div>
        <vxe-table :data="item?.healthAnalysisReports" border>
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="analysisEndTime" title="操作时间" />
          <vxe-column title="评估记录">
            <template #default="{ row }">
              <a-button type="link" @click="open(row)">查看</a-button>
            </template>
          </vxe-column>
        </vxe-table>
        <div class="mt-3">
          <div class="mb-1">
          预定频率：每 {{ item?.frequencyType }}天 {{ item?.frequencyMeasure }}
          {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit }}
        </div>
        <div>操作指南：{{ item?.remark }}</div>
        </div>
      </div>
   
      <!-- 健康记录 -->
      <a-tabs class="panel-wrapper" v-model:activeKey="activePanel" v-if="item?.healthAnalysisReports && item?.healthAnalysisReports.length > 0">
       
        <a-tab-pane v-for="panel in panels" :key="panel.id" class="panel-pane">
          <component :is="panel.component" :patient="patient" :healthAnalysisReports="item?.healthAnalysisReports" :type="type"></component>
        </a-tab-pane>
        <template #renderTabBar>
        <a-radio-group v-model:value="activePanel">
          <a-radio-button v-for="panel in panels" :key="panel.id" :value="panel.id">
            {{ panel.title }}
          </a-radio-button>
        </a-radio-group>
      </template>
      </a-tabs>
     
      </div>
       <!-- 调养效果 -->
       <div style="margin: 20px 0 10px 0;" v-if="careProcessList?.patientConditioningScores && careProcessList.patientConditioningScores.length > 0">
        <h3>调养效果</h3>
        <!-- todo 折线图 -->
        <v-chart :option="option" style="width: 350px; height: 200px" />
      </div>
       <!-- 指标 -->
       <div v-if="careProcessList?.patientQuotaGroups && careProcessList?.patientQuotaGroups.length > 0">
        <label>生理指标</label>
        <a-button type="link" @click="openIndicatorRecordsPreview">更新记录</a-button>
      </div>
  </div>
</template>

<style scoped>
.panel-pane {
  height: 600px !important;
}
.panel-wrapper {
  :deep(.ant-tabs-content-holder) {
    padding-top: 12px;
    height: 600px;
    :deep(.ant-tabs-content) {
    height: 100%;
  }
  }
 
}
.care-progress-card {
  background: #fff;
  border-radius: 8px;
  padding: 18px 24px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin: 0 0 24px 0;
}
.header {
  display: flex;
  flex-wrap: wrap;
  gap: 18px;
  align-items: center;
  font-size: 15px;
  margin-bottom: 8px;
}
.title {
  background: #ffb300;
  color: #fff;
  border-radius: 4px;
  padding: 2px 10px;
  font-weight: bold;
}
.delivery-info {
  display: flex;
  align-items: center;
  border-radius: 4px;
  padding: 6px 12px;
  margin-bottom: 12px;
  font-size: 14px;
}
.project-section {
  margin-top: 18px;
  border: 1px solid lightgray;
  /* border-radius: 6px; */
  padding: 6px 30px 6px 6px;
}
.project-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}
.stat {
  display: inline-block;
  color: #333;
  border-radius: 8px;
  padding: 2px 10px;
  margin-left: 8px;
  font-size: 14px;
}
.custom-table .table-header {
  background: #e3eafc !important;
  color: #333 !important;
  font-weight: bold;
  font-size: 15px;
}
.project-footer {
  margin-top: 8px;
  font-size: 14px;
  color: #333;
}
.yuanqi-tea {
  margin-top: 18px;
  border: 1px solid lightgray;
  /* border-radius: 6px; */
  padding: 6px 30px 6px 6px;
}
</style>
