
<template>
  <div class="pt-4">
    <SimpleForm
      ref="systemFormRef"
      :formProps="data.formDataProps"
      :formModel="state.formModel"
      :isWorkFlow="props.fromPage!=FromPageType.MENU"
      :isCamelCase="true" 
      @model-change="handleChange"
    />
    <SelectCollectionItemModal @register="registerSelectModal" @success="handleSelectSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, onMounted, nextTick, watch } from 'vue';
  import { formProps, formEventConfigs } from './config';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { addMesCollectionScheme, getMesCollectionScheme, updateMesCollectionScheme } from '/@/api/jcsj/cjfa';
  import { cloneDeep, isString  } from 'lodash-es';
  import { FormDataProps } from '/@/components/Designer/src/types';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { FromPageType } from '/@/enums/workflowEnum';
  import { createFormEvent, getFormDataEvent, loadFormEvent, submitFormEvent,} from '/@/hooks/web/useFormEvent';
  import { changeWorkFlowForm, changeSchemaDisabled } from '/@/hooks/web/useWorkFlowForm';
  import { WorkFlowFormParams } from '/@/model/workflow/bpmnConfig';
  import { useRouter } from 'vue-router';
  import { useModal } from '/@/components/Modal';
  import SelectCollectionItemModal from './SelectCollectionItemModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  
  const { filterFormSchemaAuth } = usePermission();
  const { notification } = useMessage();

  const RowKey = 'id';
  const emits = defineEmits(['changeUploadComponentIds','loadingCompleted', 'update:value']);
  const props = defineProps({
    fromPage: {
      type: Number,
      default: FromPageType.MENU,
    },
  });
  const systemFormRef = ref();
  const formDataPropsValue = cloneDeep(formProps);
  if (!formDataPropsValue.buttonList) {
    formDataPropsValue.buttonList = [];
  }
  const data: { formDataProps: FormDataProps & { buttonList: any[] } } = reactive({
    formDataProps: formDataPropsValue as FormDataProps & { buttonList: any[] },
  });
  const state = reactive({
    formModel: {} as any,
    formInfo:{formId:'',formName:''},
    subFormRef: null as any,
  });
  const { currentRoute } = useRouter();
  const [registerSelectModal, { openModal: openSelectModal }] = useModal();

  watch(
    () => state.formModel,
    (val) => { 
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );

  // 监听采集内容变化，更新SubForm配置
  watch(
    () => state.formModel.contentType,
    () => {
      updateSubFormConfig();
    },
  );

  // 更新SubForm配置，添加自定义新增逻辑
  function updateSubFormConfig() {
    const schemas = data.formDataProps.schemas;
    if (!schemas) return;

    // 查找SubForm组件
    const tabSchema = schemas.find((s) => s.component === 'Tab');
    if (!tabSchema || !tabSchema.children) return;

    const tabPane = tabSchema.children[0];
    if (!tabPane || !tabPane.list) return;

    const subFormSchema = tabPane.list.find((s: any) => s.component === 'SubForm');
    if (!subFormSchema || !subFormSchema.componentProps) return;

    // 修改SubForm配置，添加addBefore钩子来拦截新增
    subFormSchema.componentProps.addBefore = (formModel: any, pushObj: any) => {
      // 检查是否选择了采集内容
      const currentContentType = formModel?.contentType;
      if (!currentContentType) {
        notification.warning({
          message: '提示',
          description: '请先选择采集内容',
        });
        // 标记为需要取消，但在addBefore中无法阻止，需要在addAfter中处理
        pushObj._shouldCancel = true;
        return;
      }

      // 设置标志，表示需要打开选择弹窗而不是直接添加
      pushObj._customAdd = true;
    };

    // 在addAfter中处理自定义添加逻辑
    subFormSchema.componentProps.addAfter = (formModel: any, pushObj: any) => {
      // 如果需要取消（未选择采集内容），移除刚添加的行
      if (pushObj._shouldCancel) {
        nextTick(() => {
          const currentList = state.formModel.mesCollectionSchemeItemList || [];
          // 使用key属性或对象引用来查找并移除
          const index = pushObj.key !== undefined 
            ? currentList.findIndex((item: any) => item.key === pushObj.key)
            : currentList.findIndex((item: any) => item === pushObj);
          
          // 如果找不到，尝试移除最后一个元素（通常是刚添加的）
          if (index < 0 && currentList.length > 0) {
            currentList.pop();
          } else if (index >= 0) {
            currentList.splice(index, 1);
          }
          
          // 更新表单数据
          if (systemFormRef.value) {
            systemFormRef.value.setFieldsValue(state.formModel);
          }
        });
        return;
      }

      // 如果是自定义添加（需要打开选择弹窗），移除刚添加的空行并打开选择弹窗
      if (pushObj._customAdd) {
        nextTick(() => {
          const currentList = state.formModel.mesCollectionSchemeItemList || [];
          // 使用key属性或对象引用来查找并移除
          const index = pushObj.key !== undefined 
            ? currentList.findIndex((item: any) => item.key === pushObj.key)
            : currentList.findIndex((item: any) => item === pushObj);
          
          // 如果找不到，尝试移除最后一个元素（通常是刚添加的）
          if (index < 0 && currentList.length > 0) {
            currentList.pop();
          } else if (index >= 0) {
            currentList.splice(index, 1);
          }
          
          // 更新表单数据
          if (systemFormRef.value) {
            systemFormRef.value.setFieldsValue(state.formModel);
          }

          // 打开选择弹窗
          const currentContentType = formModel?.contentType;
          if (currentContentType) {
            openSelectModal(true, { contentType: currentContentType });
          }
        });
      }
    };
  }

  // 处理选择采集项成功
  function handleSelectSuccess(selectedItems: any[]) {
    if (!selectedItems || selectedItems.length === 0) return;

    // 获取当前的采集项列表
    const currentList = state.formModel.mesCollectionSchemeItemList || [];
    
    // 获取已存在的采集项ID和编码，避免重复添加
    const existingIds = new Set(currentList.map((item: any) => item.id).filter(Boolean));
    const existingCodes = new Set(currentList.map((item: any) => item.code).filter(Boolean));
    
    // 记录重复的项
    const duplicateItems: string[] = [];
    const addedItems: any[] = [];
    
    // 检查并添加选中的采集项
    selectedItems.forEach((item) => {
      // 检查是否已存在（通过ID或编码判断）
      const isDuplicateById = item.id && existingIds.has(item.id);
      const isDuplicateByCode = item.code && existingCodes.has(item.code);
      
      if (isDuplicateById || isDuplicateByCode) {
        // 记录重复项的名称
        duplicateItems.push(item.name || item.code || '未知项');
      } else {
        // 添加新项
        const newItem = {
          code: item.code,
          name: item.name,
          contentType: item.contentType,
          note: item.note,
          id: item.id,
          schemeId: state.formModel.id || '',
        };
        currentList.push(newItem);
        addedItems.push(newItem);
        
        // 更新已存在的ID和编码集合
        if (item.id) {
          existingIds.add(item.id);
        }
        if (item.code) {
          existingCodes.add(item.code);
        }
      }
    });

    // 如果有重复项，提示用户
    if (duplicateItems.length > 0) {
      notification.warning({
        message: '提示',
        description: `以下采集项已存在，已跳过：${duplicateItems.join('、')}`,
        duration: 3,
      });
    }

    // 如果没有成功添加任何项，直接返回
    if (addedItems.length === 0) {
      return;
    }

    // 更新表单模型
    state.formModel.mesCollectionSchemeItemList = currentList;
    
    // 更新表单数据，触发表单刷新
    nextTick(() => {
      if (systemFormRef.value) {
        systemFormRef.value.setFieldsValue(state.formModel);
        // 触发表单更新事件，让SubForm组件重新渲染
        emits('update:value', state.formModel);
      }
    });
  }

  
  onMounted(async () => {
    try {
      if (props.fromPage == FromPageType.MENU) {
        setMenuPermission();
        // 更新SubForm配置，添加自定义新增逻辑
        updateSubFormConfig();
        if(currentRoute.value.meta){
          state.formInfo.formName = currentRoute.value.meta.title&&isString(currentRoute.value.meta.title)?currentRoute.value.meta.title:'';
          state.formInfo.formId = currentRoute.value.meta.formId&&isString(currentRoute.value.meta.formId)?currentRoute.value.meta.formId:'';
        }
        await createFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
        await nextTick();
        await loadFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
      } else if (props.fromPage == FromPageType.FLOW) {
        emits('loadingCompleted'); //告诉系统表单已经加载完毕
        // loadingCompleted后 工作流页面直接利用Ref调用setWorkFlowForm方法
      } else if (props.fromPage == FromPageType.PREVIEW) {
        // 预览 无需权限，表单事件也无需执行
      } else if (props.fromPage == FromPageType.DESKTOP) {
        // 桌面设计 表单事件需要执行
        emits('loadingCompleted'); //告诉系统表单已经加载完毕
        await createFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
        await loadFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
      }
    } catch (error) {}
  });
  // 根据菜单页面权限，设置表单属性（必填，禁用，显示）
  function setMenuPermission() {
    data.formDataProps.schemas = filterFormSchemaAuth(data.formDataProps.schemas!);
  }

  // 校验form 通过返回表单数据
  async function validate() {
    let values = [];
    try {
      values = await systemFormRef.value?.validate();
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
    } finally {
    }
    return values;
  }  
  // 根据行唯一ID查询行数据，并设置表单数据   【编辑】
  async function setFormDataFromId(rowId) {
    try {
    const record = await getMesCollectionScheme(rowId);
      setFieldsValue(record);
      state.formModel = record;
      // 编辑模式下，数据加载后需要重新更新SubForm配置
      updateSubFormConfig();
      await getFormDataEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：获取表单数据
    } catch (error) {
      
    }
  }
  // 辅助返回表单数据
  async function getFieldsValue() {
    let values = [];
    try {
      values = await systemFormRef.value?.getFieldsValue();
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
    } finally {
    }
    return values;
  }
  // 辅助设置表单数据
  function setFieldsValue(record) {
    systemFormRef.value.setFieldsValue(record);
  }
  // 重置表单数据
  async function resetFields() {
    await systemFormRef.value.resetFields();
  }
  //  设置表单数据全部为Disabled  【查看】
  async function setDisabledForm( ) {
    data.formDataProps.schemas = changeSchemaDisabled(cloneDeep(data.formDataProps.schemas));
  }
  // 获取行键值
  function getRowKey() {
    return RowKey;
  }
  // 更新api表单数据
  async function update({ values, rowId }) {
    try {
      values[RowKey] = rowId;
      state.formModel = values;
      let saveVal = await updateMesCollectionScheme(values);
      await submitFormEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true,  state.formInfo.formName,state.formInfo.formId); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 新增api表单数据
  async function add(values) {
    try {
      state.formModel = values;
      let saveVal = await addMesCollectionScheme(values);
      await submitFormEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true,  state.formInfo.formName,state.formInfo.formId); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 根据工作流页面权限，设置表单属性（必填，禁用，显示）
  async function setWorkFlowForm(obj: WorkFlowFormParams) { 
    try {
      if (obj.formId) state.formInfo.formId = obj.formId;
      if (obj.formName) state.formInfo.formName = obj.formName;
      let flowData = await changeWorkFlowForm(cloneDeep(formProps), obj);
      let { buildOptionJson, uploadComponentIds, formModels, isViewProcess } = flowData;
      data.formDataProps = buildOptionJson;
      emits('changeUploadComponentIds', uploadComponentIds); //工作流中必须保存上传组件id【附件汇总需要】
      if (isViewProcess) {
        setDisabledForm(); //查看
      }
      state.formModel = formModels;
      setFieldsValue(formModels);
      // 工作流模式下，数据加载后需要重新更新SubForm配置
      updateSubFormConfig();
    } catch (error) {}
    await createFormEvent(formEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
    await loadFormEvent(formEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
  }
  function handleChange(val) { 
    emits('update:value', val);
  }

   async function sendMessageForAllIframe() {
    try {
      if (systemFormRef.value && systemFormRef.value.sendMessageForAllIframe) {
        systemFormRef.value.sendMessageForAllIframe();
      }
    } catch (error) {}
  }
  defineExpose({
    setFieldsValue,
    resetFields,
    validate,
    add,
    update,
    setFormDataFromId,
    setDisabledForm,
    setMenuPermission,
    setWorkFlowForm,
    getRowKey,
    getFieldsValue,
    sendMessageForAllIframe,
  });
</script>

