<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { getConditioningRecordDetailMethod, voidConditioningSchemeMethod } from '@/request/api/care.api';
import type { ConditioningRecordListModel, ConditioningRecordListQuery, SystemCwModel } from '@/model/care.model';
import CareProcess from '@/service/CareProgress.vue';
import {  notification } from 'ant-design-vue';
import VxeUI from 'vxe-table';
const model = shallowRef<ConditioningRecordListQuery>();
const props = defineProps<{
  data: ConditioningRecordListModel;
}>();
const isVoided = ref(true);
const emit = defineEmits<{
  (e: 'submit', data: SystemCwModel): void;
  (e: 'voidSubmit', data: SystemCwModel): void;
}>();
let tableData = ref<any>({});
async function getRecordDetail() {
  try {
    const res: any = await getConditioningRecordDetailMethod(props.data);
    if (res) {
      tableData.value = res;
    }
  } catch (error) {
    notification.error({ message: '获取数据失败' });
  }
}
const isShowDelivery = ref<boolean>(false);
watch(tableData, (newValue, oldValue) => {
  if (newValue.items.length > 0) {
    isShowDelivery.value = newValue.items.some((item: any) => {
      return item.conditioningProgramDetail?.isDelivery === 'Y';
    });
  }
});
onMounted(async () => {
  await getRecordDetail();
});

// 转方案
function handleChangePlan() {
  tableData.value.btnType = '转方案';
  emit('submit', tableData.value as SystemCwModel);
  VxeUI.modal.close('servicePackageDetail-modal');
}

// 查看记录
function handleViewRecord(model?: ConditioningRecordListModel) {
  VxeUI.modal.open({
    title: model?.id ? `调养过程` : `新增调养过程`,
    width: window.innerWidth,
    height: window.innerHeight,
    fullscreen: true,
    position: {
      top: Math.min(100, window.innerHeight * 0.1),
    },
    escClosable: true,
    destroyOnClose: true,
    id: `plan-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(CareProcess, <any>{
          data: model,
          onSubmit(data: ConditioningRecordListModel) {
            VxeUI.modal.close(`plan-modal`);
          },
        });
      },
    },
  });
}
const visible = ref<boolean>(false);
const setVisible = (value: boolean): void => {
  visible.value = value;
};
// 作废
function handleVoid() {
  voidConditioningSchemeMethod(Number(props.data.id)).then(async (res) => {
    notification.success({
      message: '作废成功',
      description: '',
    });
    // 作废之后刷新详情列表
    await getRecordDetail();
    isVoided.value = false;
    emit('voidSubmit', tableData.value as SystemCwModel);
  });
}

const progressTextMap: Record<string, string> = {
  '0': '待付款',
  '1': '已作废',
  '2': '用户取消',
  '3': '未开始',
  '4': '调理中',
  '5': '已完结',
  '6': '待收货',
};

const progressText = computed(() => {
  return progressTextMap[tableData.value?.progress] || '';
});
// 添加计算数量的函数
function calculateCount(row: any) {
  const pricingType = row.conditioningProgramDetail.pricingType;
  const period = Number(row.days) || 0;
  const frequency = Number(row.frequencyMeasure) || 0;
  const maxCount = row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.max;
  const acCount = (row.acuMeridianNames?.length ?? 0) + (row.acuPointNames?.length ?? 0);
  if (pricingType === '1') {
    // 按穴位计价
    const frequencyType = Number(row.frequencyType) || 0;
    row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
    if (acCount > maxCount) {
      if (row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.priceType === 0) {
        // 单价
        if (acCount > 0) {
          let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[1].price * acCount;
          row.unitPrice = unitPrice;
          row.totalPrice = Math.ceil((period / frequencyType) * frequency) * unitPrice;
        } else {
          row.unitPrice = '-';
          row.totalPrice = 0;
        }
      } else if (row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.priceType === 1) {
        // 一口价
        let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[1].price;
        row.unitPrice = unitPrice;
        row.totalPrice = row.conditioningProgramDetail.cpDynamicPricingRule[1].price * row.totalMeasure;
      }
    } else {
      if (row.conditioningProgramDetail.cpDynamicPricingRule?.length > 0) {
        if (row.conditioningProgramDetail.cpDynamicPricingRule?.[0]?.priceType === 0) {
          // 单价
          if (acCount > 0) {
            let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[0].price * acCount;
            row.unitPrice = unitPrice;
            row.totalPrice = Math.ceil((period / frequencyType) * frequency) * unitPrice;
          } else {
            row.unitPrice = '-';
            row.totalPrice = 0;
          }
        } else if (row.conditioningProgramDetail.cpDynamicPricingRule?.[0]?.priceType === 1) {
          // 一口价
          let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[0].price;
          row.unitPrice = unitPrice;
          row.totalPrice = row.conditioningProgramDetail.cpDynamicPricingRule[0].price * row.totalMeasure;
        }
      }
    }
  }
}
watch(
  () => tableData?.value?.items,
  (newData) => {
    if (!newData) return;
    newData.forEach((row: any) => {
      if (row?.days || row?.frequencyType || row?.frequencyMeasure) {
        calculateCount(row);
      }
    });
  },
  { deep: true }
);
</script>

<template>
  <div class="service-package">
    <h2 class="title">{{ tableData?.name || tableData?.conditioningWrapName }}</h2>
    <!-- 顶部信息 -->
    <div class="header">
      <span class="status" v-if="tableData?.progress">{{ progressText }}</span>
      <div>
        <!-- 调养记录详情 -->
        <div v-if="props.data.types === 'record'" style="line-height: 30px">
          <span v-if="tableData?.healthAnalysisReport?.willillStateName" class="mr-8">欲病状态：{{ tableData?.healthAnalysisReport?.willillStateName }}</span>
          <span v-if="tableData?.healthAnalysisReport?.willillDegreeName" class="mr-8">欲病程度：{{ tableData?.healthAnalysisReport?.willillDegreeName }}</span>
          <span v-if="tableData?.healthAnalysisReport?.willillSocialName" class="mr-8">欲病类型：{{ tableData?.healthAnalysisReport?.willillSocialName }}</span>
          <span v-if="tableData?.healthAnalysisReport?.willillFunctionName" class="mr-8">欲病表现：{{ tableData?.healthAnalysisReport?.willillFunctionName }}</span>
          <span v-if="tableData?.healthAnalysisReport?.constitutionGroupName" class="mr-8">体质：{{ tableData?.healthAnalysisReport?.constitutionGroupName }}</span>
          <span v-if="tableData?.diagnosis" class="mr-8">疾病名称：{{ tableData?.diagnosis }}</span>
          <span v-if="tableData?.symptom" class="mr-8">证型：{{ tableData?.symptom }}</span>
          <span v-if="tableData?.createBy" class="mr-8">开具医生：{{ tableData?.createBy }}</span>
          <span v-if="tableData?.createTime" class="mr-8">开具时间：{{ tableData?.createTime }}</span>
          <span v-if="tableData?.estimatedEndDate">调养周期：{{ tableData?.estimatedStartDate }} ~ {{ tableData?.estimatedEndDate }}</span>
        </div>
        <div v-else>
          <div class="flex mb-2" style="align-items: center">
            <!-- 机构名称 -->
            <div class="mr-10" v-if="props.data?.types === 'institution'" style="display: flex; align-items: center; margin-bottom: 0">
              <span style="white-space: nowrap; margin-right: 8px">机构名称：</span>
              <span>{{ tableData?.institutionName }}</span>
            </div>
            <!-- 服务形象照 -->
            <div class="flex" v-if="props.data?.types === 'institution' && tableData?.photo" style="align-items: center; margin-bottom: 0">
              <div class="w-20" style="white-space: nowrap; margin-right: 8px">服务形象照：</div>
              <a-image
                :width="100"
                :height="100"
                :preview="{
                  visible,
                  onVisibleChange: setVisible,
                }"
                :src="tableData?.photo"
              />
            </div>
          </div>

          <div style="margin-bottom: 16px">
            <div class="mb-3">适用情况</div>
            <div class="flex items-center mb-3" v-if="tableData?.conditioningWrapPatientMatchRule?.sex || tableData?.conditioningWrapPatientMatchRule?.age">
              <span class="w-20">使用限制</span>
              <div class="mr-10" v-if="tableData?.conditioningWrapPatientMatchRule?.sex">
                <span>性别：{{ tableData?.conditioningWrapPatientMatchRule?.sex }}</span>
              </div>
              <div v-if="tableData?.conditioningWrapPatientMatchRule?.age">
                <span>年龄：{{ tableData?.conditioningWrapPatientMatchRule?.age }}</span>
              </div>
            </div>
            <div
              class="flex items-center"
              v-if="
                tableData?.conditioningWrapPatientMatchRule?.diagnoseDiseaseNames?.length > 0 ||
                tableData?.conditioningWrapPatientMatchRule?.diagnoseSyndromeNames?.length > 0 ||
                tableData?.conditioningWrapPatientMatchRule?.constitutionGroupNames?.length > 0 ||
                tableData?.conditioningWrapPatientMatchRule?.willillStateNames?.length > 0
              "
            >
              <span class="w-20">适用</span>
              <div class="mr-10 flex items-center" v-if="tableData?.conditioningWrapPatientMatchRule?.diagnoseDiseaseNames?.length > 0">
                <span>专病：</span>
                <span>{{ tableData?.conditioningWrapPatientMatchRule?.diagnoseDiseaseNames?.join(',') }}</span>
              </div>
              <div class="mr-10 flex items-center" v-if="tableData?.conditioningWrapPatientMatchRule?.diagnoseSyndromeNames?.length > 0">
                <span>证型：</span>
                <span>{{ tableData?.conditioningWrapPatientMatchRule?.diagnoseSyndromeNames?.join(',') }}</span>
              </div>

              <div class="flex items-center mr-10" v-if="tableData?.conditioningWrapPatientMatchRule?.constitutionGroupNames?.length > 0">
                <span>体质：</span>
                <span>{{ tableData?.conditioningWrapPatientMatchRule?.constitutionGroupNames?.join(',') }}</span>
              </div>

              <div v-if="tableData?.conditioningWrapPatientMatchRule?.willillStateNames?.length > 0">
                <span>欲病状态：</span>
                <span>{{ tableData?.conditioningWrapPatientMatchRule?.willillStateNames?.join(',') }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- end -->
      </div>
    </div>

    <!-- 表格和作废字样包裹层 -->
    <div class="table-wrapper">
      <div v-if="tableData.progress === '1'" class="voided-stamp">作废</div>
      <vxe-table :data="tableData?.items" border>
        <vxe-column field="conditioningProgramDetail.name" title="项目名称" align="center" />
        <vxe-column field="days" title="周期" align="center" :disabled="true" />
        <vxe-column field="frequencyType" title="频率" width="auto">
          <template #default="{ row }">
            <div v-if="row.frequencyType === '不限'">不限</div>
            <div style="display: flex; align-items: center" v-else>
              <span>每</span>
              <a-input v-model:value="row.frequencyType" style="width: 60px" @change="() => calculateCount(row)" :disabled="true" />
              <span>天</span>
              <a-input v-model:value="row.frequencyMeasure" style="width: 60px" @change="() => calculateCount(row)" :disabled="true" />
              <span>{{ row.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit || '次' }}</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="conditioningProgramDetail.conditioningProgramType" title="方案类型" align="center" />
        <vxe-column field="totalMeasure" title="数量" align="center" />
        <vxe-column field="conditioningProgramDetail.cpFixedPricingRule.pricingUnit" title="单位" align="center">
          <template #default="{ row }">
            {{ row.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit ? row.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit : '次' }}
          </template>
        </vxe-column>
        <vxe-column field="conditioningProgramDetail.cpFixedPricingRule.unitPrice" title="单价（元）" align="center">
          <template #default="{ row }">
            {{ row.conditioningProgramDetail?.pricingType === '0' ? row.conditioningProgramDetail?.cpFixedPricingRule?.unitPrice : row.unitPrice  }}
          </template>
        </vxe-column>
        <vxe-column field="totalPrice" title="总价（元）" align="center" />
        <vxe-column field="conditioningProgramDetail.medicineNames" title="组成" align="center" />
        <vxe-column field="acuPointNames" title="穴位/经络/部位" align="center" />
        <vxe-column field="remark" title="说明" align="center" />
      </vxe-table>
    </div>

    <!-- 合计 -->
    <div class="total-row">
      合计：<b>{{ tableData?.price || tableData?.cost || 0 }}元</b>
    </div>

    <!-- 配送信息 -->
    <div class="delivery" v-if="isShowDelivery && props.data.types === 'record' && tableData.provinceName">
      <span style="color: #52c41a; font-size: 20px">✔</span>
      <span
        >配送 地址：{{ tableData.provinceName }} {{ tableData.cityName }} {{ tableData.areaName }} {{ tableData.detailAddress }} {{ tableData.patientName }}
        {{ tableData.phone }}</span
      >
    </div>
    <!-- 按钮区，作废后隐藏 -->
    <div class="footer-btns" v-if="props.data.types === 'record'">
      <a-button type="primary" style="margin-right: 24px" @click="handleChangePlan" v-if="props.data.status === '1'">转方案</a-button>
      <a-button @click="handleVoid" v-if="tableData.showRepealButton">作废</a-button>
      <a-button type="primary" style="margin-left: 24px" @click="handleViewRecord(props.data)">查看记录</a-button>
    </div>
  </div>
</template>

<style scoped>
.table-wrapper {
  position: relative;
}
.voided-stamp {
  position: absolute;
  left: 50%;
  top: 50px;
  transform: translateX(-50%) rotate(-15deg);
  color: #ff8f8d;
  font-size: 40px;
  font-weight: bold;
  letter-spacing: 16px;
  opacity: 1;
  pointer-events: none;
  z-index: 10;
  user-select: none;
  border-radius: 10px;
  border: 5px solid #ff8f8d;
}
.service-package {
  padding: 0 10px;
  background: #fff;
}
.header {
  /* display: flex;
  align-items: center; */
  gap: 24px;
  margin-bottom: 12px;
}
.status {
  background: #ff9800;
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  margin-right: 12px;
  font-weight: bold;
  width: 100px;
  text-align: center;
  height: 40px;
  line-height: 40px;
}
.title {
  text-align: center;
  margin: 16px 0 24px 0;
  font-size: 22px;
  font-weight: bold;
}
.total-row {
  display: flex;
  justify-content: flex-end;
  font-size: 18px;
  font-weight: bold;
  margin: 12px 0 24px 0;
}
.delivery {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
  font-size: 16px;
  gap: 8px;
}
.footer-btns {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
