<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 RecordsIndicatorPreview from '@/components/RecordsIndicatorPreview.vue';
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>();
const showCareBox = ref<boolean>(false);
async function getCareProgress() {
  const res: any = await getConditioningProcessMethod(Number(props.data.id));
  careProcessList.value = res as OpenConditioningSchemeModel;
  if (res.provinceName || res.cityName || res.areaName || res.detailAddress || res.phone) {
    showCareBox.value = true;
  }
}
const isShowDelivery = ref<boolean>(false);
// 监听 displayTableData 的变化
watch(careProcessList, (newValue) => {
  if (newValue?.items) {
    isShowDelivery.value = newValue.items.some((item) => {
      return item.conditioningProgramDetail?.isDelivery === 'Y';
    });
  }
});
onMounted(async () => {
  if (props.data.id) {
    await getCareProgress();
  }
});
function openChatRecord(row: any) {
  console.log('row===聊天记录', row);
  const component = defineAsyncComponent(() => import('@/components/CurrentDayChatHistory.vue'));
  const id = `drawer:chat-record:preview`;
  const onClose = () => {
    VxeUI.drawer.close(id);
  };
  onClose();
  VxeUI.drawer.open({
    id,
    mask: true,
    lockView: false,
    padding: false,
    width: window.innerWidth - 256,
    escClosable: true,
    maskClosable: true,
    title: `聊天记录`,
    slots: {
      default() {
        return h(component, {
          row: row,
          onClose,
        });
      },
    },
  });
};
function openIndicatorRecordsPreview() {
  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() {
        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,
    axisLine: { show: false },
    axisTick: { show: false }, // 不显示横坐标刻度
    axisLabel: { show: false }, // 不显示横坐标刻度名字
  },
  yAxis: {
    type: 'value',
    min: 20,
    max: 100,
    interval: 20,
    axisLine: { show: false }, // 不显示Y轴线
    axisLabel: { color: '#7ec8bb' },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: '#e0e0e0',
      },
    },
  },
  series: [
    {
      type: 'line',
      data: [] as number[],
      smooth: true,
      symbol: 'circle',
      symbolSize: 12,
      itemStyle: {
        color: '#ffd700', // 黄色中心
        borderColor: '#ff8c00', // 橙色轮廓
        borderWidth: 2,
      },
      lineStyle: {
        color: '#b0c4de', // 浅蓝色线条
        width: 2,
      },
      label: {
        show: true,
        position: 'top',
        color: '#fff',
        backgroundColor: '#ff6b6b', // 红色标签背景
        borderRadius: 4,
        padding: [4, 8],
        formatter: function (params: any) {
          return params.name;
        },
      },
      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) {
  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,
        });
      },
    },
  });
}
const progressTextMap: Record<string, string> = {
  '0': '待付款',
  '1': '已作废',
  '2': '用户取消',
  '3': '未开始',
  '4': '调理中',
  '5': '已完结',
  '6': '待收货',
};
</script>

<template>
  <div class="care-progress-card">
    <div v-if="careProcessList">
      <div class="title-wrapper" v-if="careProcessList?.conditioningWrapName">{{ careProcessList?.conditioningWrapName }}</div>
      <div class="header">
        <span class="title" v-if="careProcessList?.progress">
          {{ progressTextMap[careProcessList?.progress] || '' }}
        </span>
        <span v-if="careProcessList?.patientName"
          >姓名：<span>{{ careProcessList?.patientName }}</span></span
        >
        <span v-if="careProcessList?.diagnosis">疾病名称：{{ careProcessList?.diagnosis }}</span>
        <span v-if="careProcessList?.symptom">证型：{{ careProcessList?.symptom }}</span>
        <span v-if="careProcessList?.createBy">开具医生：{{ careProcessList?.createBy }}</span>
        <span v-if="careProcessList?.estimatedStartDate && careProcessList?.estimatedEndDate"
          >调养周期：{{ careProcessList?.estimatedStartDate }} ~ {{ careProcessList?.estimatedEndDate }}</span
        >
      </div>
    </div>
    <div v-if="isShowDelivery && showCareBox" class="delivery-info" style="margin-left: 75px">
      <a-checkbox checked style="color: #52c41a; margin-right: 8px" />
      <span style="margin-right: 15px">配送</span>
      <span v-if="careProcessList?.provinceName || careProcessList?.cityName || careProcessList?.areaName || careProcessList?.detailAddress"
        >地址：{{ careProcessList?.provinceName }}{{ careProcessList?.cityName }}{{ careProcessList?.areaName }}{{ careProcessList?.detailAddress }}</span
      >
      <span style="margin-left: 16px" v-if="careProcessList?.phone">电话：{{ careProcessList?.phone }}</span>
    </div>
    <!-- 线上项目 -->
    <div v-for="item in careProcessList?.items" :key="item.id" class="project-card">
      <div class="project-section" v-if="item?.patientConditioningOfflines">
        <div class="project-title">
          <span style="font-size: 14px; font-weight: bold; color: black">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span class="stat">数量：{{ item.totalMeasure }}{{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">还剩：{{ item?.remainCount }}{{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">已核销：{{ item?.finishCount }}{{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</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?.convertUnit || '次' }}</div>
          <div v-if="item.remark">操作指南：{{ item.remark }}</div>
        </div>
      </div>
        <!-- 健康咨询 -->
        <div class="project-section mb-3 project-card" v-if="item?.consults">
        <div class="project-title">
          <span style="font-size: 14px; font-weight: bold; color: black">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span class="stat">数量：{{ item?.totalMeasure }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">还剩：{{ item?.remainCount }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">已核销：{{ item?.finishCount }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
        </div>
        <vxe-table :data="item?.consults" border>
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="startTime" title="操作时间" />
          <vxe-column field="items" title="聊天记录">
            <template #default="{ row }">
              <a-button type="link" @click="openChatRecord(row)">查看</a-button>
            </template>
          </vxe-column>
        </vxe-table>
        <div class="mt-3">
          <div class="mb-1">
            预定频率：
            <span v-if="item?.frequencyType === '不限'">不限</span>
            <span v-else>每{{ item?.frequencyType }}天{{ item?.frequencyMeasure }}{{ item?.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit || '次' }} </span>
          </div>
          <div v-if="item?.remark">操作指南：{{ item?.remark }}</div>
        </div>
      </div>
      <!-- 线上 -->
      <div class="yuanqi-tea" v-if="item?.patientConditioningOnlines">
        <div class="mb-2">
          <span class="mr-10" style="font-size: 14px; font-weight: bold; color: black">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span>数量：{{ item.totalMeasure }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
        </div>
        <div class="mb-1">预定频率：每{{ item.frequencyType }}天{{ item.frequencyMeasure }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit || '次' }}</div>
        <div v-if="item.remark">操作指南：{{ item.remark }}</div>
      </div>
      <!-- 健康评估 -->
      <div class="project-section mb-3 project-card" v-if="item?.healthAnalysisReports">
        <div class="project-title">
          <span style="font-size: 14px; font-weight: bold; color: black">◇ {{ item?.conditioningProgramDetail?.name }}</span>
          <span class="stat">数量：{{ item?.totalMeasure }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">还剩：{{ item?.remainCount }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</span>
          <span class="stat">已核销：{{ item?.finishCount }} {{ item?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit || '次' }}</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">
            预定频率：
            <span v-if="item?.frequencyType === '不限'">不限</span>
            <span v-else>每{{ item?.frequencyType }}天{{ item?.frequencyMeasure }}{{ item?.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit || '次' }} </span>
          </div>
          <div v-if="item?.remark">操作指南：{{ item?.remark }}</div>
        </div>
      </div>
    </div>
    <!-- 调养效果 -->
    <div class="care-box">
      <h3 style="color: black">调养效果</h3>
      <div class="care-box-content">
        <!-- 评分 折线图 -->
        <div class="chart-wrapper" v-if="careProcessList?.patientConditioningScores && careProcessList.patientConditioningScores.length > 0">
          <v-chart :option="option" style="width: 350px; height: 200px" />
        </div>
        <!-- 健康记录 -->
        <div class="health-records-card" v-if="careProcessList?.healthAnalysisReports && careProcessList?.healthAnalysisReports.length > 0">
          <a-tabs class="panel-wrapper" v-model:activeKey="activePanel">
            <a-tab-pane v-for="panel in panels" :key="panel.id" class="panel-pane">
              <div class="panel-title">记录</div>
              <component :is="panel.component" :patient="patient" :healthAnalysisReports="careProcessList?.healthAnalysisReports" :type="type"></component>
            </a-tab-pane>
          </a-tabs>
        </div>

        <!-- 指标 -->
        <div class="mt-3" v-if="careProcessList?.patientQuotaGroups && careProcessList?.patientQuotaGroups.length > 0">
          <b>指标</b>
          <!-- <a-button type="link" @click="openIndicatorRecordsPreview">查看指标记录</a-button>
            -->
          <RecordsIndicatorPreview :records="careProcessList?.patientQuotaGroups" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.care-box {
  margin: 20px 0 10px 0;
}
.care-box-content {
  border: 1px solid lightgray !important;
  padding: 10px;
}
.panel-pane {
  height: 600px !important;
  margin-bottom: 28px;
}
.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: 4px 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;
}
.project-card :deep(.vxe-table--header th) {
  background: #9abde4 !important;
  color: black !important;
}
.health-records-card :deep(.vxe-table--header th) {
  background: #f8f8f9 !important;
  color: unset !important;
}
.project-card :deep(.vxe-table--border .vxe-body--row > td),
.project-card :deep(.vxe-table--border .vxe-header--row > th) {
  border-color: #bfcbd9 !important;
  border-width: 2px !important;
}
.project-card :deep(.vxe-table--border) {
  border-color: #bfcbd9 !important;
}
:deep(.ant-tabs-nav) {
  position: unset;
  display: none;
}
.panel-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  color: black;
}
.title-wrapper {
  text-align: center;
  margin-bottom: 20px;
  font-weight: bold;
  font-size: 17px;
  color: black;
}
.chart-wrapper {
  width: 100%;
}
</style>
