<script setup lang="ts">
import { ref, computed, nextTick, h, watch, onMounted, useTemplateRef } from 'vue';
import { notification } from 'ant-design-vue';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import { UploadIFile } from '@/request/api/follow.api';
import type { UploadFile } from 'ant-design-vue/es/upload/interface';
import { branchMethod } from '@/request/api/system.api';
import { message } from 'ant-design-vue';
import {
  pageMedicineMethod,
  pageDiagnoseTypeMethod,
  addSystemCwMethod,
  addOrgCwMethod,
  getConditioningRecordDetailMethod,
  getAllSystemCpMethod,
  getCpContentListMethod,
} from '@/request/api/care.api';
import RemoteSelect from '@/libs/v-select-page/RemoteSelect.vue';
import { usePagination, useRequest } from 'alova/client';
import 'ant-design-vue/dist/reset.css';
import type { SystemCwModel } from '@/model/care.model';
import AcupointEdit from '@/service/AcupointEdit.vue';
import ServiceDetail from '@/service/ServiceDetail.vue';
import ServicePackageList from '@/service/ServicePackageList.vue';
import { MinusCircleOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { VxeUI } from 'vxe-pc-ui';
type FollowModel = Partial<SystemCwModel>;
const props = defineProps<{ data: FollowModel }>();
const fileList = ref<UploadFile[]>([]);
const uploadProps = reactive({ showRemoveIcon: true });
const emit = defineEmits<{ submit: [data?: SystemCwModel] }>();
const deptId = ref<string>('');
// 获取所有的机构
const branch = ref<any[]>([]);
const { loading: branchLoading } = useRequest(branchMethod).onSuccess(({ data }) => {
  const to = (data?: any[]): any[] => {
    return Array.isArray(data)
      ? data.map((item) => {
          return {
            ...item,
            value: item.id,
            key: item.id.toString(),
            children: to(item.children),
          };
        })
      : [];
  };
  branch.value = to(data);
});
// 递归查找机构名称（优先 label，其次 title），找不到返回空字符串
function findInstitutionLabelById(nodes: any[], targetId: string | number | undefined): string {
  if (!Array.isArray(nodes) || targetId === undefined || targetId === null) return '';
  for (const node of nodes) {
    if (node?.id === targetId || node?.value === targetId) {
      return node?.label ?? node?.title ?? '';
    }
    const childResult = findInstitutionLabelById(node?.children ?? [], targetId);
    if (childResult) return childResult;
  }
  return '';
}
const { loading: addSystemCwLoading, send: addSystemCw } = useRequest(addSystemCwMethod, {
  immediate: false,
}).onSuccess(({ data }) => {
  emit('submit');
});
const { loading: addOrgCwLoading, send: addOrgCw } = useRequest(addOrgCwMethod, {
  immediate: false,
}).onSuccess(({ data }) => {
  emit('submit');
});

const formData = reactive<FollowModel>({
  name: '', //服务包名称
  price: 0, //总计价格
  conditioningWrapPatientMatchRule: {
    sex: '',
    age: '',
    diagnoseDiseaseNames: [],
    diagnoseSyndromeNames: [],
    constitutionGroupNames: [],
    willillStateNames: [],
  },
  items: [],
});
const emptyRow = {
  id: '',
  conditioningWrapId: '',
  conditioningProgramId: 0,
  days: '',
  frequencyType: '',
  frequencyTypeing: [],
  frequencyMeasure: '',
  totalMeasure: '',
  totalPrice: '',
  initialDay: '',
  conditioningProgramDetail: {
    id: '',
    name: '',
    conditioningProgramType: '',
    pricingType: '',
    cpFixedPricingRule: {
      unitPrice: 0,
      pricingUnit: '',
      convertDose: 0,
      convertUnit: '',
    },
    cpDynamicPricingRule: [],
    cpMedicines: [],
    effect: '',
    isOffline: null,
    isDelivery: null,
    photo: '',
    institutionId: '',
    institutionName: '',
    remark: '',
  },
  cwcpAcuMeridians: [],
  cwcpAcuPoints: [],
  conditioningProgramSupplierName: '',
};

function getInstitutionProjectList() {
  const {
    loading: projectLoading,
    onSuccess,
    replace,
    refresh,
    remove,
  } = usePagination(() => getCpContentListMethod(), {
    initialData: { data: [] },
    immediate: true,
  });
  onSuccess(({ data }: any) => {
    allProjects.value = data;
  });
}
function getSystemProjectList() {
  const { loading: projectLoading, onSuccess } = useRequest(getAllSystemCpMethod, {
    immediate: true,
  });
  onSuccess(({ data }: any) => {
    allProjects.value = data;
  });
}
async function getProjectList() {
  if (props.data?.types === 'system') {
    getSystemProjectList();
  } else {
    getInstitutionProjectList();
  }
}
const totalPrice = computed(() => {
  return (formData.items ?? []).reduce((sum, row) => {
    const price = Number(row?.totalPrice) || 0;
    return sum + price;
  }, 0);
});

watch(totalPrice, (val) => {
  formData.price = val;
});

const projectSearchRef = useTemplateRef<any>('projectSearchRef');
const projectSearchFocus = (visible: boolean) => {
  if (visible) setTimeout(() => projectSearchRef.value?.focus?.(), 300);
};

const handleSearchInput = () => {
  console.log('搜索输入事件触发，当前值:', projectSearch.value);
  nextTick();
};
// 安全获取浮层挂载容器：优先 body，无法获取则回退到父节点
const getPopoverContainer = (triggerNode: any) => {
  try {
    // @ts-ignore
    if (typeof document !== 'undefined' && document?.body) return document.body;
    // @ts-ignore
    return triggerNode?.ownerDocument?.body || triggerNode?.parentNode;
  } catch (e) {
    return triggerNode?.parentNode;
  }
};

const projectSearch = ref('');
const showProjectPopover = ref(false);

// 监听搜索文本变化
watch(projectSearch, (newValue, oldValue) => {
  console.log('搜索文本变化:', { newValue, oldValue });
  console.log('当前项目数据:', allProjects.value);
  console.log('过滤后的结果:', filteredProjects.value);
});
const allProjects = ref<
  Array<{
    name: string;
    conditioningProgramType?: string;
    effect?: string;
  }>
>([]);
watch(showProjectPopover, (v) => {
  if (v) nextTick(() => projectSearchRef.value?.focus?.());
});

const filteredProjects = computed(() => {
  const searchText = projectSearch.value.trim().toLowerCase();
  if (!searchText) return allProjects.value;
  return allProjects.value.filter((p) => p.name?.toLowerCase().includes(searchText));
});

function onSelectProject({ row }: any) {
  if ((formData.items ?? []).some((item) => item.conditioningProgramDetail?.name === row.name)) {
    notification.warning({
      message: '不能重复添加该项目',
    });
    return;
  }
  // 添加新行到主表格
  if (!formData.items) formData.items = [];
  formData.items.push({
    id: '',
    conditioningWrapId: '',
    conditioningProgramId: row.id,
    unitPrice: '-',
    days: '',
    frequencyType: '',
    frequencyMeasure: '',
    totalMeasure: '',
    totalPrice: '',
    initialDay: '',
    // 经络
    cwcpAcuMeridians: row?.cwcpAcuMeridians ?? [],
    // 穴位
    cwcpAcuPoints: row?.cwcpAcuPoints ?? [],
    conditioningProgramDetail: {
      ...row,
      id: row?.id || '',
      name: row?.name,
      conditioningProgramType: row?.conditioningProgramType,
      effect: row?.effect,
      pricingType: row?.pricingType,
      cpFixedPricingRule: {
        unitPrice: row?.cpFixedPricingRule?.unitPrice,
        pricingUnit: row?.cpFixedPricingRule?.pricingUnit,
        convertDose: row?.cpFixedPricingRule?.convertDose,
        convertUnit: row?.cpFixedPricingRule?.convertUnit,
      },
      cpDynamicPricingRule: row?.cpDynamicPricingRule,
      cpMedicines: row?.cpMedicines,
      isOffline: row?.isOffline,
      isDelivery: row?.isDelivery,
      photo: row?.photo,
      conditioningProgramSupplierName: row?.conditioningProgramSupplierName,
    },
    // 备注
    remark: row?.remark,
  });

  // 关闭弹窗
  showProjectPopover.value = false;
  // 清空搜索
  projectSearch.value = '';
}
// 预览

function onPreview(row: any) {
  if (row.conditioningProgramDetail.id) {
    // 这里写你的预览逻辑
    VxeUI.modal.open({
      title: `预览`,
      height: 600,
      width: 950,
      escClosable: true,
      destroyOnClose: true,
      id: `preview-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(ServiceDetail, {
            data: row.conditioningProgramDetail,
            onSubmit: (data: any) => {
              VxeUI.modal.close(`preview-modal`);
            },
          });
        },
      },
    });
  } else {
    message.warning('请先添加服务包');
  }
}
function detailPreview(row: any) {
  if (row.id) {
    // 这里写你的预览逻辑
    VxeUI.modal.open({
      title: `预览`,
      height: 600,
      width: 950,
      escClosable: true,
      destroyOnClose: true,
      id: `preview-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(ServiceDetail, {
            data: row,
            onSubmit: (data) => {
              VxeUI.modal.close(`preview-modal`);
            },
          });
        },
      },
      onHide() {
        showProjectPopover.value = true;
      },
    });
    showProjectPopover.value = false;
  } else {
    notification.warning({ message: '请先添加服务包' });
  }
}
function editPart(row: any) {
  VxeUI.modal.open({
    title: `编辑部位`,
    height: 700,
    width: 750,
    escClosable: true,
    destroyOnClose: true,
    id: `edit-part-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(AcupointEdit, {
          data: row,
          onSubmit: (data: any) => {
            VxeUI.modal.close(`edit-part-modal`);
          },
        });
      },
    },
  });
}

// 添加计算数量的函数
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 === '0') {
    // 检查是否选择了"不限"
    if (row.frequencyType === '不限') {
      row.frequencyMeasure = ''; // 重置 frequencyMeasure
      row.totalMeasure = 1;
    } else {
      const convertDose = Number(row.conditioningProgramDetail.cpFixedPricingRule.convertDose) || 0;
      const frequencyType = Number(row.frequencyType) || 0;
      row.totalMeasure = Math.ceil(((period / frequencyType) * frequency) / convertDose);
    }
    // 获取单价
    const unitPrice = Number(row.conditioningProgramDetail?.cpFixedPricingRule?.unitPrice) || 0;
    // 计算总价
    row.totalPrice = (row.totalMeasure * unitPrice).toFixed(2);
  } else if (pricingType === '1') {
    // 按穴位计价
    const frequencyType = Number(row.frequencyType) || 0;

    row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
    // console.log(frequencyType, 'frequencyType', frequency, period, row.totalMeasure);
    // console.log(acCount, maxCount, 'acCount, maxCount', row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.priceType);
    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.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.unitPrice = '-';
          row.totalPrice = row.conditioningProgramDetail.cpDynamicPricingRule[0].price * row.totalMeasure;
        }
      }
    }
  }
}

// 添加监听器
watch(
  () => formData.items,
  (newData) => {
    if (!newData) return;
    newData.forEach((row: any) => {
      if (row?.days || row?.frequencyType || row?.frequencyMeasure) {
        calculateCount(row);
      }
    });
  },
  { deep: true }
);

function cancel() {
  VxeUI.modal.close(`edit-system-service-modal`);
}

function confirm() {
  const isValid = (formData.items ?? []).every((item: any) => {
    delete item.id; // 删除 id 属性
    if (item?.conditioningProgramDetail && item?.conditioningProgramDetail?.pricingType === '1') {
      // 确保 cwcpAcuMeridians 和 cwcpAcuPoints 存在
      const hasMeridians = item.cwcpAcuMeridians?.length > 0; // 使用可选链
      const hasPoints = item.cwcpAcuPoints?.length > 0; // 使用可选链
      // 只要有一个长度大于0，就满足条件
      if (!hasMeridians && !hasPoints) {
        // 如果两个都没有，显示提示
        notification.warning({ message: '请至少选择一个穴位或经络' });
        return false; // 返回 false 表示条件不满足
      }
    }
    return true; // 返回 true 表示条件满足
  });
  formData?.items?.forEach((row: any) => {
    if (row.frequencyTypeing && row.frequencyTypeing.length > 0) {
      row.frequencyType = row.frequencyTypeing[0];
    }
  });
  // 如果所有条件都满足，继续执行后续代码
  if (isValid) {
    // 系统服务包
    if (props.data.types === 'system') {
      delete formData.types;
      addSystemCw({
        ...formData,
      }).then((res) => {
        notification.success({ message: '操作成功' });
        VxeUI.modal.close(`edit-system-service-modal`);
      });
    } else if (props.data.types === 'institution') {
      if (fileList.value.length > 0) {
        const upImg = fileList.value[0]?.response?.url || fileList.value[0]?.thumbUrl;
        formData.photo = upImg;
        fileList.value = upImg
          ? [
              {
                uid: '-1',
                name: 'image.png',
                status: 'done',
                url: upImg,
                thumbUrl: upImg,
                response: { url: upImg },
              },
            ]
          : [];
      }
      addOrgCw({
        ...formData,
      }).then((res) => {
        notification.success({ message: '操作成功' });
        VxeUI.modal.close(`edit-system-service-modal`);
      });
    }
  }
}
// 欲病状态
const desiredConditions = ref<{ id: string; name: string }[]>([]);
const constitutionGroups = ref<{ id: string; name: string }[]>([]);
async function getDesiredConditions() {
  const res = await getDictionaryMethod('conditioning_wrap_willill_state');
  if (res?.length > 0) {
    desiredConditions.value = res.map((item: any) => ({
      id: item.value,
      name: item.label,
    }));
  }
}
// 获取性别
const genders = ref<{ id: string; name: string }[]>([]);
const gendersLoading = ref(false);
async function getGender() {
  gendersLoading.value = true;
  const res = await getDictionaryMethod('sys_user_sex');
  if (res && res.length > 0) {
    genders.value = res.map((item: any) => ({
      id: item.label,
      name: item.label,
    }));
  }
  gendersLoading.value = false;
}
// 获取年龄
const ages = ref<{ id: string; name: string }[]>([]);
async function getAge() {
  const res = await getDictionaryMethod('conditioning_wrap_rule_age');
  if (res && res.length > 0) {
    ages.value = res.map((item: any) => ({
      id: item.label,
      name: item.label,
    }));
  }
}
async function getConstitutionGroup() {
  const res = await getDictionaryMethod('constitution_group');
  if (res && res.length > 0) {
    constitutionGroups.value = res.map((item: any) => ({
      id: item.value,
      name: item.label,
    }));
  }
}
onMounted(async () => {
  // 获取欲病状态
  getDesiredConditions();
  // 获取性别
  getGender();
  // 获取年龄
  getAge();
  // 获取体质
  getConstitutionGroup();
  // 获取机构项目列表  服务包内容点击 弹窗里的内容
  await getProjectList();
  // 有id说明是编辑
  if (props.data.id) {
    props.data.types = 'institution';
    // 调编辑接口获取调理包详情  机构服务包和系统服务包的详情接口是一样的
    const res: any = await getConditioningRecordDetailMethod(props.data);
    Object.assign(formData, res); // Use the response to update formData
    await nextTick(); // 确保视图更新
    // 获取适用情况
    const matchRule = res?.conditioningWrapPatientMatchRule || {};
    Object.assign(formData.conditioningWrapPatientMatchRule!, {
      sex: matchRule.sex ?? '',
      age: matchRule.age ?? '',
      diagnoseDiseaseNames: Array.isArray(matchRule.diagnoseDiseaseNames) ? matchRule.diagnoseDiseaseNames : [],
      diagnoseSyndromeNames: Array.isArray(matchRule.diagnoseSyndromeNames) ? matchRule.diagnoseSyndromeNames : [],
      constitutionGroupNames: Array.isArray(matchRule.constitutionGroupNames) ? matchRule.constitutionGroupNames : [],
      willillStateNames: Array.isArray(matchRule.willillStateNames) ? matchRule.willillStateNames : [],
    });
    formData.items = res?.items ?? [];
    fileList.value = res?.photo
      ? [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: res?.photo,
            thumbUrl: res?.photo,
          },
        ]
      : [];
    formData?.items?.forEach((row: any) => {
      row.frequencyTypeing = row.frequencyType ? [row.frequencyType] : [];
    });
  }
});

const tableData = computed(() => {
  return [...(formData.items ?? []), { ...emptyRow }];
});

function removeTableRow(idx: number) {
  if (idx < (formData.items ?? []).length) {
    formData.items?.splice(idx, 1);
  }
}
// 引入服务包
function addInstitution() {
  deptId.value = localStorage.getItem('deptId') || '';
  // console.log(formData.institutionId, 'formData.institutionId', branch, 'deptId.value');
  // 若未有机构名称且已选择机构ID，则从树中递归查找名称
  if (formData.institutionId) {
    formData.institutionName = findInstitutionLabelById(branch.value, formData.institutionId) || '';
  }
  // console.log(formData.institutionName, 'formData.institutionName');
  VxeUI.modal.open({
    title: '选择引入',
    width: 1000,
    height: 700,
    escClosable: true,
    destroyOnClose: true,
    id: `systemService-list-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(ServicePackageList, {
          data: formData,
          institutionId: formData.institutionId ? formData.institutionId : deptId.value,
          institutionName: formData.institutionName ? formData.institutionName : '',
          onSubmit(data: SystemCwModel) {
            VxeUI.modal.close(`systemService-list-modal`);
          },
        });
      },
    },
  });
}
function customUpload(e: any) {
  // 二次封装上传接口
  UploadIFile(e.file)
    .then((res) => {
      // 文件上传成功
      e.onSuccess(res, e);
    })
    .catch((err) => {
      // 文件上传失败
      e.onError(err);
    });
}
const visible = ref<boolean>(false);
const setVisible = (value: boolean): void => {
  visible.value = value;
};
const previewImg = ref<string>('');
// 预览图片
const handlePreview = async (file: UploadFile) => {
  previewImg.value = file.response?.url ?? file.thumbUrl;
  visible.value = true;
};
function set() {
  formData.items = [];
  formData.name = '';
  formData.conditioningWrapPatientMatchRule = {
    sex: '',
    age: '',
    diagnoseDiseaseNames: [],
    diagnoseSyndromeNames: [],
    constitutionGroupNames: [],
    willillStateNames: [],
  };
}
let multiple = ref<boolean>(true);
function handleSelect(value: string, node: any, extra: any) {
  set();
  formData.institutionId = value;
  formData.institutionName = node.label;
}
function openPopover() {
  showProjectPopover.value = true;
}
</script>

<template>
  <div style="padding: 0 24px">
    <div class="flex" 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>
        <a-tree-select
          v-model:value="formData.institutionId"
          style="width: 280px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          tree-default-expand-all
          :tree-data="branch"
          @select="handleSelect"
          :loading="branchLoading"
          :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
        />
      </div>
      <!-- 服务包名称 -->
      <div class="mr-6" style="display: flex; align-items: center; margin-bottom: 0">
        <span style="white-space: nowrap; margin-right: 8px">服务包名称：</span>
        <a-input style="width: 200px" v-model:value="formData.name" />
        <a-button type="primary" @click="addInstitution" class="ml-4" v-if="props.data?.types === 'institution'" :disabled="!formData.institutionId">引入</a-button>
      </div>
      <!-- 服务形象照 -->
      <div class="flex" v-if="props.data?.types === 'institution'" style="align-items: center; margin-bottom: 0">
        <div class="w-35" style="white-space: nowrap; margin-right: 8px">服务形象照：</div>
        <a-upload
          :showUploadList="uploadProps"
          v-model:file-list="fileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          @preview="handlePreview"
          :maxCount="1"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          :customRequest="customUpload"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
          </div>
        </a-upload>
      </div>
    </div>
    <div style="margin-bottom: 16px">
      <div class="mb-3">适用情况</div>
      <div class="flex items-center mb-3">
        <span class="w-20">使用限制</span>
        <div class="mr-10">
          <span>性别：</span>
          <a-select
            placeholder="请选择"
            v-model:value="formData.conditioningWrapPatientMatchRule.sex"
            style="width: 150px; margin: 0 5px"
            allowClear
            :loading="gendersLoading"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option v-for="option in genders" :key="option.id" :value="option.id" placeholder="请选择">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </div>
        <div>
          <span>年龄：</span>
          <a-select
            v-model:value="formData.conditioningWrapPatientMatchRule.age"
            style="width: 150px; margin: 0 8px"
            placeholder="请选择"
            allowClear
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option v-for="option in ages" :key="option.id" :value="option.id" placeholder="请选择">{{ option.name }}</a-select-option>
          </a-select>
        </div>
      </div>
      <div class="flex items-center">
        <span class="w-20">适用</span>
        <div class="mr-10 flex items-center">
          <span>专病：</span>
          <RemoteSelect
            :load="pageMedicineMethod"
            key-prop="name"
            v-model:value="formData.conditioningWrapPatientMatchRule.diagnoseDiseaseNames"
            style="margin: 0 8px"
            :multiple="multiple"
          />
        </div>
        <div class="mr-10 flex items-center">
          <span>证型：</span>
          <RemoteSelect
            :load="pageDiagnoseTypeMethod"
            key-prop="name"
            v-model:value="formData.conditioningWrapPatientMatchRule.diagnoseSyndromeNames"
            style="margin: 0 8px"
            :multiple="multiple"
          />
        </div>

        <div class="flex items-center mr-10">
          <span>体质：</span>
          <a-select
            v-model:value="formData.conditioningWrapPatientMatchRule.constitutionGroupNames"
            style="width: 120px; margin: 0 8px"
            placeholder="请选择"
            allowClear
            mode="multiple"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option v-for="option in constitutionGroups" :key="option.id" :value="option.id" placeholder="请选择">{{ option.name }}</a-select-option>
          </a-select>
        </div>

        <div>
          <span>欲病状态：</span>
          <a-select
            v-model:value="formData.conditioningWrapPatientMatchRule.willillStateNames"
            style="width: 120px; margin: 0 8px"
            placeholder="请选择"
            allowClear
            mode="multiple"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
            @change="(value) => (formData.conditioningWrapPatientMatchRule.willillStateNames = value)"
          >
            <a-select-option v-for="option in desiredConditions" :key="option.id" :value="option.id" placeholder="请选择">{{ option.name }}</a-select-option>
          </a-select>
        </div>
      </div>
    </div>

    <div style="margin-bottom: 16px">
      <span>服务包内容</span>
      <vxe-table :data="tableData" border style="margin-top: 8px">
        <vxe-column width="60" title="">
          <template #default="{ rowIndex }">
            <a-button type="text" danger @click="removeTableRow(rowIndex)" :disabled="rowIndex === tableData.length - 1">
              <MinusCircleOutlined />
            </a-button>
          </template>
        </vxe-column>
        <vxe-column field="conditioningProgramDetail.name" title="项目名称" width="180">
          <template #default="{ row, rowIndex }">
            <template v-if="rowIndex === tableData.length - 1">
              <a-popover v-model:open="showProjectPopover"
                trigger="click"
                placement="bottomLeft" 
               :overlayStyle="{ width: '350px', padding: 0, zIndex: 4000 }"
               :getPopupContainer="getPopoverContainer"
               :destroyTooltipOnHide="false"
               :arrow="false"
                @openChange="projectSearchFocus">
                <template #content>
                  <vxe-input
                    ref="projectSearchRef"
                    v-model="projectSearch"
                    placeholder="输入项目名称搜索"
                    style="margin: 8px; width: 90%"
                    @change="handleSearchInput"
                  ></vxe-input>
                  <vxe-table :data="filteredProjects" border size="small" style="max-height: 240px; overflow-y: auto" @cell-click="onSelectProject">
                    <vxe-column field="name" title="项目名称" />
                    <vxe-column field="conditioningProgramType" title="方案类型" />
                    <vxe-column field="effect" title="功效" />
                    <vxe-column title="预览" width="60">
                      <template #default="{ row }">
                        <EyeOutlined style="font-size: 18px; color: #1890ff; cursor: pointer" @click.stop="detailPreview(row)" />
                      </template>
                    </vxe-column>
                  </vxe-table>
                </template>
                <vxe-input v-model="row.name" placeholder="请搜索" style="width: 120px" @click="openPopover" readonly></vxe-input>
              </a-popover>
            </template>
            <template v-else>
              {{ row.conditioningProgramDetail?.name }}
            </template>
          </template>
        </vxe-column>
        <vxe-column title="预览" width="50">
          <template #default="{ row }">
            <EyeOutlined style="font-size: 18px; color: #1890ff; cursor: pointer" @click="onPreview(row)" v-if="row?.conditioningProgramDetail?.id" />
          </template>
        </vxe-column>
        <vxe-column field="days" title="周期" width="100">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <a-input v-model:value="row.days" @change="() => calculateCount(row)" />
              <span>天</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="frequencyType" title="频率" width="auto">
          <template #default="{ row }">
            <div v-if="row.conditioningProgramDetail?.name === '健康咨询' || row.conditioningProgramDetail?.name === '健康评估'" class="flex items-center">
              <div class="flex items-center mr-4">
                <span>每</span>
                <a-input v-model:value="row.frequencyType" style="width: 50px" @change="() => calculateCount(row)" :disabled="row.frequencyType === '不限'" />
                <span>天</span>
                <a-input v-model:value="row.frequencyMeasure" style="width: 50px" @change="() => calculateCount(row)" :disabled="row.frequencyType === '不限'" />
                <span>{{ row.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit ? row.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit : '次' }}</span>
              </div>
              <div>
                <a-checkbox-group
                  v-model:value="row.frequencyTypeing"
                  @change="
                    (value) => {
                      row.frequencyTypeing = value.includes('不限') ? ['不限'] : [];
                      row.frequencyType = value.includes('不限') ? '不限' : '';
                      calculateCount(row);
                    }
                  "
                >
                  <a-checkbox value="不限">不限</a-checkbox>
                </a-checkbox-group>
              </div>
            </div>
            <div class="flex items-center" v-else>
              <span>每</span>
              <a-input v-model:value="row.frequencyType" style="width: 50px" @change="() => calculateCount(row)" />
              <span>天</span>
              <a-input v-model:value="row.frequencyMeasure" style="width: 50px" @change="() => calculateCount(row)" />
              <span>{{ row.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit ? row.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit : '次' }}</span>
            </div>
          </template>
        </vxe-column>

        <vxe-column field="row?.conditioningProgramDetail?.conditioningProgramType" title="方案类型" width="120">
          <template #default="{ row }">
            {{ row?.conditioningProgramDetail?.conditioningProgramType || '-' }}
          </template>
        </vxe-column>
        <vxe-column field="row.totalMeasure" title="数量" width="60">
          <template #default="{ row }">
            {{ row.totalMeasure || 0 }}
          </template>
        </vxe-column>
        <vxe-column field="row?.conditioningProgramDetail?.cpFixedPricingRule?.unit" title="单位" width="60">
          <template #default="{ row }">
            {{ row?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit ? row?.conditioningProgramDetail?.cpFixedPricingRule?.pricingUnit : '次' }}
          </template>
        </vxe-column>
        <vxe-column field="row.conditioningProgramDetail.cpFixedPricingRule.unitPrice" title="单价（元）" width="100">
          <template #default="{ row }">
            {{ row?.conditioningProgramDetail?.pricingType === '0' ? row.conditioningProgramDetail?.cpFixedPricingRule?.unitPrice : row?.unitPrice }}
          </template>
        </vxe-column>
        <vxe-column field="row.totalPrice" title="总价（元）" width="auto" @change="() => calculateCount(row)">
          <template #default="{ row }">
            <span>{{ row.totalPrice || 0 }}</span>
          </template>
        </vxe-column>
        <vxe-column field="start" title="开始时间" width="190">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <span>调养开始第</span>
              <a-input v-model:value="row.initialDay" style="width: 60px" />
              <span>天</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="conditioningProgramDetail.isOffline" title="线下项目" width="100">
          <template #default="{ row }">
            <span v-if="row.conditioningProgramDetail?.isOffline">
              {{ row.conditioningProgramDetail.isOffline === 'Y' ? '是' : '否' }}
            </span>
            <span v-else>-</span>
          </template>
        </vxe-column>

        <vxe-column field="conditioningProgramDetail.pricingType" title="穴位/经络/部位" width="120">
          <template #default="{ row }">
            <a @click="editPart(row)" style="color: #1890ff; cursor: pointer" v-if="row?.conditioningProgramDetail?.pricingType === '1'">编辑</a>
          </template>
        </vxe-column>
        <vxe-column field="remark" title="说明" width="180">
          <template #default="{ row }">
            <!-- <div>说明star：{{ row.remark }}：说明结束</div> -->
            <a-textarea v-model:value="row.remark" style="max-width: 180px; width: 100%; height: 50px" :rows="2" show-count :maxLength="200" />
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <a-image
      :width="200"
      :style="{ display: 'none' }"
      :preview="{
        visible,
        onVisibleChange: setVisible,
      }"
      :src="previewImg"
    />
    <div style="display: flex; justify-content: flex-end">
      <span style="font-weight: bold">合计：{{ formData.price }}元</span>
    </div>

    <div style="display: flex; justify-content: center">
      <a-button style="margin-right: 24px" @click="cancel">取消</a-button>
      <a-button type="primary" @click="confirm">确认</a-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 可根据实际需求自定义样式 */
.v-dropdown-trigger {
  width: 160px !important;
}
.sp-trigger-container .sp-trigger.sp-select .sp-select-content {
  overflow: hidden !important;
  width: 100px !important;
  white-space: nowrap !important;
  text-overflow: ellipsis !important;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
