<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 { addMesProductionTask, getMesProductionTask, updateMesProductionTask } from '/@/api/scgl/scrw';
import { getRokeRouting } from '/@/api/jcsj/gylx';
  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 { notification } from 'ant-design-vue';
  import axios from 'axios';
  import { getEnvConfig } from '/@/build/utils';
import { log } from 'node:console';

  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:''},
    isInitializing: false
  });
  const { currentRoute } = useRouter();
  watch(
    () => state.formModel,
    (val) => { 
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );

  // Watch for changes to BOM field and call API
  watch(
    () => state.formModel.bom,
    async (newBomId) => {
      if (newBomId && !state.isInitializing) {
        try {
          const apiUrl = import.meta.env.VITE_GLOB_API_URL || '';
          const response = await axios.get(apiUrl + '/magic-api/jcxx/wlxList', { params: { bomId: newBomId } });
          state.formModel.mesWarehouseMaterialList = []
          // Process API response data and assign to material list
          state.formModel.mesWarehouseMaterialList = response.data.data.map(item => ({
            wlbh: item.wlbh,
            wlmc: item.wlmc,
            blsl: item.wlsl,
            kcl: item.kcl,
            khbz: item.khbz,
            nkbz: item.nkbz,
            sftl: item.sftl,
            wlId: item.id
          }
        )
        );
          
          // state.formModel.mesWarehouseMaterialList = materialList;
        } catch (error) {
          notification.error({ message: '获取物料清单失败' });
        }
      }
    }
  );

  // Watch for changes to process route field and call API
  watch(
    () => state.formModel.gylx,
    async (newGylxId) => {
      if (newGylxId && !state.isInitializing) {
        try {
          const response = await getRokeRouting(newGylxId);
          
          // Assign the process list from API response to production order list with field mapping
          state.formModel.mesProductionGongdanList = response.rokeRoutingProcessList.map(item => ({
            gxbh: item.code, // 工序编号 → 工序编号
            gxmc: item.name, // 工序名称 → 工序名称
            gxId: item.processId // 工序ID → 工序ID
          }));
        } catch (error) {
          notification.error({ message: '获取工艺路线详情失败' });
        }
      }
    }
  );

  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 {
      state.isInitializing = true;
      const record = await getMesProductionTask(rowId);
      setFieldsValue(record);
      state.formModel = record;
      await getFormDataEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true, state.formInfo.formName, state.formInfo.formId); //表单事件：获取表单数据
    } catch (error) {
      
    } finally {
      state.isInitializing = false;
    }
  }
  // 辅助返回表单数据
  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 updateMesProductionTask(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 addMesProductionTask(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) {}
  }
  function handleChange(val) { 
    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>