<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import { pageMedicineMethod, pageDiagnoseTypeMethod, getConditioningSchemeDetailMethod } from '@/request/api/care.api';
import RemoteSelect from '@/libs/v-select-page/RemoteSelect.vue';
import 'ant-design-vue/dist/reset.css';
import type { SystemItemModel } from '@/model/care.model';
import { VxeUI } from 'vxe-pc-ui';
type FollowModel = Partial<SystemItemModel>;
const props = defineProps<{ data: FollowModel }>();
const emit = defineEmits<{
  (e: 'submit', data: FollowModel): void;
  (e: 'cancel'): void;
}>();
const formData = reactive<FollowModel>({
  cpPatientMatchRule: {
    sex: '',
    age: '',
    diagnoseDiseaseNames: [],
    diagnoseSyndromeNames: [],
    constitutionGroupNames: [],
    willillStateNames: [],
    tabooCrowds: [],
  },
});

// 取消
function cancel() {
  emit('cancel'); // 触发取消事件
  VxeUI.modal.close(`derivation-modal`);
}
// 确定
function confirm() {
  if (props.data?.checkedList.includes('2')) {
    const matchRule = formData.cpPatientMatchRule as {
      diagnoseDiseaseNames?: any[];
      willillStateNames?: any[];
      constitutionGroupNames?: any[];
      diagnoseSyndromeNames?: any[];
    };
    const isAllEmpty =
      (!matchRule.diagnoseDiseaseNames || matchRule.diagnoseDiseaseNames.length === 0) &&
      (!matchRule.willillStateNames || matchRule.willillStateNames.length === 0) &&
      (!matchRule.constitutionGroupNames || matchRule.constitutionGroupNames.length === 0) &&
      (!matchRule.diagnoseSyndromeNames || matchRule.diagnoseSyndromeNames.length === 0);
    if (isAllEmpty) {
      VxeUI.modal.message({ content: '专病、欲病状态、体质、证型至少填写一项', status: 'warning' });
      return;
    }
    formData.isForWrap = 'Y';
  }
  VxeUI.modal.close(`derivation-modal`);
  emit('submit', formData);
}
// 欲病状态
const desiredConditions = ref<{ label: string; value: string }[]>([]);
const constitutionGroups = ref<{ label: string; value: string }[]>([]);
const tabooCrowds = ref<{ label: string; value: string }[]>([]);
async function getDesiredConditions() {
  const res = await getDictionaryMethod('conditioning_wrap_willill_state');
  if (res?.length > 0) {
    desiredConditions.value = res.map((item: any) => ({
      label: item.label,
      value: item.value,
    }));
  }
}
// 获取性别
const genders = ref<{ label: string; value: 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) => ({
      label: item.label,
      value: item.label,
    }));
  }
  gendersLoading.value = false;
}
// 获取年龄
const ages = ref<{ label: string; value: string }[]>([]);
async function getAge() {
  const res = await getDictionaryMethod('conditioning_wrap_rule_age');
  if (res && res.length > 0) {
    ages.value = res.map((item: any) => ({
      label: item.label,
      value: item.label,
    }));
  }
}
// 获取体质
async function getConstitutionGroup() {
  const res = await getDictionaryMethod('constitution_group');
  if (res && res.length > 0) {
    constitutionGroups.value = res.map((item: any) => ({
      label: item.label,
      value: item.value,
    }));
  }
}
// 获取禁忌
async function getTabooCrowds() {
  const res = await getDictionaryMethod('fdhb_taboo_crowd');
  if (res && res.length > 0) {
    tabooCrowds.value = res.map((item: any) => ({
      label: item.label,
      value: item.value,
    }));
  }
}
onMounted(async () => {
  // 获取欲病状态
  getDesiredConditions();
  // 获取性别
  getGender();
  // 获取年龄
  getAge();
  // 获取体质
  getConstitutionGroup();
  // 获取禁忌
  getTabooCrowds();
  // 获取适用情况数据
  let matchRule = props.data.cpPatientMatchRule || {};
  // if (props.data.id) {
  //   // 调编辑接口获取调理包详情
  //   const res: any = await getConditioningSchemeDetailMethod(props.data);
  //   console.log(res,'调编辑接口获取调理包详情');
  //   await nextTick(); // 确保视图更新
  //   matchRule = res?.cpPatientMatchRule || {};
  // }

  // 统一处理数据赋值
  Object.assign(formData.cpPatientMatchRule!, {
    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 : [],
    tabooCrowds: Array.isArray(matchRule.tabooCrowds) ? matchRule.tabooCrowds : [],
  });
});
let multiple = ref<boolean>(true);
</script>

<template>
  <div class="derivation-container">
    <!-- 左侧表单区域 -->
    <div class="form-section">
      <!-- 适用情况 -->
      <div class="section-block">
        <div class="section-title">适用情况</div>
        <div class="form-content">
          <!-- 专病 -->
          <div class="form-item">
            <span class="label">专病：</span>
            <RemoteSelect :load="pageMedicineMethod" key-prop="name" v-model:value="formData.cpPatientMatchRule.diagnoseDiseaseNames" style="width: 100%" :multiple="multiple" />
          </div>
          <!-- 欲病状态 -->
          <div class="form-item">
            <span class="label">欲病状态：</span>
            <vxe-select
              v-model="formData.cpPatientMatchRule.willillStateNames"
              placeholder="请选择"
              style="width: 100%"
              clearable
              multiple
              :options="desiredConditions"
            ></vxe-select>
          </div>

          <!-- 体质 -->
          <div class="form-item constitution-item">
            <span class="label">体质：</span>
            <vxe-select
              v-model="formData.cpPatientMatchRule.constitutionGroupNames"
              style="width: 100%"
              placeholder="请选择"
              clearable
              multiple
              :options="constitutionGroups"
            ></vxe-select>
          </div>

          <!-- 证型 -->
          <div class="form-item">
            <span class="label">证型：</span>
            <RemoteSelect
              :load="pageDiagnoseTypeMethod"
              key-prop="name"
              v-model:value="formData.cpPatientMatchRule.diagnoseSyndromeNames"
              style="width: 200px"
              :multiple="multiple"
            />
          </div>

          <!-- 性别限制 -->
          <div class="form-item">
            <span class="label">性别限制：</span>
            <vxe-select v-model="formData.cpPatientMatchRule.sex" placeholder="请选择" style="width: 100%" clearable :options="genders"></vxe-select>
          </div>

          <!-- 年龄限制 -->
          <div class="form-item">
            <span class="label">年龄限制：</span>
            <vxe-select v-model="formData.cpPatientMatchRule.age" placeholder="请选择" style="width: 100%" clearable :options="ages"></vxe-select>
          </div>
        </div>
      </div>

      <!-- 禁忌 -->
      <div class="section-block">
        <div class="section-title">禁忌</div>
        <div class="form-content">
          <div class="form-item">
            <span class="label">禁忌人群：</span>
            <vxe-select v-model="formData.cpPatientMatchRule.tabooCrowds" style="width: 100%" placeholder="请选择" clearable multiple :options="tabooCrowds"></vxe-select>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 底部按钮 -->
  <div class="button-container">
    <a-button @click="cancel">取消</a-button>
    <a-button type="primary" @click="confirm">确定</a-button>
  </div>
</template>

<style scoped>
.derivation-container {
  display: flex;
  gap: 40px;
  padding: 24px;
  min-height: 500px;
  position: relative;
}

.form-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  /* gap: 32px; */
}

.section-block {
  background: #fff;
  border-radius: 8px;
  padding: 0 0 20px 0px;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); */
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

.constitution-item {
  position: relative;
}

.label {
  min-width: 80px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  text-align: right;
}

.info-section {
  width: 300px;
  display: flex;
  align-items: flex-start;
  padding-top: 80px; /* 对齐体质字段 */
}

.info-box {
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 8px;
  padding: 20px;
  width: 100%;
  position: relative;
}

.info-box::before {
  content: '';
  position: absolute;
  left: -10px;
  top: 50%;
  width: 10px;
  height: 2px;
  background: #d9d9d9;
  transform: translateY(-50%);
}

.info-title {
  font-size: 14px;
  font-weight: bold;
  color: #d46b08;
  margin-bottom: 12px;
}

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

.rule-item {
  display: flex;
  align-items: flex-start;
  gap: 4px;
  font-size: 13px;
  line-height: 1.5;
  color: #666;
}

.rule-number {
  color: #d46b08;
  font-weight: bold;
  flex-shrink: 0;
}

.rule-text {
  flex: 1;
}

.info-signature {
  text-align: right;
  margin-top: 12px;
  font-size: 12px;
  color: #999;
  font-style: italic;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 20px;
}

.button-container .ant-btn {
  min-width: 80px;
  height: 32px;
}

.button-container .ant-btn-primary {
  background: #faad14;
  border-color: #faad14;
}

.button-container .ant-btn-primary:hover {
  background: #ffc53d;
  border-color: #ffc53d;
}
</style>
