
<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 { addMesDeQualityInspection, getMesDeQualityInspection, updateMesDeQualityInspection } from '/@/api/zlgl/cprkzjd';
  import { cloneDeep, isString  } from 'lodash-es';
  import { FormDataProps } from '/@/components/Designer/src/types';
  import { usePermission } from '/@/hooks/web/usePermission';
  import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  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 axios from 'axios';
  import { notification } from 'ant-design-vue';
  
  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: { formDataProps: FormDataProps } = reactive({
    formDataProps: cloneDeep(formProps),
  });
  const state = reactive({
    formModel: {},
    formInfo:{formId:'',formName:''}
  });
  const { currentRoute } = useRouter();
  watch(
    () => state.formModel,
    (val) => { 
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );

  // 质检方案联动：根据方案id从接口获取明细，并整体替换当前明细列表
  let zjfaReqSeq = 0;
  async function handleZjfaChange(zjfaId: string) {
    const seq = ++zjfaReqSeq;
    try {
      const resp = await axios.get(
        import.meta.env.VITE_GLOB_API_URL + '/magic-api/zlgl/zjjcsj/getFaById',
        { params: { id: zjfaId } },
      );
      // 若请求已过期（用户快速切换了方案），丢弃旧响应，避免串台
      if (seq !== zjfaReqSeq) return;
      const list = (resp as any)?.data?.data ?? [];
      // 用接口返回 data 列表整体替换当前明细
      const detailList = Array.isArray(list)
        ? list.map((item: any) => ({
            bzz: item.bzz,
            bh: item.bh,
            zjxm: item.mc,
            bz: item.bz,
            jyyf: item.zjfs,
          }))
        : [];

      // 用"整对象替换"触发表单/子表重新渲染（很多实现只监听 formModel 引用变化）
      const nextModel = {
        ...(state.formModel as any),
        mesQualityInspectionDetailList: detailList,
      };
      state.formModel = nextModel;

      // 显式同步到表单实例（SubForm 需要 setFieldsValue 才会立刻刷新）
      systemFormRef.value?.setFieldsValue?.(nextModel);
    } catch (error) {
      if (seq !== zjfaReqSeq) return;
      console.error('获取质检方案详情失败:', error);
      notification.error({ message: '获取质检详情失败' });
      state.formModel = { ...(state.formModel as any), mesQualityInspectionDetailList: [] };
      systemFormRef.value?.setFieldsValue?.({ mesQualityInspectionDetailList: [] });
    }
  }

  // 监听质检方案字段，选择/切换方案时刷新质检明细列表
  watch(
    () => (state.formModel as any)?.zjfa,
    async (newZjfaId) => {
      if (!newZjfaId) {
        state.formModel = { ...(state.formModel as any), mesQualityInspectionDetailList: [] };
        systemFormRef.value?.setFieldsValue?.({ mesQualityInspectionDetailList: [] });
        return;
      }
      await handleZjfaChange(newZjfaId);
    },
  );
  
  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 = [];
    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 getMesDeQualityInspection(rowId);
      setFieldsValue(record);
      state.formModel = record;
      await getFormDataEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：获取表单数据

      // 打开编辑弹窗时：用当前方案id刷新明细（放在 getFormDataEvent 后，避免被其覆盖）
      await nextTick();
      const zjfaId = (state.formModel as any)?.zjfa;
      if (zjfaId) {
        await handleZjfaChange(zjfaId);
      }
    } 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 updateMesDeQualityInspection(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 addMesDeQualityInspection(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) { 
    // 新增/编辑弹窗字段变化时，同步 formModel，确保 watch(zjfa) 能触发联动
    state.formModel = 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>

