<template>
  <BasicLayout>
    <view class="p-15">
      <view v-if="education.xl.length > 0">
        <template v-for="(item, index) in education.xl" :key="index">
          <view class="po-re mb-15">
            <BasicForm
              v-model="item.value"
              :schema="getSchemaForIndex(index)"
              :index="index"
              :key="`form-${index}-${forceUpdateKey}`"
              :formsProps="{ labelWidth: 100 }"
            />
            <view
              @click="deleteMemberFamily(index, item.value)"
              class="delete-icon"
            >
              <BasicIcon type="clear" size="30" />
            </view>
          </view>
        </template>
      </view>
      <view
        class="flex-row items-center justify-center pb-10 pt-5"
        style="border: 1px solid #e8e8e8"
        @click="addEducation"
      >
        <uni-icons type="plus" size="16" color="#447ADE"></uni-icons>
        <view class="ml-5 cor-447ADE">新增</view>
      </view>
    </view>
    <template #bottom>
      <view class="flex-row items-center pb-10 pt-5">
        <u-button text="提交" class="mx-15" type="primary" @click="submit" />
      </view>
    </template>
  </BasicLayout>
</template>

<script lang="ts" setup>
import { fractionRuleApi1 } from "@/api/base/server";
import { showToast } from "@/utils/uniapp";
import { cloneDeep, map } from "lodash";

// 主数据
const education = reactive<any>({
  xl: [{ value: {} }],
});

// 荣誉类别数据缓存
const honorCategories = ref<any[]>([]);

// 每个表单项对应的获奖级别数据
const awardLevelsMap = reactive<Record<number, any>>({});

// 强制重新渲染的键
const forceUpdateKey = ref(0);

// 基础表单配置
const baseSchema = [
  {
    field: "rymc",
    label: "荣誉名称",
    component: "BasicInput",
    componentProps: {},
  },
  {
    field: "hilb_id",
    label: "荣誉类别",
    component: "BasicPicker",
    componentProps: {
      api: fractionRuleApi1,
      rangeKey: "inspectStandard",
      savaKey: "id",
      ok: (selectedIndex: number, form: any, list: any, attrs: any) => {
        const selectedCategory = list[selectedIndex];
        const formIndex = attrs.index;

        // 更新当前表单项的获奖级别选项
        updateAwardLevels(formIndex, selectedCategory);

        // 清空已选择的获奖级别（如果之前有选择的话）
        if (education.xl[formIndex].value.xm) {
          education.xl[formIndex].value.xm = "";
        }

        // 强制重新渲染
        forceUpdateKey.value++;
      },
    },
  },
  {
    field: "xm",
    label: "获奖级别",
    component: "BasicPicker",
    componentProps: {
      range: [],
      rangeKey: "name",
      savaKey: "id",
      open: (value: any, attrs: any, model: any) => {
        const formIndex = attrs.index;

        // 检查是否已选择荣誉类别
        if (!model?.hilb_id) {
          showToast({
            title: "请先选择荣誉类别",
            icon: "none",
          });
          return false;
        }

        // 检查是否有对应的获奖级别数据
        const awardLevels = awardLevelsMap[formIndex] || [];

        if (awardLevels.length === 0) {
          showToast({
            title: "该荣誉类别暂无获奖级别数据",
            icon: "none",
          });
          return false;
        }

        return true;
      },
    },
  },
  {
    field: "bjdw",
    label: "颁奖单位",
    component: "BasicInput",
    componentProps: {},
  },
  {
    field: "hjtime",
    label: "获奖时间",
    component: "BasicDateTimes",
    componentProps: {},
  },
  {
    field: "jf",
    label: "积分",
    component: "BasicInput",
    componentProps: {},
  },
  {
    field: "hjfjId",
    label: "上传证书",
    component: "BasicUpload",
    required: true,
    itemProps: {
      labelPosition: "top",
    },
    componentProps: {},
  },
];

// 为每个表单项生成动态的schema
const getSchemaForIndex = (index: number) => {
  const schema = cloneDeep(baseSchema);

  // 更新获奖级别的选项数据
  const hjjbField = schema.find((item) => item.field === "xm");
  if (hjjbField) {
    hjjbField.componentProps.range = awardLevelsMap[index] || [];
  }

  return schema;
};

// 更新指定表单项的获奖级别选项
const updateAwardLevels = (formIndex: number, category: any) => {
  if (category?.ruleItemList && category.ruleItemList.length > 0) {
    awardLevelsMap[formIndex] = category.ruleItemList;
  } else {
    awardLevelsMap[formIndex] = [];
  }
};

// 初始化荣誉类别数据
const initHonorCategories = async () => {
  try {
    const result = await fractionRuleApi1();
    honorCategories.value = result.result || result || [];
  } catch (error) {
    console.error("获取荣誉类别数据失败:", error);
  }
};

// 初始化回显数据
const initEchoData = async () => {
  await initHonorCategories();

  // 为每个已有数据的表单项初始化获奖级别选项
  education.xl.forEach((formItem: any, index: number) => {
    if (formItem.value?.hilb_id) {
      const category = honorCategories.value.find(
        (cat: any) => cat.id === formItem.value.hilb_id
      );

      if (category) {
        // 更新获奖级别选项
        updateAwardLevels(index, category);
      } else {
        console.log(`未找到荣誉类别 ID: ${formItem.value.hilb_id}`);
      }
    }
  });

  // 强制重新渲染以确保获奖级别能正确显示
  forceUpdateKey.value++;
};

// 添加新的教育项
function addEducation() {
  const newIndex = education.xl.length;
  education.xl.push({ value: {} });

  // 为新项初始化空的获奖级别选项
  awardLevelsMap[newIndex] = [];
}

// 删除教育项
function deleteMemberFamily(index: number, item: any) {
  // 删除对应的获奖级别数据
  delete awardLevelsMap[index];

  // 重新整理awardLevelsMap的键值
  const newAwardLevelsMap: Record<number, any[]> = {};
  education.xl.forEach((_: any, i: number) => {
    if (i < index) {
      newAwardLevelsMap[i] = awardLevelsMap[i] || [];
    } else if (i > index) {
      newAwardLevelsMap[i - 1] = awardLevelsMap[i] || [];
    }
  });

  // 删除表单项
  education.xl.splice(index, 1);

  // 更新awardLevelsMap
  Object.keys(awardLevelsMap).forEach(
    (key: string) => delete awardLevelsMap[Number(key)]
  );
  Object.assign(awardLevelsMap, newAwardLevelsMap);
}

// 提交数据
function submit() {
  const gkkRyList = map(education.xl, (item) => {
    return { ...item.value, hjlxId: "GKKHJQK" };
  });
}

// // 初始化数据
// const { getFile, setFile } = useDataStore();

// // 处理回显数据
// if (getFile.gkkRyList && getFile.gkkRyList.length > 0) {
//   education.xl = map(getFile.gkkRyList, (item) => {
//     return { value: item };
//   });
// }

// 页面加载时初始化
onMounted(() => {
  // if (getFile.gkkRyList && getFile.gkkRyList.length > 0) {
  //   // 有回显数据时，延迟初始化确保数据正确加载
  //   nextTick(() => {
  //     initEchoData();
  //   });
  // } else {
  //   // 无回显数据时，只需要初始化荣誉类别
  //   initHonorCategories();
  // }
});
</script>
<style>
.delete-icon {
  position: absolute;
  right: -13px;
  top: -14px;
  z-index: 1;
}
</style>
