
<template>
  <div class="pt-4">
    <SimpleForm
      ref="systemFormRef"
      :formProps="data.formDataProps"
      :formModel="state.formModel"
      :isWorkFlow="props.fromPage!=FromPageType.MENU"
      :isCamelCase="true" 
      @model-change="handleChange"
    />
  </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 { addRokeProcess, getRokeProcess, updateRokeProcess } from '/@/api/jcsj/gxgl';
  import { getMesCollectionScheme } from '/@/api/jcsj/cjfa';
  import { cloneDeep, isString  } from 'lodash-es';
  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';
  
  const { filterFormSchemaAuth } = usePermission();

  const RowKey = 'id';
  const emits = defineEmits(['changeUploadComponentIds','loadingCompleted', 'update:value']);
  const props = defineProps({
    fromPage: {
      type: Number,
      default: FromPageType.MENU,
    },
  });
  const systemFormRef = ref();
  const data = reactive({
    formDataProps: cloneDeep(formProps) as any,
  });
  const state = reactive({
    formModel: {} as any,
    formInfo:{formId:'',formName:''},
    isUpdatingCollectionItems: false, // 防止编辑时触发更新
  });
  const { currentRoute } = useRouter();
  watch(
    () => state.formModel,
    (val) => { 
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );
  
  // 监听采集方案变化，实时更新采集项列表
  watch(
    () => state.formModel.collectionSchemeId,
    async (newVal, oldVal) => {
      // 如果正在更新采集项列表，则不处理（防止编辑时加载数据触发）
      if (state.isUpdatingCollectionItems) {
        return;
      }
      
      // 如果值没有变化，则不处理
      if (newVal === oldVal) {
        return;
      }
      
      // 如果采集方案为空，清空采集项列表
      if (!newVal) {
        state.formModel.mesProcessSchemeList = [];
        await nextTick();
        setFieldsValue({ mesProcessSchemeList: [] });
        return;
      }
      
      // 获取采集方案下的采集项列表
      await loadCollectionItemsByScheme(newVal);
    },
    {
      immediate: false,
      deep: false, // 不需要深度监听，只监听值的变化
    },
  );
  
  // 根据采集方案ID加载采集项列表
  async function loadCollectionItemsByScheme(schemeId: string | string[]) {
    // 处理采集方案可能是数组的情况（多选），取第一个
    const actualSchemeId = Array.isArray(schemeId) ? (schemeId.length > 0 ? schemeId[0] : '') : schemeId;
    
    if (!actualSchemeId) {
      state.formModel.mesProcessSchemeList = [];
      await nextTick();
      setFieldsValue({ mesProcessSchemeList: [] });
      return;
    }
    
    try {
      state.isUpdatingCollectionItems = true;
      
      // 先尝试通过采集方案详情获取采集项列表
      try {
        const schemeInfo: any = await getMesCollectionScheme(actualSchemeId);
        
        // 如果采集方案详情中包含采集项列表
        if (schemeInfo && schemeInfo.mesCollectionSchemeItemList && Array.isArray(schemeInfo.mesCollectionSchemeItemList)) {
          const collectionItems = schemeInfo.mesCollectionSchemeItemList;
          
          // 转换为 mesProcessSchemeList 格式
          const processSchemeList = collectionItems.map((item: any) => ({
            id: item.id || '',
            collectionSchemeId: actualSchemeId,
            bianMa8881: item.code || '', // 编码
            mingChen4867: item.name || '', // 名称
            mingChen3506: item.dataType || item.contentType || '', // 数据类型
            mingChen6235: item.required || '0', // 是否必填
            beiZhu2454: item.note || '', // 备注
            required: item.required || '0',
            note: item.note || '',
          }));
          
          // 更新表单数据
          state.formModel.mesProcessSchemeList = processSchemeList;
          // 使用 nextTick 确保数据更新后再设置到表单
          await nextTick();
          setFieldsValue({ mesProcessSchemeList: processSchemeList });
          return;
        }
      } catch (error) {
        console.warn('通过采集方案详情获取采集项列表失败，尝试其他方式', error);
      }
      
      // 如果采集方案详情中没有采集项列表，尝试通过采集项API获取
      // 注意：这里需要根据实际的API接口调整，可能需要通过其他方式获取
      // 暂时先尝试通过采集方案的详情接口，如果失败则清空列表
      state.formModel.mesProcessSchemeList = [];
      await nextTick();
      setFieldsValue({ mesProcessSchemeList: [] });
    } catch (error) {
      console.error('获取采集项列表失败', error);
      // 如果获取失败，清空列表
      state.formModel.mesProcessSchemeList = [];
      await nextTick();
      setFieldsValue({ mesProcessSchemeList: [] });
    } finally {
      // 确保在数据更新完成后再重置标志
      await nextTick();
      state.isUpdatingCollectionItems = false;
    }
  }
  
  onMounted(async () => {
    try {
      if (props.fromPage == FromPageType.MENU) {
        setMenuPermission();
        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: any = {};
    try {
      values = await systemFormRef.value?.validate() || {};
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component: any) => {
          values[component.bindField] = component.value;
        });
      }
    } finally {
    }
    return values;
  }  
  // 根据行唯一ID查询行数据，并设置表单数据   【编辑】
  async function setFormDataFromId(rowId) {
    try {
      // 编辑时设置标志，防止加载数据时触发采集方案变化监听
      state.isUpdatingCollectionItems = true;
      
      const record: any = await getRokeProcess(rowId);
      
      // 先设置表单数据
      setFieldsValue(record);
      // 再更新 formModel，这样 watch 不会在数据加载时触发
      state.formModel = record;
      
      // 等待数据设置完成
      await nextTick();
      
      // 如果编辑时没有采集项列表，但采集方案存在，则加载采集项列表
      if (record.collectionSchemeId && (!record.mesProcessSchemeList || record.mesProcessSchemeList.length === 0)) {
        // 加载采集项列表时，isUpdatingCollectionItems 已经在 loadCollectionItemsByScheme 中管理
        await loadCollectionItemsByScheme(record.collectionSchemeId);
      }
      
      await getFormDataEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：获取表单数据
    } catch (error) {
      console.error('加载表单数据失败', error);
    } finally {
      // 确保在数据加载完成后重置标志，允许后续的采集方案切换触发更新
      await nextTick();
      state.isUpdatingCollectionItems = false;
    }
  }
  // 辅助返回表单数据
  async function getFieldsValue() {
    let values: any = {};
    try {
      values = await systemFormRef.value?.getFieldsValue() || {};
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component: any) => {
          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 updateRokeProcess(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 addRokeProcess(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);
    } 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) { 
    // 保存旧的采集方案ID，用于判断是否发生变化
    const oldCollectionSchemeId = state.formModel.collectionSchemeId;
    
    // 同步更新 state.formModel，确保 watch 能监听到变化
    // 使用响应式的方式更新，确保能触发 watch
    if (val.collectionSchemeId !== undefined) {
      state.formModel.collectionSchemeId = val.collectionSchemeId;
    }
    // 更新其他字段
    Object.keys(val).forEach(key => {
      if (key !== 'collectionSchemeId') {
        state.formModel[key] = val[key];
      }
    });
    
    emits('update:value', val);
    
    // 如果采集方案发生变化，且不在更新状态，立即触发更新
    // 这样可以确保即使 watch 没有触发，也能更新采集项列表
    if (val.collectionSchemeId !== undefined && 
        val.collectionSchemeId !== oldCollectionSchemeId && 
        !state.isUpdatingCollectionItems) {
      nextTick(() => {
        if (!state.isUpdatingCollectionItems) {
          loadCollectionItemsByScheme(val.collectionSchemeId);
        }
      });
    }
  }
   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>

