<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :canFullscreen="false"
    :draggable="false"
    :showCancelBtn="!isDetail"
    :showOkBtn="!isDetail"
    :title="getTitle"
    @ok="ModalSureClick"
    width="80%"
    :closeFunc="closeFunc"
    :destroyOnClose="true"
  >
    <ImagePreview  style="width:100%;height:" v-if="isShowImagePreview" :globalImagePreviewUrl="globalImagePreviewUrl" @closeImagePreview="closeImagePreview"></ImagePreview>

    <template v-if="tabsColumns.length > 1">
      <a-tabs style="width: 100%" @change="tabsChange">
        <a-tab-pane v-for="(colItem, index) in tabsColumns" :tab="colItem.label" :key="index">
          <BasicForm
            ref="myDataBaseFormRef"
            @register="registerForm"
            @click="codeClickFunction('beforeSetData', beforeSetData)"
            @change="codeClickFunction('changeDataEvent', changeDataEvent)"
          >
            <template #CardGroup>
              <CardGourp
                v-if="cardGroupData.length > 0 && cardGroupData[index]"
                :data="cardGroupData[index]"
                :formData="cardGourpFormData"
                :parentValue="cardGroupData[index].field"
                :callModal="true"
              />
            </template>
          </BasicForm>
          <template v-for="(item, useIndex) in createOrModifyList[index]" :key="useIndex">
            <CreateOrModifyComponent
              :data="item"
              :createOrModifyData="createOrModifyData"
              :isUpdate="isUpdate"
              :isDetail="isDetail"
            />
          </template>
          <template v-for="(button_item, button_index) in gridButtonLayout" :key="button_index">
            <a-row style="width: 100%">
              <a-col :span="button_item?.item?.colProps?.span || 24" style="padding: 10px">
                <a-button
                  v-if="button_item.tabValue == colItem.value"
                  :type="button_item.item.componentProps.type"
                  :shape="button_item.item.componentProps.shape"
                  :size="button_item.item.componentProps.size"
                  @click="codeClickFunction('codeClick', button_item.item.componentProps.clickCode)"
                >
                  <template #icon v-if="button_item.item.componentProps.icon">
                    <Icon :icon="button_item.item.componentProps.icon" />
                  </template>
                  {{ button_item.item.label }}
                </a-button>
              </a-col>
            </a-row>
          </template>
        </a-tab-pane>
      </a-tabs>
    </template>

    <BasicForm
      ref="myDataBaseFormRef"
      @register="registerForm"
      v-if="formModalVisible && tabsColumns.length < 1"
      @click="codeClickFunction('beforeSetData', beforeSetData)"
      @change="codeClickFunction('changeDataEvent', changeDataEvent)"
    >
      <template #CardGroup>
        <CardGourp
          v-if="cardGroupData.length > 0"
          :data="cardGroupData[0]"
          :formData="cardGourpFormData"
          :parentValue="cardGroupData[0].field"
          :callModal="true"
        />
      </template>
    </BasicForm>
    <template v-for="(item, index) in cardLayout" :key="index">
      <a-row style="width: 100%">
        <a-col :span="item?.colProps?.span || 24" style="padding: 10px">
          <a-card
            :title="item.label"
            :class="
              item.shadow === 'always' ? 'card-always' : item.shadow === 'hover' ? 'card-hover' : ''
            "
          >
            <template v-for="(childItem, childIndex) in item.columns[0].children" :key="childIndex">
              <a-row style="width: 100%; margin-bottom: 10px">
                <a-col :span="childItem?.colProps?.span || 24">
                  <CallModalFormItem :data="childItem" :dataKey="item.field" :values="cardValues" />
                </a-col>
              </a-row>
            </template>
          </a-card>
        </a-col>
      </a-row>
    </template>
    <template v-for="(item, index) in buttonLayout" :key="index">
      <a-row style="width: 100%">
        <a-col :span="item?.colProps?.span || 24" style="padding: 10px">
          <a-button
            :type="item.componentProps.type"
            :shape="item.componentProps.shape"
            :size="item.componentProps.size"
            @click="codeClickFunction('codeClick', item.componentProps.clickCode)"
          >
            <template #icon v-if="item.componentProps.icon">
              <Icon :icon="item.componentProps.icon" />
            </template>
            {{ item.label }}
          </a-button>
        </a-col>
      </a-row>
    </template>
    <a-table
      class="sub-table"
      :columns="subTableColumns"
      :data-source="subTableList"
      :pagination="false"
      v-if="subTableId"
      :scroll="scrollValue"
    >
      <template #headerCell="{ column, record }">
        <template v-if="column.key === 'setting'">
          <PlusOutlined class="icon-button" @click="addListItem" v-if="!isDetail" />
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'setting'">
          <DeleteOutlined
            class="icon-button"
            @click="delListItem(column, record)"
            v-if="!isDetail"
          />
        </template>
        <template v-else>
          <FormItem :data="column" :record="record" />
        </template>
      </template>
    </a-table>
    <!-- todo  创建/修改  人/时间 -->
    <template v-if="!(tabsColumns.length > 1)">
      <template v-for="(item, index) in createOrModifyList" :key="index">
        <CreateOrModifyComponent :data="item" :createOrModifyData="createOrModifyData" />
      </template>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { unref, ref, reactive,watch } from 'vue';
  import { FormSchema } from '@/components/Table';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { saveFormsData } from '@/api/formrender/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { create, saveDraft } from '@/api/sys/WFProcess';
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { v4 as uuidv4 } from 'uuid';
  import FormItem from './ShowFormModal/FormItem/index.vue';
  import CallModalFormItem from './CallModalFormItem/index.vue';
  import { CardGourp } from '@/components/FormViewer/index.ts';
  import { subTableStore } from '@/store/modules/subTable';
  import { changeCardStructure, cardNestStructure } from '@/views/demo/onlineform/util.ts';
  import CreateOrModifyComponent from '@/views/demo/onlineform/formCall/CreateOrModifyComponent/index.vue';
  import dayjs from 'dayjs';
  import Icon from '@/components/Icon/Icon.vue';

  import { storeToRefs } from 'pinia';
  import ImagePreview from "@/components/Upload/src/components/image_preview.vue";
  import { userFormFileStore } from '@/store/modules/formFileUrl';
  const subTableDataStore = subTableStore();

  // import FormRender from '@/views/demo/form-design/components/VFormCreate/components/FormRender.vue';

  const emit = defineEmits(['success']);
  const { createMessage } = useMessage();
  const formModalVisible = ref(false);
  const isUpdate = ref(true);
  const isDetail = ref(true);
  const getTitle = ref();
  const primaryQuery = ref();
  const addQuery: any = ref([]);
  const formColumns: any = ref([]);
  const tabsColumns: any = ref([]);
  const flowCode = ref('');
  const userStore = useUserStore();
  const userInfo: any = userStore.getUserInfo;
  const formData = reactive({
    userId: userInfo.id,
    title: '',
  });
  const cardGroupData = ref([]);
  const cardGourpFormData = ref({});
  const cardGroupValues = ref({});
  const subTableId = ref(null);
  const subTableColumns: any = ref([]);
  const subTableData = ref([]);
  const subTableList: any = ref([]);
  const scrollValue = ref();
  const cardLayout = ref([]);
  const createOrModifyList = ref([]);
  const createOrModifyData = ref({});
  // 按钮
  const gridButtonLayout: any = ref([]);
  const buttonLayout = ref([]);
  // 脚本
  const cardValues = ref({});
  const beforeSetData = ref('');
  const afterValidateForm = ref('');
  const afterSaveEvent = ref('');
  const changeDataEvent = ref('');
  const getCardLayoutKey = (dataList, key) => {
    dataList.forEach((item) => {
      if (item.component === 'Card') {
        getCardLayoutKey(item.columns[0].children, key);
      } else if (item.type === 'subTable') {
        cardValues.value[key][item.field] = [];
      } else {
        cardValues.value[key][item.field] = '';
      }
    });
  };
  const getCardGroupLayoutKey = (dataList) => {
    console.log('dataList', dataList);
    dataList.children.forEach((item?) => {
      if (['CardGroup'].includes(item.component)) {
        cardGroupValues.value[item.field] = '';
        item.componentProps.options.forEach((childItem) => {
          getCardGroupLayoutKey(childItem);
        });
      } else {
        cardGroupValues.value[item.field] = '';
      }
    });
  };
  const [registerModal, { setModalProps, closeModal }] = useModalInner((data: any) => {
    cardLayout.value = [];
    subTableDataStore.clearGoupData();
    console.log('daaaaa', data);
    // 脚本
    beforeSetData.value = data?.beforeSetData;
    afterValidateForm.value = data?.afterValidateForm;
    afterSaveEvent.value = data?.afterSaveEvent;
    changeDataEvent.value = data?.changeDataEvent;

    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.isDetail;
    const arr: FormSchema[] = [];
    data.tab.forEach((item) => {
      if (item.field == 'Tabs') {
        let arrayLength = item.componentProps.options.length;
        for (let i = 0; i < arrayLength; i++) {
          createOrModifyList.value.push([]);
        }
        item.componentProps.options.forEach((val, index) => {
          val.children.forEach((opt) => {
            if (opt.rules !== undefined) {
              let myString = opt.rules[0].pattern;
              const lastCharacter = myString.charAt(myString.length - 1);
              if (lastCharacter === 'i' || lastCharacter === 's') {
                opt.rules[0].pattern = new RegExp(opt.rules[0].pattern.slice(1, -2), lastCharacter);
              } else {
                opt.rules[0].pattern = new RegExp(opt.rules[0].pattern.slice(1, -1));
              }
            }
            if (opt.component === 'Card') {
              cardLayout.value.push(opt);
            }
            if (opt.component === 'CardGroup') {
              opt.slot = 'CardGroup';
              if (cardGroupData.value.length !== index) {
                cardGroupData.value.push(null);
              }
              cardGroupData.value.push(opt);
            }
            if (opt.component === 'Button') {
              gridButtonLayout.value.push({
                tabValue: val.value,
                item: opt,
              });
            }
            if (['createuser', 'createtime', 'modifyuser', 'modifytime'].includes(opt.type)) {
              createOrModifyList.value[index].push(opt);
            }
            if (opt.component === 'Transfer') {
              opt.componentProps.render = (item) => `${item.title} ${item.description}`;
              if (unref(isUpdate) && !unref(isDetail)) {
                opt.componentProps.targetKeys = JSON.parse(
                  data.record[item.field]?.replace(/\r\n/g, ''),
                );
              }
            }
            if (opt.component === 'RangePicker') {
              if (unref(isUpdate) && !unref(isDetail)) {
                if (typeof data.record[opt.field] == 'string') {
                  data.record[opt.field] = JSON.parse(
                    data.record[opt.field]?.replace(/\r\n/g, '') || data.record[opt.field],
                  );
                }
              }
            }
            subTableColumns.value = [
              {
                dataIndex: 'setting',
                key: 'setting',
                fixed: 'left',
                width: 60,
              },
            ];

            if (opt.type === 'subTable') {
              subTableId.value = opt.field;
              let tableData = [];
              opt.columns.forEach((itemColumn) => {
                itemColumn.children.forEach((itemColumnChild) => {
                  tableData.push(itemColumnChild);
                  subTableColumns.value.push({
                    key: itemColumnChild.field,
                    title: itemColumnChild.label,
                    dataIndex: itemColumnChild.field,
                    ...itemColumnChild,
                    width: 120,
                  });
                });
              });
              scrollValue.value = { x: (subTableColumns.value.length - 1) * 140, y: 300 };
              subTableData.value = tableData;
            }
            if (opt.columns) {
              opt.columns.forEach((itemColumn) => {
                itemColumn.children.forEach((itemColumnChild) => {
                  console.log('itemColumnChild', itemColumnChild);
                  itemColumnChild.itemProps.hidden = true;
                  if (index == 0) {
                    itemColumnChild.itemProps.hidden = false;
                  }
                  itemColumnChild.colProps.span = itemColumn.span;
                  arr.push(itemColumnChild);
                  // arr.push({
                  //   parentValue: index,
                  //   ...itemColumnChild,
                  //   show: index == 0 ? true : false,
                  // });
                  val.children.push(itemColumnChild);
                });
              });
            }

            opt.itemProps.hidden = true;
            if (index == 0) {
              opt.itemProps.hidden = false;
            }
            if (opt.ptype !== 'gridlayout') {
              arr.push(opt);
              // arr.push({
              //   parentValue: index,
              //   ...opt,
              //   show: index == 0 ? true : false,
              // });
            }
            // arr.forEach((arrcol) => {
            //   if (arrcol.component === 'CardGroup') {
            //     arrcol.label = '';
            //   }
            // });
            formColumns.value = arr;
          });
        });
        tabsColumns.value = item.componentProps.options;
        console.log('tabsColumns', tabsColumns.value);
        console.log('formColumns1', formColumns.value);
      } else {
        if (item.rules !== undefined) {
          let myString = item.rules[0].pattern;
          const lastCharacter = myString.charAt(myString.length - 1);
          if (lastCharacter === 'i' || lastCharacter === 's') {
            item.rules[0].pattern = new RegExp(item.rules[0].pattern.slice(1, -2), lastCharacter);
          } else {
            item.rules[0].pattern = new RegExp(item.rules[0].pattern.slice(1, -1));
          }
        }
        if (item.columns && item.component !== 'Card') {
          item.columns.forEach((col) => {
            col.children.forEach((chld) => {
              chld.colProps.span = col.span;
              arr.push(chld);
            });
          });
        } else {
          if (item.ptype !== 'gridlayout') {
            arr.push(item);
          }
        }
        // arr.forEach((arrcol) => {
        //   if (arrcol.component === 'CardGroup') {
        //     arrcol.label = '';
        //   }
        // });
        formColumns.value = arr;
        if (item.component === 'Card') {
          cardLayout.value.push(item);
        }
        if (item.component === 'CardGroup') {
          item.slot = 'CardGroup';
          cardGroupValues.value[item.field] = '';
          item.componentProps.options.forEach((childItem) => {
            getCardGroupLayoutKey(childItem);
          });
          cardGroupData.value.push(item);
        }
        if (item.component === 'Button') {
          buttonLayout.value.push(item);
        }
        if (['createuser', 'createtime', 'modifyuser', 'modifytime'].includes(item.type)) {
          createOrModifyList.value.push(item);
        }
        if (item.component === 'Transfer') {
          item.componentProps.render = (item) => `${item.title} ${item.description}`;
          if (unref(isUpdate) && !unref(isDetail)) {
            item.componentProps.targetKeys = JSON.parse(
              data.record[item.field]?.replace(/\r\n/g, ''),
            );
          }
        }
        if (item.component === 'RangePicker') {
          if (unref(isUpdate) && !unref(isDetail)) {
            if (typeof data.record[item.field] == 'string') {
              data.record[item.field] = JSON.parse(
                data.record[item.field]?.replace(/\r\n/g, '') || data.record[item.field],
              );
            }
          }
        }
        subTableColumns.value = [
          {
            dataIndex: 'setting',
            key: 'setting',
            fixed: 'left',
            width: 60,
          },
        ];

        if (item.type === 'subTable') {
          subTableId.value = item.field;
          let tableData = [];
          item.columns.forEach((itemColumn) => {
            itemColumn.children.forEach((itemColumnChild) => {
              tableData.push(itemColumnChild);
              subTableColumns.value.push({
                key: itemColumnChild.field,
                title: itemColumnChild.label,
                dataIndex: itemColumnChild.field,
                ...itemColumnChild,
                width: 120,
              });
            });
          });
          scrollValue.value = { x: (subTableColumns.value.length - 1) * 140, y: 300 };
          subTableData.value = tableData;
        }
      }
      if (item.component === 'Card') {
        cardValues.value[item.field] = {};
        getCardLayoutKey(item.columns[0].children, item.field);
      }
    });

    if (!unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '新增';
      data.btnList.forEach((element) => {
        if (element.prop === 'Add' && element.isWFlow) {
          flowCode.value = element.wFlowCode;
        }
      });
    }
    if (unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '编辑';
      Object.keys(data.infoUseMainTableData).forEach((itemKey) => {
        if (itemKey.indexOf('_time_') !== -1 || itemKey.indexOf('_user_') !== -1) {
          createOrModifyData.value[itemKey] = data.infoUseMainTableData[itemKey];
        }
      });
      data.btnList.forEach((element) => {
        if (element.prop === 'Edit' && element.isWFlow) {
          flowCode.value = element.wFlowCode;
        }
      });
      if (Object.keys(cardValues.value).length > 0) {
        Object.keys(cardValues.value).forEach((cardItem) => {
          let cardItemKeyList = Object.keys(cardValues.value[cardItem]);
          Object.keys(data.infoUseMainTableData).forEach((item) => {
            if (cardItemKeyList.includes(item)) {
              cardValues.value[cardItem][item] = data.infoUseMainTableData[item];
            }
          });
          // todo
          cardItemKeyList.forEach((item) => {
            if (item.indexOf('grid') !== -1) {
              cardValues.value[cardItem][item] = data.infoUseSubTableData;
            }
          });
        });
      }
      Object.keys(cardGroupValues.value).forEach((item) => {
        cardGroupValues.value[item] = data.infoUseMainTableData[item];
      });
      subTableDataStore.setGroupData(cardGroupValues.value);
    }
    if (!unref(isUpdate) && unref(isDetail)) {
      getTitle.value = '详情';
      Object.keys(data.infoUseMainTableData).forEach((itemKey) => {
        if (itemKey.indexOf('_time_') !== -1 || itemKey.indexOf('_user_') !== -1) {
          createOrModifyData.value[itemKey] = data.infoUseMainTableData[itemKey];
        }
      });
      let isTabs = false;
      data.tab = changeCardStructure(data.tab);
      data.tab.forEach((itemComponent) => {
        if (itemComponent.component === 'Tabs') {
          isTabs = true;
          itemComponent.componentProps.options.forEach((itemChild) => {
            itemChild.children.forEach((itemChildComponent) => {
              if (itemChildComponent.component) {
                itemChildComponent.componentProps.disabled = true;
              }
            });
          });
        } else if (itemComponent.component) {
          itemComponent.componentProps.disabled = true;
        }
      });
      if (isTabs) {
        data.tab = data.tab[0];
        data.tab.componentProps.options = data.tab.componentProps.options.map((item) => {
          return {
            value: item.value,
            label: item.label,
            schemas: item.children,
          };
        });
        data.tab.componentProps.options = cardNestStructure(data.tab.componentProps.options);
        data.tab.componentProps.options = data.tab.componentProps.options.map((item) => {
          return {
            value: item.value,
            label: item.label,
            children: item.schemas,
          };
        });
        tabsColumns.value = data.tab.componentProps.options;
      } else {
        data.tab = cardNestStructure(data.tab);
      }
      if (Object.keys(cardValues.value).length > 0) {
        Object.keys(cardValues.value).forEach((cardItem) => {
          let cardItemKeyList = Object.keys(cardValues.value[cardItem]);
          Object.keys(data.infoUseMainTableData).forEach((item) => {
            if (cardItemKeyList.includes(item)) {
              cardValues.value[cardItem][item] = data.infoUseMainTableData[item];
            }
          });
          // todo
          cardItemKeyList.forEach((item) => {
            if (item.indexOf('grid') !== -1) {
              cardValues.value[cardItem][item] = data.infoUseSubTableData;
            }
          });
        });
      }
      Object.keys(cardGroupValues.value).forEach((item) => {
        cardGroupValues.value[item] = data.infoUseMainTableData[item];
      });
      subTableDataStore.setGroupData(cardGroupValues.value);
    }
    formModalVisible.value = true;
    primaryQuery.value = data.query;
    if (data.record) {
      setTimeout(() => {
        setFieldsValue({
          ...data.record,
        });
      }, 100);
      subTableList.value = data.recordChildren;
    } else {
      if (tabsColumns.value.length < 1) {
        // resetFields();
      }
      subTableList.value = [];
    }
    addQuery.value = [];
    if (data.addParams) {
      data.addParams.forEach((item) => {
        addQuery.value.push({
          type: item.type,
          field: item.field,
          value: generateUniqueDigits(20).join(''),
        });
      });
      console.log('addQuery', addQuery);
    }
  });

  async function tabsChange(e) {
    const columns: FormSchema[] = [];
    tabsColumns.value.forEach((item) => {
      item.children.forEach((val) => {
        val.itemProps.hidden = true;
      });
    });
    tabsColumns.value[e].children.forEach((item) => {
      item.itemProps.hidden = false;
    });
    // formColumns.value.forEach((element) => {
    //   element.show = false;
    //   if (element.parentValue == e) {
    //     element.show = true;
    //   }
    // });
    tabsColumns.value.forEach((item) => {
      item.children.forEach((val) => {
        columns.push(val);
      });
    });
    setTimeout(() => {
      updateSchema(columns);
      resetFields();
    }, 100);
    if (!isDetail.value) {
      const obj = await validate();
      setTimeout(() => {
        setFieldsValue(obj);
      }, 500);
    }
  }
  function generateUniqueDigits(length: number): number[] {
    const digits = new Set<number>();
    while (digits.size < length) {
      const randomDigit = Math.floor(Math.random() * 20);
      digits.add(randomDigit);
    }
    return Array.from(digits);
  }
  const addListItem = () => {
    let keyValue = uuidv4();
    let emptyItem = { key: keyValue };
    subTableData.value.map((item) => {
      if (item.component == 'InputGuid') {
        emptyItem[item.field] = keyValue;
      } else {
        emptyItem[item.field] = '';
      }
    });

    subTableList.value.push(emptyItem);
  };
  const delListItem = (column, record) => {
    subTableList.value = subTableList.value.filter((item) => item.key != record.key);
  };

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue }] =
    useForm({
      labelWidth: 100,
      schemas: formColumns,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    });
  //表单填写数据
  async function ModalSureClick() {
    try {
      let values = await validate();
      // 将老创建人创建时间赋值
      values = { ...values, ...createOrModifyData.value };
      // 添加校验后脚本
      let cardValueList = Object.values(cardValues.value);
      cardValueList.forEach((item) => {
        values = { ...values, ...item };
      });
      Object.keys(values).forEach((itemKey) => {
        if (!isUpdate.value) {
          if (itemKey.indexOf('_time_') !== -1)
            values[itemKey] = dayjs().format('YYYY-MM-DD HH:mm:ss');
          if (itemKey.indexOf('_user_') !== -1)
            values[itemKey] = localStorage.getItem('fireUserLoginName');
        } else {
          if (itemKey.indexOf('_modify_time') !== -1)
            values[itemKey] = dayjs().format('YYYY-MM-DD HH:mm:ss');
          if (itemKey.indexOf('_modify_user') !== -1)
            values[itemKey] = localStorage.getItem('fireUserLoginName');
        }
      });
      codeClickFunction('afterValidateForm', afterValidateForm.value);
      console.log('values', values);
      let query = values;
      let saveSubTableList = [];
      subTableList.value.forEach((item) => {
        let emptyObj = {};
        for (const key in item) {
          if (key === 'key') continue;
          emptyObj[key] = item[key];
        }
        saveSubTableList.push(emptyObj);
      });
      if (subTableId.value) {
        query[subTableId.value] = JSON.stringify(saveSubTableList);
      }
      let params: any = {
        schemeId: primaryQuery.value.id,
        isUpdate: isUpdate.value,
        pkey: primaryQuery.value.key,
      };
      console.log('params', params);
      if (unref(isUpdate)) {
        params.pkeyValue = primaryQuery.value.keyValue;
      } else {
        addQuery.value.forEach((item) => {
          if (item.type == 'main') {
            params.pkeyValue = item.value;
          }
          if (!query[item.field]) {
            query[item.field] = item.value;
          }
        });
      }
      query = { ...query, ...subTableDataStore.getGroupData };
      params.data = JSON.stringify(query);
      console.log('query222', query);
      console.log('params222', params);
      const data = await saveFormsData(params);
      if (data) {
        setModalProps({ confirmLoading: true });
        emit('success');
        if (flowCode.value == '') {
          closeModal();
        } else {
          handleCreateFlow(params.pkeyValue);
        }
        return createMessage.success('操作成功');
      } else {
        return createMessage.error('操作失败');
      }
    } finally {
      setModalProps({ confirmLoading: false });
      // 添加保存后脚本
      codeClickFunction('afterSaveEvent', afterSaveEvent.value);
      closeFunc();
    }
  }
  async function handleCreateFlow(processId) {
    var querys = {
      schemeCode: flowCode.value,
      userId: formData.userId,
      title: formData.title,
      processId: processId,
    };
    const draft = await saveDraft(querys);
    if (draft) {
      querys.schemeCode = '';
      const data = await create(querys);
      if (data) {
        closeModal();
        return createMessage.success('发起流程成功');
      } else {
        return createMessage.error('发起流程失败');
      }
    } else {
      return createMessage.error('保存草稿失败');
    }
  }
  // 脚本执行方法
  async function codeClickFunction(code, codeClick) {
    try {
      if (codeClick) {
        // 动态导入utils模块
        const { utils } = await import('./utils');
        let callModalData = {
          formModalVisible: formModalVisible,
          isUpdate: isUpdate,
          isDetail: isDetail,
          getTitle: getTitle,
          primaryQuery: primaryQuery,
          addQuery: addQuery,
          formColumns: formColumns,
          tabsColumns: tabsColumns,
          flowCode: flowCode,
          formData: formData,
          subTableId: subTableId,
          subTableColumns: subTableColumns,
          subTableData: subTableData,
          subTableList: subTableList,
          scrollValue: scrollValue,
          cardLayout: cardLayout,
          createOrModifyList: createOrModifyList,
          buttonLayout: buttonLayout,
          gridButtonLayout: gridButtonLayout,
          record: isUpdate.value ? getFieldsValue() : {},
          cardValues: cardValues,
        };
        utils.setCallModalData(callModalData);
        eval(codeClick);
      }
    } catch (e) {
      switch (code) {
        case 'codeClick':
          createMessage.success('【按钮组件脚本】错误：' + e);
          break;
        case 'beforeSetData':
          createMessage.success('【添加赋值前脚本】错误：' + e);
          break;
        case 'afterValidateForm':
          createMessage.success('【添加校验后脚本】错误：' + e);
          break;
        case 'afterSaveEvent':
          createMessage.success('【添加保存后脚本】错误：' + e);
          break;
        case 'changeDataEvent':
          createMessage.success('【添加数据改变脚本】错误：' + e);
          break;
        default:
          createMessage.success('【未知脚本】错误：' + e);
          break;
      }
    }
  }
  const closeFunc = () => {
    buttonLayout.value = [];
    gridButtonLayout.value = [];
    // cardLayout.value = [];
    createOrModifyList.value = [];
    return true;
  };


  // 图片预览
const isShowImagePreview = ref<Boolean>(false);
const closeImagePreview = ()=>{
  isShowImagePreview.value = false;
}
const globalImagePreviewUrl=ref<String>();
const formFileStore = userFormFileStore();
const formFileState = storeToRefs(formFileStore);
watch(formFileState.url, (newValue, oldValue) => {
  isShowImagePreview.value = true;
  globalImagePreviewUrl.value = newValue;
});

</script>
