<template>
  <SimpleForm
    ref="systemFormRef"
    :formProps="data.formDataProps"
    :formModel="{}"
    :isWorkFlow="props.fromPage!=FromPageType.MENU"
  />
</template>
<script lang="ts" setup>
import type { CascaderProps } from 'ant-design-vue';
  import { reactive, ref,onBeforeMount,onMounted,nextTick  } from 'vue';
  import { formProps, formEventConfigs ,formConfig} from './config';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { addLngBBank, getLngBBank, updateLngBBank, deleteLngBBank } from '/@/api/mdm/Bank';
  import { cloneDeep } from 'lodash-es';
  import { FormDataProps } from '/@/components/Designer/src/types';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useFormConfig } from '/@/hooks/web/useFormConfig';
  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 {  getTreeData, getTreeChild } from '/@/api/mdm/CountryRegion';
  const { filterFormSchemaAuth } = usePermission();
  const { mergeFormSchemas,mergeFormEventConfigs } = useFormConfig();
  const { currentRoute } = useRouter();

  const RowKey = 'id';
  const emits = defineEmits(['changeUploadComponentIds','loadingCompleted', 'form-mounted']);
  const props = defineProps({
    fromPage: {
      type: Number,
      default: FromPageType.MENU,
    },
  });
  const systemFormRef = ref();
  const data: { formDataProps: FormDataProps } = reactive({
    formDataProps: {schemas:[]} as FormDataProps,
  });
  const state = reactive({
    formModel: {},
  });
  
  let customFormEventConfigs=[];
  

  // 初始选项
const cascaderOptions = ref<CascaderProps['options']>([])
const cascaderKey = ref(0); // 用于强制重新渲染

// 动态加载数据
const loadData: CascaderProps['loadData']  = async (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  
  try {
    // 调用 API 获取子级数据
    const arr = reactive ([]);
    arr.value = [
    {
    "id": "1981158570698272770",
    "code": "11",
    "fullName": "中国",
    "regionTypeCode": "COUNTRY",
    "pid": "1980912427490508801",
    "fullPath": "亚洲中国",
    "valid": "Y",
    "note": "国这有",
    "createUserId": "1000000000000000000",
    "createDate": "2025-10-23 08:39:46",
    "modifyUserId": "1000000000000000000",
    "modifyDate": "2025-10-23 08:49:42",
    "tenantId": "1",
    "deptId": null,
    "ruleUserId": "1000000000000000000"
}
    ]
    // arr.value = await getTreeChild({
    //   pid: targetOption.id,
    // });
    console.log(arr.value, 889)
    targetOption.loading = false;
    targetOption.children = arr.value
    // .map(item => ({
    //   ...item,
    //   value: item.code,
    //   label: item.fullName,
    //   // isLeaf: !item.hasChildren,
    //   isLeaf: false, 
    //   children: item.children||[]
    // }));
    cascaderOptions.value = [...cascaderOptions.value]
    console.log(targetOption.children,8897)

  } catch (error) {
    targetOption.loading = false;
    console.error('加载数据失败:', error);
  }
};

// 初始化根节点数据
const initRootData = async () => {
  const data = reactive ([]);
  data.value = await getTreeChild({});
  console.log(data, 6767)
  cascaderOptions.value = data.value.map(item => ({
    ...item,
    // value: item.code,
    // label: item.fullName,
    // isLeaf: !item.hasChildren,
    isLeaf: false, 
    children: item.children||[]
  }));
  console.log(cascaderOptions.value, 888)
};
formProps.schemas= [
    {
      key: '1',
      field: 'code',
      label: '编码',
      type: 'input',
      component: 'Input',
      colProps: { span: 24 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: true,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '5fdaec7802364d16a979fc9d3218bbfa',
      field: 'fullName',
      label: '银行名称',
      type: 'input',
      component: 'Input',
      colProps: { span: 16 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入银行名称',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: true,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '2',
      field: 'shortName',
      label: '简称',
      type: 'input',
      component: 'Input',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入银行名称简称',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: true,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '38bd834c265446658be6f9784672e1ae',
      field: 'bankCode',
      label: '联行号',
      type: 'input',
      component: 'Input',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入联行号',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '4',
      field: 'regionCode',
      label: '所属国家/地区',
      type: 'cascader',
      component: 'Cascader',
      colProps: { span: 8 },
      defaultValue: [],
      componentProps: {
        key: cascaderKey,
        changeOnSelect: false,
        options: cascaderOptions,
        loadData,
        fieldNames: {label: 'fullName', value: 'code', children: 'children'},
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请选择',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '6461a5e152124abca28bd2114dd577e6',
      field: 'swift',
      label: 'SWIFT',
      type: 'input',
      component: 'Input',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入SWIFT',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '5',
      field: 'ib',
      label: '中转行',
      type: 'input',
      component: 'Input',
      colProps: { span: 16 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入中转行',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '6',
      field: 'ibSwift',
      label: '中转行SWIFT',
      type: 'input',
      component: 'Input',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入中转行SWIFT',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '7',
      field: 'routing',
      label: 'Routing',
      type: 'input',
      component: 'Input',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入Routing',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '8',
      field: 'soft',
      label: '显示顺序',
      type: 'input',
      component: 'InputNumber',
      colProps: { span: 8 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入显示顺序',
        maxlength: null,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
    {
      key: '714953d458d9402bb507893c92913d44',
      field: 'valid',
      label: '有效标志',
      type: 'select',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        width: '100%',
        span: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请选择下拉选择',
        sepTextField: '',
        showLabel: true,
        showSearch: false,
        clearable: false,
        disabled: true,
        staticOptions: [
          { key: 1, label: 'Option 1', value: 'Option 1' },
          { key: 2, label: 'Option 2', value: 'Option 2' },
          { key: 3, label: 'Option 3', value: 'Option 3' },
        ],
        defaultSelect: 'Y',
        datasourceType: 'dic',
        params: { itemId: '1978057078528327681' },
        labelField: 'name',
        valueField: 'value',
        apiConfig: {
          path: 'CodeGeneration/selection',
          method: 'GET',
          apiId: '93d735dcb7364a0f8102188ec4d77ac7',
        },
        dicOptions: [],
        required: false,
        rules: [],
        events: {},
        isShow: true,
        itemId: '1978057078528327681',
        style: { width: '100%' },
      },
    },
    {
      key: '9',
      field: 'note',
      label: '备注',
      type: 'input',
      component: 'InputTextArea',
      colProps: { span: 24 },
      defaultValue: '',
      componentProps: {
        width: '100%',
        span: '',
        defaultValue: '',
        labelWidthMode: 'fix',
        labelFixWidth: 120,
        responsive: false,
        respNewRow: false,
        placeholder: '请输入内容，最多200字',
        maxlength: 200,
        prefix: '',
        suffix: '',
        addonBefore: '',
        addonAfter: '',
        disabled: false,
        allowClear: false,
        showLabel: true,
        required: false,
        rules: [],
        events: {},
        isSave: false,
        isShow: true,
        scan: false,
        style: { width: '100%' },
      },
    },
  ]
  onMounted(async () => {
   await initRootData();
    // const treeData = await getTreeData({})
    // formProps.schemas?.forEach(v => {
    //   if (v.field == 'regionCode') {
    //     v.componentProps.options = cascaderOptions
    //     v.componentProps.loadData = loadData
    //   }
    // })
    console.log(formProps.schemas, 667)

    






    try {
      // 合并渲染覆盖配置中的字段配置、表单事件配置
      await mergeCustomFormRenderConfig();
      
      if (props.fromPage == FromPageType.MENU) {
        setMenuPermission();
        await createFormEvent(customFormEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas); //表单事件：初始化表单
        await loadFormEvent(customFormEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas); //表单事件：加载表单
      } 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(customFormEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas); //表单事件：初始化表单
        await loadFormEvent(customFormEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas); //表单事件：加载表单
      }
      emits('form-mounted', formProps);
    } catch (error) {

    }
  });
  

  async function mergeCustomFormRenderConfig() {
     let cloneProps=cloneDeep(formProps);
     let fEventConfigs=cloneDeep(formEventConfigs);
      if (formConfig.useCustomConfig) {
         if(props.fromPage !== FromPageType.FLOW){
              let formPath=currentRoute.value.query.formPath;
              //1.合并字段配置
              cloneProps.schemas=await mergeFormSchemas({formSchema:cloneProps.schemas!,formPath:formPath});
              //2.合并表单事件配置
              fEventConfigs=await mergeFormEventConfigs({formEventConfigs:fEventConfigs,formPath:formPath});
         }
      }
     data.formDataProps=cloneProps;
     customFormEventConfigs=fEventConfigs;
  }
  
  // 根据菜单页面权限，设置表单属性（必填，禁用，显示）
  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, skipUpdate) {
    try {
      let record = await getLngBBank(rowId);
      record = {...record, regionCode: (record.regionCode || []).split(',')}
      if (skipUpdate) {
          return record;
      }
      setFieldsValue(record);
      state.formModel = record;
      await getFormDataEvent(customFormEventConfigs, state.formModel, systemFormRef.value, formProps.schemas); //表单事件：获取表单数据
      return record;  
    } catch (error) {

    }
  }
  // 辅助设置表单数据
  function setFieldsValue(record) {
    systemFormRef.value.setFieldsValue(record);
  }
  // 重置表单数据
  async function resetFields() {
    await systemFormRef.value.resetFields();
  }
  //  设置表单数据全部为Disabled  【查看】
  async function setDisabledForm(isDisabled) {
    data.formDataProps.schemas = changeSchemaDisabled(cloneDeep(data.formDataProps.schemas),isDisabled);
  }
  // 获取行键值
  function getRowKey() {
    return RowKey;
  }
  // 更新api表单数据
  async function update({ values, rowId }) {
    try {
      values[RowKey] = rowId;
      state.formModel = values;
      let saveVal = await updateLngBBank({...values, regionCode: (values.regionCode||[]).join(',')});
      await submitFormEvent(customFormEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 新增api表单数据
  async function add(values) {
    try {
      state.formModel = values;
      let saveVal = await addLngBBank({...values, regionCode: (values.regionCode||[]).join(',')});
      await submitFormEvent(customFormEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 根据工作流页面权限，设置表单属性（必填，禁用，显示）
  async function setWorkFlowForm(obj: WorkFlowFormParams) {
    try {
      const cloneProps=cloneDeep(formProps);
      customFormEventConfigs=cloneDeep(formEventConfigs);
      if (formConfig.useCustomConfig) {
        const parts = obj.formConfigKey.split('_');
        const formId=parts[1];
        cloneProps.schemas=await mergeFormSchemas({formSchema:cloneProps.schemas!,formId:formId});
        customFormEventConfigs=await mergeFormEventConfigs({formEventConfigs:customFormEventConfigs,formId:formId});
      }
      
      let flowData = changeWorkFlowForm(cloneProps, obj);
      let { buildOptionJson, uploadComponentIds, formModels, isViewProcess } = flowData;
      data.formDataProps = buildOptionJson;
      emits('changeUploadComponentIds', uploadComponentIds); //工作流中必须保存上传组件id【附件汇总需要】
      if (isViewProcess) {
        setDisabledForm(); //查看
      }
      state.formModel = formModels;
      if(formModels[RowKey]) {
        setFormDataFromId(formModels[RowKey], false)
      } else {
        setFieldsValue(formModels)
      }
    } catch (error) {}
    await createFormEvent(customFormEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas); //表单事件：初始化表单
    await loadFormEvent(customFormEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas); //表单事件：加载表单
  }
  function getFormModel() {
      return systemFormRef.value.formModel
  }
  async function handleDelete(id) {
      return await deleteLngBBank([id]);
  }
  defineExpose({
    setFieldsValue,
    resetFields,
    validate,
    add,
    update,
    setFormDataFromId,
    setDisabledForm,
    setMenuPermission,
    setWorkFlowForm,
    getRowKey,
    getFormModel,
    handleDelete
  });
</script>