<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { getConditioningRecordDetailMethod } from '@/request/api/care.api';
import type { ConditioningRecordListModel, SystemCwModel } from '@/model/care.model';
import VxeUI from 'vxe-table';
import SingleItemDetail from '@/service/SingleItemDetail.vue';
const props = defineProps<{
  data: ConditioningRecordListModel;
}>();
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) {
    console.error('获取数据失败', error);
  }
}
const isShowDelivery = ref<boolean>(false);
watch(tableData, (newValue) => {
  if (newValue.items?.length > 0) {
    isShowDelivery.value = newValue.items.some((item: any) => {
      return item.conditioningProgramDetail?.isDelivery === 'Y';
    });
  }
});
onMounted(() => {
  getRecordDetail();
});


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

const progressText = computed(() => {
  return progressTextMap[tableData.value?.progress] || '';
});

// 订单状态映射
const orderStatusTextMap: Record<string, string> = {
  '1': '交易关闭（已作废）',
  '0': '待付款',
  '2': '交易关闭（用户取消）',
  '6': '已付款',
  '345': '交易成功',
};

const orderStatusText = computed(() => {
  return orderStatusTextMap[tableData.value?.orderStatus] || '';
});

// 收货信息组合字段
const deliveryInfo = computed(() => {
  const parts = [
    tableData.value?.provinceName,
    tableData.value?.cityName,
    tableData.value?.areaName,
    tableData.value?.detailAddress,
    ' ',
    tableData.value?.liaison,
    ' ',
    tableData.value?.phone
  ].filter(Boolean);
  return parts.join(' ');
});

// 点击项目名称查看商品详情
function handleItemNameClick(row: any) {
  VxeUI.modal.open({
    title: '商品详情',
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: 'item-detail-modal',
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(SingleItemDetail, {
          data: {
            ...row,
          },
        } as any);
      },
    },
  });
}
// 添加计算数量的函数
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="progressText">{{ progressText }}</span>
      <div>
        <!-- 调养记录详情 -->
        <div 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>
    </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">
          <template #default="{ row }">
            <a style="color: #1890ff; cursor: pointer;" @click="handleItemNameClick(row)">
              {{ row.conditioningProgramDetail?.name }}
            </a>
          </template>
        </vxe-column>
        <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="info-section">
      <h3 class="info-title">订单信息</h3>
      <div class="info-content-wrapper">
        <div class="info-content">
          <div class="info-item" v-if="tableData?.orderNo">
            <span class="info-label">订单编号：</span>
            <span class="info-value">{{ tableData?.orderNo }}</span>
          </div>
          <div class="info-item" v-if="tableData?.createTime">
            <span class="info-label">创建时间：</span>
            <span class="info-value">{{ tableData?.createTime }}</span>
          </div>
          <div class="info-row">
            <div class="info-item" v-if="orderStatusText">
              <span class="info-label">订单状态：</span>
              <span class="info-value">{{ orderStatusText }}</span>
            </div>
            <div class="info-item" v-if="tableData?.payTime">
              <span class="info-label">付款时间：</span>
              <span class="info-value">{{ tableData?.payTime }}</span>
            </div>
            <div class="info-item" v-if="tableData?.cost">
              <span class="info-label">支付金额：</span>
              <span class="info-value">¥{{ tableData?.cost }}</span>
            </div>
            <div class="info-item" v-if="tableData?.payType">
              <span class="info-label">付款方式：</span>
              <span class="info-value">{{ tableData?.payType === '0' ? '微信支付' : '' }}</span>
            </div>
            <div class="info-item" v-if="tableData?.payTransactionNo">
              <span class="info-label">微信交易号：</span>
              <span class="info-value">{{ tableData?.payTransactionNo }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item mr-20" v-if="tableData?.finishTime">
              <span class="info-label">成交时间：</span>
              <span class="info-value">{{ tableData?.finishTime }}</span>
            </div>
            <div class="info-item" v-if="tableData?.cancelTime">
              <span class="info-label">关闭时间：</span>
              <span class="info-value">{{ tableData?.cancelTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 用户信息 -->
    <div class="info-section" v-if="tableData?.patientName || (isShowDelivery && tableData.provinceName)">
      <h3 class="info-title">用户信息</h3>
      <div class="info-content-wrapper">
        <div class="info-content">
          <div class="info-item" v-if="tableData?.patientName">
            <span class="info-label">用户姓名：</span>
            <span class="info-value">{{ tableData?.patientName }}</span>
          </div>
          <div class="info-item" v-if="isShowDelivery && tableData.provinceName">
            <span class="info-label">收货信息：</span>
            <span class="info-value">{{ deliveryInfo }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分账信息 -->
    <div class="info-section"
      v-if="tableData?.profitSharing !== null || tableData?.profitSharingAmount !== null">
      <h3 class="info-title">分账信息</h3>
      <div class="info-content-wrapper">
        <div class="info-content-profit-sharing">
          <div class="info-item" v-if="tableData?.profitSharing!==null">
            <span class="info-label">分账比例：</span>
            <span class="info-value">{{ tableData?.profitSharing }}</span>
          </div>
          <div class="info-item" v-if="tableData?.profitSharingAmount !== null">
            <span class="info-label">分账金额：</span>
            <span class="info-value">
              {{ tableData?.profitSharingAmount }}元
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.table-wrapper {
  position: relative;
}
.info-content-profit-sharing{
  display: flex;
  gap: 50px;
}
.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;
}

.info-section {
  margin-top: 24px;
  margin-bottom: 24px;
  background: #fff;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.info-content-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  line-height: 24px;
}

.info-label {
  color: #666;
  margin-right: 8px;
  white-space: nowrap;
  /* min-width: 100px; */
}

.info-value {
  color: #333;
  font-weight: 400;
}

.split-count {
  display: inline-block;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  background: #ffc107;
  color: #333;
  border-radius: 2px;
  margin-left: 6px;
  font-size: 12px;
  font-weight: 600;
  vertical-align: middle;
}
</style>
