ny
昨天 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<script lang="ts" setup>
import { computed, reactive, ref, unref } from 'vue';
 
import { useMessage } from '@jnpf/hooks';
import { BasicForm, useForm } from '@jnpf/ui/form';
import { BasicPopup, usePopupInner } from '@jnpf/ui/popup';
import { buildBitUUID, getDataTypeText } from '@jnpf/utils';
 
import { DownOutlined } from '@ant-design/icons-vue';
import Sortablejs from 'sortablejs';
 
import { getCommonFieldsList } from '#/api/systemData/commonFields';
import { addTableFields, createDataModel as create, getDataModelInfo as getInfo, updateDataModel as update } from '#/api/systemData/dataModel';
import { $t } from '#/locales';
 
const emit = defineEmits(['register', 'reload']);
const { createMessage } = useMessage();
 
const options = [
  { fullName: '字符串', id: 'varchar' },
  { fullName: '整型', id: 'int' },
  { fullName: '日期时间', id: 'datetime' },
  { fullName: '浮点', id: 'decimal' },
  { fullName: '长整型', id: 'bigint' },
  { fullName: '文本', id: 'text' },
];
const dataForm = reactive({
  value: {
    table: '',
    tableName: '',
    newTable: '',
  },
});
const linkId = ref('');
const dbType = ref('');
const hasTableData = ref(false);
const fieldList = ref<any[]>([]);
const commonFieldList = ref<any[]>([]);
const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  baseColProps: { span: 8 },
  labelWidth: 100,
  schemas: [
    {
      field: 'newTable',
      label: '表名称',
      component: 'Input',
      componentProps: { placeholder: '请输入', maxlength: 50 },
      rules: [
        { required: true, trigger: 'blur', message: '必填' },
        { pattern: /(^_([A-Z0-9]_?)*$)|(^[A-Z](_?[A-Z0-9])*_?$)/i, message: '请输入正确的表名称', trigger: 'blur' },
      ],
    },
    {
      field: 'tableName',
      label: '表说明',
      component: 'Input',
      componentProps: { placeholder: '请输入', maxlength: 50 },
      rules: [{ required: true, trigger: 'blur', message: '必填' }],
    },
  ],
});
const getColumns = computed(() => {
  let list: any[] = [
    { title: '拖动', dataIndex: 'drag', key: 'drag', align: 'center', width: 50 },
    {
      width: 50,
      title: '序号',
      align: 'center',
      customRender: ({ index }) => index + 1,
    },
    { title: '列名', dataIndex: 'field', key: 'field' },
    { title: '类型', dataIndex: 'dataType', key: 'dataType', width: 120 },
    { title: '长度', dataIndex: 'dataLength', key: 'dataLength', width: 120 },
    { title: '是否主键', dataIndex: 'primaryKey', key: 'primaryKey', align: 'center', width: 80 },
    { title: '自增长ID', dataIndex: 'identity', key: 'identity', align: 'center', width: 80 },
    { title: '允许空', dataIndex: 'allowNull', key: 'allowNull', align: 'center', width: 80 },
    { title: '说明', dataIndex: 'fieldName', key: 'fieldName', width: 300 },
    { title: '操作', dataIndex: 'action', key: 'action', width: 50 },
  ];
  if (['KingbaseES', 'Oracle', 'PostgreSQL'].includes(dbType.value)) list = list.filter((o) => o.key != 'identity');
  return list;
});
const [registerModal, { closePopup, changeLoading, changeOkLoading }] = usePopupInner(init);
 
const getTitle = computed(() => (unref(dataForm.value.table) ? $t('common.editText') : $t('common.addText')));
 
function init(data) {
  dataForm.value.table = data.table;
  linkId.value = data.linkId;
  dbType.value = data.dbType;
  fieldList.value = [];
  getFieldList();
  changeLoading(true);
  resetFields();
  if (dataForm.value.table) {
    getInfo(unref(linkId), dataForm.value.table).then((res) => {
      dataForm.value = res.data.tableInfo;
      dataForm.value.newTable = dataForm.value.table;
      setFieldsValue(dataForm.value);
      let tableFieldList = res.data.tableFieldList.map((o) => ({
        ...o,
        index: buildBitUUID(),
        primaryKey: !!o.primaryKey,
        allowNull: !!o.allowNull,
        identity: !!o.identity,
      }));
      hasTableData.value = res.data.hasTableData || false;
      if (hasTableData.value) {
        tableFieldList = tableFieldList.map((o) => ({ ...o, disabled: true }));
      }
      fieldList.value = tableFieldList;
      changeLoading(false);
    });
  } else {
    hasTableData.value = false;
    dataForm.value.newTable = data.table || '';
    changeLoading(false);
  }
  initSort();
}
function initSort() {
  const table: any = document.querySelector(`.drag-table .ant-table-tbody`);
  Sortablejs.create(table, {
    handle: '.drag-handler',
    animation: 150,
    easing: 'cubic-bezier(1, 0, 0, 1)',
    onStart: () => {},
    // 结束拖动事件
    onEnd: ({ newIndex, oldIndex }: any) => {
      setNodeSort(fieldList.value, oldIndex, newIndex);
    },
  });
}
const setNodeSort = (data: any, oldIndex: any, newIndex: any) => {
  const currRow = data.splice(oldIndex, 1)[0];
  data.splice(newIndex, 0, currRow);
};
function handleDelItem(index) {
  fieldList.value.splice(index, 1);
}
function handleAdd(row: Recordable | undefined = undefined) {
  const index = buildBitUUID();
  let item = {};
  item = row
    ? {
        field: row.field,
        dataType: row.dataType,
        dataLength: row.dataLength,
        allowNull: !!row.allowNull,
        fieldName: row.fieldName,
        primaryKey: false,
        index,
      }
    : {
        field: '',
        dataType: 'varchar',
        dataLength: 50,
        allowNull: true,
        primaryKey: false,
        fieldName: '',
        index,
      };
  fieldList.value.push(item);
}
function onKeyChange(row) {
  row.identity = false;
  row.allowNull = false;
}
function getFieldList() {
  getCommonFieldsList().then((res) => {
    commonFieldList.value = res.data.list;
  });
}
function exist() {
  let isOk = true;
  for (let i = 0; i < fieldList.value.length; i++) {
    const e = fieldList.value[i];
    if (!e.field) {
      createMessage.error(`第${i + 1}行列名不能为空`);
      isOk = false;
      break;
    }
    // eslint-disable-next-line regexp/no-unused-capturing-group
    const reg = /(^_([a-z0-9]_?)*$)|(^[a-z](_?[a-z0-9])*_?$)/i;
    const dataLengthReg = /^\d+(?:,\d*)?$/;
    if (!reg.test(e.field)) {
      createMessage.error(`第${i + 1}行列名格式错误,请重新输入`);
      isOk = false;
      break;
    }
    const num = fieldList.value.filter((o) => o.field == e.field);
    if (num.length > 1) {
      createMessage.error(`第${i + 1}行列名'${e.field}'已重复`);
      isOk = false;
      break;
    }
    if (e.dataType == 'decimal' && !dataLengthReg.test(e.dataLength)) {
      createMessage.error(`第${i + 1}行请输入数字`);
      isOk = false;
      break;
    }
    if (!e.fieldName) {
      createMessage.error(`第${i + 1}行说明不能为空`);
      isOk = false;
      break;
    }
  }
  return isOk;
}
async function handleSubmit() {
  const values = await validate();
  if (!values) return;
  if (!fieldList.value.length) return createMessage.error('请至少添加一个字段');
  if (!exist()) return;
  const boo = fieldList.value.some((o) => o.primaryKey);
  if (!boo) return createMessage.error('请选择一个字段作为主键');
  changeOkLoading(true);
  const tableInfo = { ...dataForm.value, ...values };
  const tableFieldList = hasTableData.value ? fieldList.value.filter((o) => !o.disabled) : fieldList.value;
  const query = {
    tableFieldList: tableFieldList.map((o) => ({
      ...o,
      primaryKey: o.primaryKey ? 1 : 0,
      allowNull: o.allowNull ? 1 : 0,
      identity: o.identity && o.primaryKey ? 1 : 0,
    })),
    tableInfo,
  };
  const formMethod = hasTableData.value ? addTableFields : dataForm.value.table ? update : create;
  formMethod(unref(linkId), query)
    .then((res) => {
      createMessage.success(res.msg);
      changeOkLoading(false);
      closePopup();
      setTimeout(() => {
        emit('reload');
      }, 200);
    })
    .catch(() => {
      changeOkLoading(false);
    });
}
</script>
<template>
  <BasicPopup v-bind="$attrs" @register="registerModal" :title="getTitle" show-ok-btn @ok="handleSubmit">
    <div class="m-[10px] mb-0">
      <BasicForm @register="registerForm" />
    </div>
    <div class="caption">
      <p class="title">字段设置</p>
      <a-dropdown :disabled="!commonFieldList.length">
        <template #overlay>
          <a-menu>
            <a-menu-item :key="item.field" v-for="item in commonFieldList" @click="handleAdd(item)">{{ item.field }}</a-menu-item>
          </a-menu>
        </template>
        <a-button>常用字段<DownOutlined /></a-button>
      </a-dropdown>
    </div>
    <a-table :data-source="fieldList" :columns="getColumns" size="small" :pagination="false" row-key="index" class="drag-table">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'drag'">
          <i class="drag-handler icon-ym icon-ym-darg" title="点击拖动"></i>
        </template>
        <template v-if="record.disabled">
          <a-checkbox :checked="record[column.key]" v-if="['primaryKey', 'allowNull'].includes(column.key)" />
          <template v-if="column.key === 'dataType'">{{ getDataTypeText(record[column.key]) }}</template>
        </template>
        <template v-else>
          <template v-if="column.key === 'field'">
            <a-input v-model:value="record.field" placeholder="请输入" :maxlength="50" />
          </template>
          <template v-if="column.key === 'dataLength'">
            <a-input v-model:value="record.dataLength" placeholder="请输入" v-if="record.dataType == 'decimal'" />
            <a-input-number
              v-model:value="record.dataLength"
              placeholder="请输入"
              :disabled="record.dataType !== 'varchar' && record.dataType !== 'decimal'"
              class="!w-full"
              v-else />
          </template>
          <template v-if="column.key === 'dataType'">
            <jnpf-select v-model:value="record.dataType" placeholder="请选择" :options="options" />
          </template>
          <template v-if="column.key === 'primaryKey'">
            <a-checkbox v-model:checked="record.primaryKey" @change="onKeyChange(record)" />
          </template>
          <template v-if="column.key === 'identity'">
            <a-checkbox v-model:checked="record.identity" v-if="record.primaryKey" />
            <span v-else></span>
          </template>
          <template v-if="column.key === 'allowNull'">
            <a-checkbox v-model:checked="record.allowNull" :disabled="!!record.primaryKey" />
          </template>
          <template v-if="column.key === 'fieldName'">
            <a-input v-model:value="record.fieldName" placeholder="请输入" :maxlength="50" />
          </template>
        </template>
        <template v-if="column.key === 'action'">
          <a-button class="action-btn" type="link" color="error" @click="handleDelItem(index)" size="small" v-if="!record.disabled">删除</a-button>
        </template>
      </template>
    </a-table>
    <div class="table-add-action" @click="handleAdd()">
      <a-button type="link" pre-icon="icon-ym icon-ym-btn-add">新增一行</a-button>
    </div>
  </BasicPopup>
</template>
<style lang="scss" scoped>
.caption {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 10px;
 
  .title {
    font-size: 16px;
    line-height: 24px;
  }
}
</style>