<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :canFullscreen="false"
    :draggable="false"
    :showCancelBtn="!isDetail"
    :showOkBtn="!isDetail"
    :title="getTitle"
    @ok="ModalSureClick"
    width="60%"
  >
    <BasicForm ref="myDataBaseFormRef" @register="registerForm" v-if="formModalVisible" />
    <a-table
      class="sub-table"
      :columns="subTableColumns"
      :data-source="subTableList"
      :pagination="false"
    >
      <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>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { unref, ref, reactive } 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';

  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 flowCode = ref('');
  const userStore = useUserStore();
  const userInfo: any = userStore.getUserInfo;
  const formData = reactive({
    userId: userInfo.id,
    title: '',
  });
  const subTableId = ref(null);
  const subTableColumns: any = ref([]);
  const subTableData = ref([]);
  const subTableList: any = ref([]);

  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);
      subTableColumns.value = [
        {
          dataIndex: 'setting',
          key: 'setting',
        },
      ];

      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,
            });
          });
        });
        subTableData.value = tableData;
      }
    });

    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 = '编辑';
      data.btnList.forEach((element) => {
        if (element.prop === 'Edit' && element.isWFlow) {
          flowCode.value = element.wFlowCode;
        }
      });
    }
    if (!unref(isUpdate) && unref(isDetail)) {
      getTitle.value = '详情';
    }
    formModalVisible.value = true;
    primaryQuery.value = data.query;
    if (data.record) {
      setTimeout(() => {
        setFieldsValue({
          ...data.record,
        });
      }, 100);
      subTableList.value = data.recordChildren;
    } else {
      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);
    }
  });

  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) => {
      console.log(item);
      if (item.component == 'InputGuid') {
        emptyItem[item.field] = keyValue;
      } else {
        emptyItem[item.field] = '';
      }
    });

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

  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;
      let saveSubTableList = [];
      subTableList.value.forEach((item) => {
        let emptyObj = {};
        for (const key in item) {
          if (key === 'key') continue;
          emptyObj[key] = item[key];
        }
        saveSubTableList.push(emptyObj);
      });
      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;
          }
        });
      }
      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 });
    }
  }
  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('保存草稿失败');
    }
  }
</script>
