<script setup lang="ts">
import { ref, computed, nextTick, h, watch, onMounted } 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 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);
});
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: [],
  },
  cwPatientMatchRules: [
    {
      diagnoseDiseaseNames: [],
      diagnoseSyndromeNames: [],
      constitutionGroupNames: [],
      diagnoseDisease: {
        id: '',
        code: '',
        name: '',
        optionalWords: '',
        attributes: [],
        children: [],
      },
      diagnoseSyndrome: {
        code: '',
        name: '',
        analysis: '',
        remark: '',
      },
      constitutionGroup: {
        id: '',
        code: '',
        name: '',
        definition: '',
        remark: '',
      },
    },
  ], // 适用情况
  items: [], // Initialize as empty array
});
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;
});

// function addSituation() {
//   if (!formData.cwPatientMatchRules) formData.cwPatientMatchRules = [];
//   formData.cwPatientMatchRules.push({
//     diagnoseDiseaseNames: [],
//     diagnoseSyndromeNames: [],
//     constitutionGroupNames: [],
//     diagnoseDisease: { id: '', code: '', name: '' },
//     diagnoseSyndrome: { code: '', name: '', analysis: '', remark: '' },
//     constitutionGroup: { id: '', code: '', name: '', definition: '', remark: '' },
//   });
// }

// function removeSituation(idx: number) {
//   if (formData.cwPatientMatchRules) {
//     formData.cwPatientMatchRules.splice(idx, 1);
//   }
// }
const projectSearchRef = useTemplateRef<HTMLInputElement>('projectSearchRef');
const projectSearchFocus = (visible: boolean) => {
  if (visible) setTimeout(() => projectSearchRef.value?.focus?.(), 300);
};

const projectSearch = ref('');
const showProjectPopover = ref(false);
const allProjects = ref<
  Array<{
    name: string;
    conditioningProgramType?: string;
    effect?: string;
  }>
>([]);
const filteredProjects = computed(() => {
  const searchText = projectSearch.value.toLowerCase();
  if (allProjects.value.length > 0) {
    return allProjects.value.filter(
      (p) => p.name.toLowerCase().includes(searchText) || p?.conditioningProgramType?.toLowerCase().includes(searchText) || p.effect?.toLowerCase().includes(searchText)
    );
  } else {
    return [];
  }
});

function onSelectProject({ row }: any) {
  console.log(row, 'onSelectProject');
  if ((formData.items ?? []).some((item) => item.conditioningProgramDetail?.name === row.name)) {
    message.warning('不能重复添加该项目');
    return;
  }
  // 添加新行到主表格
  if (!formData.items) formData.items = [];
  formData.items.push({
    id: '',
    conditioningWrapId: '',
    conditioningProgramId: row.id,
    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) {
  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) => {
              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 {
    message.warning('请先添加服务包');
  }
}
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) => {
            console.log(data, '编辑穴位传递的参数');
            // refresh(page.value);
            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;
  console.log(row, '添加计算数量的函数');
  const acCount = (row.acuMeridianNames?.length ?? 0) + (row.acuPointNames?.length ?? 0);
  console.log(acCount, 'acCount');
  // 一口价
  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);
    let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[0].price;
    if (acCount > maxCount) {
      if (row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.priceType === 0) {
        // 单价
        // let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[1].price;
        row.unitPrice = unitPrice;
        // row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
        row.totalPrice = Math.ceil((period / frequencyType) * unitPrice * acCount);
      } else if (row.conditioningProgramDetail.cpDynamicPricingRule?.[1]?.priceType === 1) {
      
        // 一口价
        row.conditioningProgramDetail.unitPrice = '-';
        row.totalPrice = row.conditioningProgramDetail.cpDynamicPricingRule[1].price;
        // row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
      }
    } else {
      if (row.conditioningProgramDetail.cpDynamicPricingRule?.length > 0) {
        if (row.conditioningProgramDetail.cpDynamicPricingRule?.[0]?.priceType === 0) {
          // 单价
          // let unitPrice: number = row.conditioningProgramDetail.cpDynamicPricingRule[0].price;
          row.unitPrice = unitPrice;
          // row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
          row.totalPrice = Math.ceil((period / frequencyType) * unitPrice * acCount);
        } else if (row.conditioningProgramDetail.cpDynamicPricingRule?.[0]?.priceType === 1) {
          // 一口价
          row.unitPrice = '-';
          row.totalPrice = row.conditioningProgramDetail.cpDynamicPricingRule[0].price;
          // row.totalMeasure = Math.ceil((period / frequencyType) * frequency);
        }
      }
    }
  }
}

// 添加监听器
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) {
        // 如果两个都没有，显示提示
        message.warning('请至少选择一个穴位或经络');
        return false; // 返回 false 表示条件不满足
      }
    }
    return true; // 返回 true 表示条件满足
  });
  formData?.items?.forEach((row: any) => {
    if (row.frequencyTypeing && row.frequencyTypeing.length > 0) {
      row.frequencyType = row.frequencyTypeing[0];
    }
  });
  // console.log(props.data.types, 'formData.items');
  // 如果所有条件都满足，继续执行后续代码
  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;
        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 }[]>([]);
async function getGender() {
  const res = await getDictionaryMethod('sys_user_sex');
  if (res && res.length > 0) {
    genders.value = res.map((item: any) => ({
      id: item.label,
      name: item.label,
    }));
  } else {
    console.log('性别数据未获取到');
  }
}
// 获取年龄
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();
  if (props.data.id) {
    props.data.types = 'institution'; // Modify the local copy instead
    // 调编辑接口获取数据
    const res: any = await getConditioningRecordDetailMethod(props.data);
    Object.assign(formData, res); // Use the response to update formData
    await nextTick(); // 确保视图更新

    formData.conditioningWrapPatientMatchRule = res?.conditioningWrapPatientMatchRule ?? {
      sex: '',
      age: '',
      diagnoseDiseaseNames: [],
      diagnoseSyndromeNames: [],
      constitutionGroupNames: [],
      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] : [];
    });
  }
  await getProjectList();
});

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

function removeTableRow(idx: number) {
  if (idx < (formData.items ?? []).length) {
    formData.items?.splice(idx, 1);
  }
}
// 引入服务包
function addInstitution() {
  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,
          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;
};
let multiple = ref<boolean>(true);
function handleSelect(value: string, node: any, extra: any) {
  // console.log(value, 'value');
  // console.log(node, 'node');
  // console.log(extra, 'extra');
  formData.institutionId = value;
  formData.institutionName = node.label;
}
</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"
          show-search
          style="width: 220px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          allow-clear
          tree-default-expand-all
          :tree-data="branch"
          @select="handleSelect"
        />
      </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'">引入</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>
            <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>
            <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"
          >
            <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"
            @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 v-for="(item, idx) in formData.cwPatientMatchRules" :key="idx" style="display: flex; align-items: center; margin-bottom: 8px">
        <span>情况{{ idx + 1 }} 专病：</span>
        <RemoteSelect :load="pageMedicineMethod" key-prop="name" v-model:value="item.diagnoseDisease" style="margin: 0 8px" :multiple="multiple"/>
        <span>且 证型：</span>
        <RemoteSelect :load="pageDiagnoseTypeMethod" key-prop="name" v-model:value="item.diagnoseSyndrome.name" style="margin: 0 8px" :multiple="multiple"  />
        <span>且 体质：</span>
        <a-select v-model="item.constitutionGroup" style="width: 120px; margin: 0 8px" placeholder="请选择" allowClear mode="multiple">
          <a-select-option v-for="option in constitutionGroups" :key="option.id" :value="option.id" placeholder="请选择">{{ option.name }}</a-select-option>
        </a-select>
        <a-button v-if="(formData.cwPatientMatchRules?.length ?? 0) > 1" @click="removeSituation(idx)" type="text" danger>
          <MinusCircleOutlined />
        </a-button>
        <a-button v-if="idx === (formData.cwPatientMatchRules?.length ?? 0) - 1" @click="addSituation" type="text">
          <PlusCircleOutlined />
        </a-button>
      </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 }"
                @openChange="projectSearchFocus($event)"
              >
                <template #content>
                  <a-input ref="projectSearchRef" v-model:value="projectSearch" placeholder="输入项目名称搜索" style="margin: 8px; width: 90%" @input="() => nextTick()" />
                  <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>
                <a-input v-model:value="row.name" placeholder="请搜索" style="width: 120px" @click="showProjectPopover = true" readonly />
              </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 }">
            <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>
