<template>
  <div class="pt-4">
    <SimpleForm
      ref="systemFormRef"
      :formProps="data.formDataProps"
      :formModel="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/llzjd';
  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 { getRokeRouting } from '/@/api/jcsj/gylx';
  import { notification } from 'ant-design-vue';
  import axios from 'axios';

  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({
    formInfo: { formId: '', formName: '' },
  });
  let formModel = ref<any>({});
  const { currentRoute } = useRouter();
  watch(
    () => formModel,
    (val) => {
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );
  //监听质检方案变化
  watch(
    () => formModel.value.zjfa,
    async (newZjfaId) => {
      console.log(formModel.value);
      if (!newZjfaId) {
        formModel.value.mesQualityInspectionDetailList = [];
        return;
      }
      await handleZjfaChange(newZjfaId);
    },
  );
  //监听产品名称变化
  watch(
    () => formModel.value.cp,
    async (newCpflId, oldCpflId) => {
      if (newCpflId && newCpflId !== oldCpflId) {
        await handleCpflChange(newCpflId);
      }
    },
  );

  // 产品名称变化：根据产品分类ID查询对应的质检方案
  async function handleCpflChange(cpflId: string) {
    try {
      const response = await axios.get(
        import.meta.env.VITE_GLOB_API_URL + '/magic-api/zlgl/zjjcsj/getZjfaByCpfl',
        {
          params: { id: cpflId },
        },
      );

      const zjfaData = (response as any)?.data?.data;
      // return;
      if (zjfaData) {
        // 回填质检方案字段
        formModel.value.zjfa = zjfaData[0].id;

        // 手动触发一次质检方案变化的处理，带出质检明细
        // 由于watch是异步的，直接赋值会触发上面的zjfa监听
        // 但为了确保立即执行，可以手动调用
        // await handleZjfaChange(zjfaData[0].mc);
      } else {
        // 如果没有找到对应的质检方案，清空质检方案和相关明细
        formModel.value.zjfa = '';
        formModel.value.mesQualityInspectionDetailList = [];
      }
    } catch (error) {
      formModel.value.zjfa = '';
      formModel.value.mesQualityInspectionDetailList = [];
    }
  }

  // 质检方案变化：根据方案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 ?? [];
      formModel.value.mesQualityInspectionDetailList = Array.isArray(list)
        ? list.map((item: any) => ({
            bzz: item.bzz,
            bh: item.bh,
            zjxm: item.mc,
            bz: item.bz,
            jyyf: item.zjfs,
          }))
        : [];
    } catch (error) {
      if (seq !== zjfaReqSeq) return;
      console.error('获取质检方案详情失败:', error);
      notification.error({ message: '获取质检详情失败' });
      // 请求失败时，保持可预期：清空明细，避免展示旧方案的数据
      formModel.value.mesQualityInspectionDetailList = [];
    }
  }

  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,
          formModel,
          systemFormRef.value,
          formProps.schemas,
          true,
          state.formInfo.formName,
          state.formInfo.formId,
        ); //表单事件：初始化表单
        await nextTick();
        await loadFormEvent(
          formEventConfigs,
          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,
          formModel,
          systemFormRef.value,
          formProps.schemas,
          true,
          state.formInfo.formName,
          state.formInfo.formId,
        ); //表单事件：初始化表单
        await loadFormEvent(
          formEventConfigs,
          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);
      formModel.value = record;

      // 等待 DOM 更新完成后，如果 zjfa 存在，则手动触发处理
      await nextTick();
      if (record.zjfa) {
        handleZjfaChange(record.zjfa);
      }

      await getFormDataEvent(
        formEventConfigs,
        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;
      formModel.value = values;
      let saveVal = await updateMesDeQualityInspection(values);
      await submitFormEvent(
        formEventConfigs,
        formModel,
        systemFormRef.value,
        formProps.schemas,
        true,
        state.formInfo.formName,
        state.formInfo.formId,
      ); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 新增api表单数据
  async function add(values) {
    try {
      formModel.value = values;
      let saveVal = await addMesDeQualityInspection(values);
      await submitFormEvent(
        formEventConfigs,
        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, formModel, isViewProcess } = flowData;
      data.formDataProps = buildOptionJson;
      emits('changeUploadComponentIds', uploadComponentIds); //工作流中必须保存上传组件id【附件汇总需要】
      if (isViewProcess) {
        setDisabledForm(); //查看
      }
      formModel.value = formModel.values;
      setFieldsValue(formModel.values);
    } catch (error) {}
    await createFormEvent(
      formEventConfigs,
      formModel,
      systemFormRef.value,
      formProps.schemas,
      true,
      state.formInfo.formName,
      state.formInfo.formId,
    ); //表单事件：初始化表单
    await loadFormEvent(
      formEventConfigs,
      formModel,
      systemFormRef.value,
      formProps.schemas,
      true,
      state.formInfo.formName,
      state.formInfo.formId,
    ); //表单事件：加载表单
  }
  function handleChange(val) {
    // 新增/编辑弹窗内字段变化时，同步 formModel，确保 watch(zjfa) 能触发联动更新明细
    formModel.value = 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>
