<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :canFullscreen="false"
    :draggable="false"
    :showCancelBtn="!isDetail"
    :showOkBtn="!isDetail"
    :title="getTitle"
    @ok="ModalSureClick"
  >
    <BasicForm ref="myDataBaseFormRef" @register="registerForm" v-if="formModalVisible" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { unref, ref } 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';

  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: FormSchema[] = [];
  const [registerModal, { setModalProps, closeModal }] = useModalInner((data: any) => {
    console.log('daaaaa', data);
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.isDetail;
    data.tab.forEach((item) => {
      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));
        }
      }
      formColumns.push(item);
    });
    if (!unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '新增';
    }
    if (unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '编辑';
    }
    if (!unref(isUpdate) && unref(isDetail)) {
      getTitle.value = '详情';
    }
    formModalVisible.value = true;
    primaryQuery.value = data.query;
    if (data.record) {
      setTimeout(() => {
        setFieldsValue({
          ...data.record,
        });
      }, 100);
    } else {
      console.log('rrreeeeccc');
      resetFields();
    }
    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);
    }
  });
  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 [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formColumns,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });
  //表单填写数据
  async function ModalSureClick() {
    try {
      const values = await validate();
      let query = values;
      console.log('query', query);
      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;
          }
        });
      }
      params.data = JSON.stringify(query);
      console.log('query222', query);
      console.log('params222', params);
      const data = await saveFormsData(params);
      if (data) {
        setModalProps({ confirmLoading: true });
        closeModal();
        emit('success');
        return createMessage.success('操作成功');
      } else {
        return createMessage.error('操作失败');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
