<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
          toolbar
          rowNumber
          dragSort
          sortKey="sortNum"
          :sortBegin="1"
          rowSelection
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="dbInfoColumn"
          :dataSource="databaseSource"
        >
          <template #myAction="props">
            <a-divider type="vertical" />
            <Popconfirm title="确定删除吗？" @confirm="onDeleteRow(props)">
              <a>删除</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </TabPane>
      <TabPane tab="页面属性" key="tableRef2">
        <JVxeTable
          ref="tableRef2"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="vueInfoColumn"
          :dataSource="vueSource"
        />
      </TabPane>
      <TabPane tab="校验字段" key="tableRef3">
        <JVxeTable
          ref="tableRef3"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="checkInfoColumn"
          :dataSource="checkSource"
        />
      </TabPane>
      <TabPane tab="外键" key="tableRef4">
        <JVxeTable
          ref="tableRef4"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="foreignInfoColumn"
          :dataSource="foreignSource"
        />
      </TabPane>
      <TabPane tab="索引" key="tableRef5">
        <JVxeTable
          ref="tableRef5"
          toolbar
          rowNumber
          dragSort
          sortKey="sortNum"
          :sortBegin="1"
          rowSelection
          :disabledRows="{ dbFieldName: ['id'] }"
          :height="400"
          :columns="indexInfoColumn"
          :dataSource="dataIndexSource"
          :linkageConfig="linkageConfig"
        >
          <template #myAction="props">
            <a-divider type="vertical" />
            <Popconfirm title="确定删除吗？" @confirm="onDeleteRow(props)">
              <a>删除</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </TabPane>
      <TabPane tab="查询配置" key="tableRef6">
        <JVxeTable
          ref="tableRef6"
          keepSource
          rowNumber
          sortKey="sortNum"
          :sortBegin="1"
          :disabledRows="{ dbFieldName: ['id'] }"
          :maxHeight="580"
          :columns="searchInfoColumn"
          :dataSource="searchSource"
        />
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { defHttp } from '@jdlinker/func';
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm, BasicDrawer, useDrawerInner, JVxeTable } from '@jdlinker/ui';
  import {
    formSchema,
    dbInfoColumn,
    vueInfoColumn,
    checkInfoColumn,
    foreignInfoColumn,
    indexInfoColumn,
    searchInfoColumn
  } from '../cgform.data';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { saveOrUpdateAll } from '../cgform.api';

  const linkageConfig = ref<any[]>([{ requestData: requestFieldData, key: 'indexField' }]);
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const rowId = ref('');
  const isUpdate = ref(true);
  const tableRef = ref<any>();
  const tableRef2 = ref<any>();
  const tableRef3 = ref<any>();
  const tableRef4 = ref<any>();
  const tableRef5 = ref<any>();
  const tableRef6 = ref<any>();
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增表单' : '编辑表单'));
  const dataSource = ref<any[]>([]);
  const databaseSource = ref<any[]>([]);
  const fieldData = ref<any[]>([]);
  const dataIndexSource = ref<any[]>([]);
  const checkSource = ref<any[]>([]);
  const vueSource = ref<any[]>([]);
  const foreignSource = ref<any[]>([]);
  const searchSource = 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;
      loadingIndexData({ headId: rowId.value });
    } else {
      rowId.value = '0';
    }
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      setFieldsValue({
        ...data.record
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter });
    // 加载数据
    loadingData({ headId: rowId.value });
  });
  //提交事件
  async function handleSubmit() {
    const deleteData = tableRef.value!.getDeleteData();
    let deleteFieldIds = deleteData.map((row) => row.id);
    let deleteIndexIds: any = [];
    let indexData: any = [];
    if (unref(tableRef5.value)) {
      const deleteIndexData = tableRef5.value!.getDeleteData();
      deleteIndexIds = deleteIndexData.map((row) => row.id);
      indexData = tableRef5.value!.getTableData();
    }
    let targetArray: any = tableRef.value!.getTableData().map((item, index) => {
      item.orderNum = index + 1;
      return item;
    });
    if (unref(tableRef6.value)) {
      targetArray = targetArray.reduce((acc, cur) => {
        const target = acc.find((e) => e.id === cur.id);
        if (target) {
          Object.assign(target, cur);
        } else {
          acc.push(cur);
        }
        return acc;
      }, tableRef6.value!.getTableData());
    }

    if (unref(tableRef4.value)) {
      targetArray = targetArray.reduce((acc, cur) => {
        const target = acc.find((e) => e.id === cur.id);
        if (target) {
          Object.assign(target, cur);
        } else {
          acc.push(cur);
        }
        return acc;
      }, tableRef4.value!.getTableData());
    }

    if (unref(tableRef3.value)) {
      targetArray = targetArray.reduce((acc, cur) => {
        const target = acc.find((e) => e.id === cur.id);
        if (target) {
          Object.assign(target, cur);
        } else {
          acc.push(cur);
        }
        return acc;
      }, tableRef3.value!.getTableData());
    }
    if (unref(tableRef2.value)) {
      targetArray = targetArray.reduce((acc, cur) => {
        const target = acc.find((e) => e.id === cur.id);
        if (target) {
          Object.assign(target, cur);
        } else {
          acc.push(cur);
        }
        return acc;
      }, tableRef2.value!.getTableData());
    }
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateAll(
        {
          deleteFieldIds: deleteFieldIds,
          deleteIndexIds: deleteIndexIds,
          head: values,
          fields: targetArray,
          indexs: indexData
        },
        unref(isUpdate)
      );
      //关闭弹窗
      closeDrawer();
      //刷新列表
      // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function loadingData(params) {
    const url = '/online/cgform/field/listByHeadId';
    try {
      loading.value = true;
      let result = await defHttp.get({ url, params });
      dataSource.value = result;
      loadDatabaseData(result);
      loadVueData(result);
      loadCheckData(result);
      loadForeignData(result);
      loadSearchData(result);
      fieldData.value = result.map((item) => {
        return {
          text: item.dbFieldName,
          value: item.dbFieldName
        };
      });
    } finally {
      loading.value = false;
    }
  }
  /**数据库属性*/
  function loadDatabaseData(result) {
    databaseSource.value = result.map((item) => {
      return {
        id: item.id,
        dbFieldName: item.dbFieldName,
        dbFieldTxt: item.dbFieldTxt,
        dbLength: item.dbLength,
        dbPointLength: item.dbPointLength,
        dbDefaultVal: item.dbDefaultVal,
        dbType: item.dbType,
        dbIsKey: item.dbIsKey,
        dbIsNull: item.dbIsNull
      };
    });
  }
  /**页面属性*/
  function loadVueData(result) {
    vueSource.value = result.map((item) => {
      return {
        id: item.id,
        dbFieldName: item.dbFieldName,
        dbFieldTxt: item.dbFieldTxt,
        isShowForm: item.isShowForm,
        isShowList: item.isShowList,
        sortFlag: item.sortFlag,
        isReadOnly: item.isReadOnly,
        fieldShowType: item.fieldShowType,
        fieldLength: item.fieldLength,
        isQuery: item.isQuery,
        queryMode: item.queryMode,
        fieldDefaultValue: item.fieldDefaultValue,
        fieldExtendJson: item.fieldExtendJson,
        converter: item.converter
      };
    });
  }
  /**校验*/
  function loadCheckData(result) {
    checkSource.value = result.map((item) => {
      return {
        id: item.id,
        dbFieldName: item.dbFieldName,
        dbFieldTxt: item.dbFieldTxt,
        fieldHref: item.fieldHref,
        fieldValidType: item.fieldValidType,
        fieldMustInput: item.fieldMustInput,
        dictTable: item.dictTable,
        dictField: item.dictField,
        dictText: item.dictText
      };
    });
  }
  /**外键*/
  function loadForeignData(result) {
    foreignSource.value = result.map((item) => {
      return {
        id: item.id,
        dbFieldName: item.dbFieldName,
        dbFieldTxt: item.dbFieldTxt,
        mainTable: item.mainTable,
        mainField: item.mainField
      };
    });
  }
  /**查询配置*/
  function loadSearchData(result) {
    searchSource.value = result.map((item) => {
      return {
        id: item.id,
        dbFieldName: item.dbFieldName,
        dbFieldTxt: item.dbFieldTxt,
        queryShowType: item.queryShowType,
        queryDictTable: item.queryDictTable,
        queryDictField: item.queryDictField,
        queryDictText: item.queryDictText,
        queryDefVal: item.queryDefVal,
        queryConfigFlag: item.queryConfigFlag
      };
    });
  }

  async function loadingIndexData(params) {
    const url = '/online/cgform/index/listByHeadId';
    try {
      loading.value = true;
      let result = await defHttp.get({ url, params });
      dataIndexSource.value = result;
    } finally {
      loading.value = false;
    }
  }

  function requestFieldData() {
    return new Promise((resolve) => {
      setTimeout(() => resolve(fieldData.value), 500);
    });
  }
</script>
<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
