<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="100%" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
    <Tabs defaultActiveKey="tableRef">
      <TabPane tab="数据库属性" key="tableRef">
        <JVxeTable
          ref="tableRef"
          keepSource
          rowNumber
          dragSort
          sortKey="sortNum"
          :sortBegin="1"
          rowSelection
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="dbInfoColumn"
          :dataSource="dataSource"
        />
      </TabPane>
      <TabPane tab="页面属性" key="tableRef2">
        <JVxeTable
          ref="tableRef2"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="vueInfoColumn"
          :dataSource="dataSource"
        />
      </TabPane>
      <TabPane tab="个性化查询配置" key="tableRef6">
        <JVxeTable
          ref="tableRef6"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="searchInfoColumn"
          :dataSource="dataSource"
        />
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { formSchema, dbInfoColumn, vueInfoColumn, searchInfoColumn } from './cgform.data';
  import { BasicDrawer, useDrawerInner, JVxeTable, BasicForm, useForm } from '@jdlinker/ui';
  import { getCodegenTable, updateCodegenTable } from '../service';
  import { mergeWith } from 'lodash-es';
  import { Tabs, TabPane } from 'ant-design-vue';

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const rowId = ref('');
  const isUpdate = ref(true);
  const tableRef = ref<any>();
  const tableRef2 = ref<any>();
  const tableRef6 = ref<any>();
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增表单' : '编辑表单'));
  const dataSource = ref<any[]>([]);
  const fieldData = ref<any[]>([]);
  const loading = ref<boolean>(false);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false
  });
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    let showFooter = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
    } else {
      rowId.value = '0';
    }
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      setFieldsValue({
        ...data.record
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter });
    // 加载数据
    loadingData(rowId.value);
  });
  //提交事件
  async function handleSubmit() {
    let targetArray: any = tableRef.value!.getTableData().map((item, index) => {
      item.orderNum = index + 1;
      return item;
    });

    if (tableRef6.value) {
      mergeWith(targetArray, tableRef6.value!.getTableData(), (objValue, srcValue) => {
        if (Array.isArray(srcValue)) {
          return [...new Set([...objValue, ...srcValue])];
        } else {
          return srcValue;
        }
      });
    }
    if (tableRef2.value) {
      mergeWith(targetArray, tableRef2.value!.getTableData(), (objValue, srcValue) => {
        if (Array.isArray(srcValue)) {
          return [...new Set([...objValue, ...srcValue])];
        } else {
          return srcValue;
        }
      });
    }
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await updateCodegenTable({
        table: values,
        columns: targetArray
      });
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function loadingData(params) {
    try {
      loading.value = true;
      let result = await getCodegenTable(params);
      dataSource.value = result.columns;
      fieldData.value = result.columns.map((item) => {
        return {
          text: item.dbFieldName,
          value: item.dbFieldName
        };
      });
    } finally {
      loading.value = false;
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
