tableCreateManual.vue 35.7 KB
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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
<route lang="yaml">
name: tableCreateManual
</route>

<script lang="ts" setup name="tableCreateManual">
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import {
  getDatabase,
  saveSubjectTable,
  syncPolicys,
  tableModels,
  tableCategoryList,
  getDimList,
  getDictionary,
  aggMethodList,
  getMetaStandardDsField,
  getAllFlowData
} from "@/api/modules/dataMetaService";
import useUserStore from "@/store/modules/user";
import expandPropertyDialog from "./components/expandPropertyDialog.vue";
import tableDefaultValue from "./components/tableDefaultValue.vue";
import { useDefault } from "@/hooks/useDefault"
import { getCamundaDeploymentId } from "@/api/modules/workFlowService"

const userStore = useUserStore();
const { checkDefault } = useDefault()
const router = useRouter();
const route = useRoute();
const flowExpand = ref(true);
const deploymentId = ref('');
const fullPath = route.fullPath;
const isLook = <any>route.query.isLook == 1;
const subjectDomainGuid: any = ref(route.query.domainGuid);
const { proxy } = getCurrentInstance() as any;
const fieldStandardTableRef = ref<InstanceType<typeof ElTable>>();

/** 表模型,只有doris数据库才有 */
const dbType = ref("");

const databaseList: any = ref([]);

const tableFieldsLoading = ref(false);

const tableCreateInfoLoading = ref(false);

//记录当前正在编辑的表创建信息。
const tableCreateInfo: Ref<any> = ref({
  guid: "",
  isCreate: false,
  inputNameValue: '',
  tableCreateType: 1,
  tableData: [
    {
      //数据库表信息。
      dataSourceGuid: '',
      dataServerName: "",
      dataServerChName: "",
      enName: "",
      chName: "",
      subjectDomain: route.query.domainName,
      subjectDomainGuid: subjectDomainGuid.value,
      tableCategory: route.query.layereAttribute == '3' ? 6 : 1,
      syncPolicy: 3,
      characterSet: 'utf8mb3',
      tableModel: 1, //若是聚合模型,下方出现一列聚合方式选择。处了主键列,其余列都需要选择。每个表里都要有主键。
      description: "",
    },
  ],
  partitionAttribute: {},
  tableFields: [], // 字段标准数组。
});

const selectTableFieldRows = ref([]);

//字段类型
const fieldTypes: any = ref([]);

//字符集
const characterList: any = ref([]);

//是否列表
const isNotList = ref([
  {
    label: "Y",
    value: "Y",
  },
  {
    label: "N",
    value: "N",
  },
]);

//字典列表
const dictionaryList: any = ref([]);

// 可选择的关联维度的列表。
const dimListData: any = ref([]);

const fullscreenLoading = ref(false);

/** 表里有数据时不能修改字段类型,长度,精度 */
const hasSubjectData = ref(false);

const expandProperties = ref({});

onBeforeMount(() => {
  getDatabaseList();
  getFieldTypeList();
  getCharacterListData();
  if (route.query.metaStandard) {
    tableCreateInfo.value.tableData[0].chName = route.query.standardName;
    fullscreenLoading.value = true;
    getMetaStandardDsField(route.query.metaStandard).then((res: any) => {
      fullscreenLoading.value = false;
      if (res.code == proxy.$passCode) {
        tableCreateInfo.value.tableFields = res.data?.map((d, i) => {
          d.orderNum = i;
          d.isEdit = true;
          return d;
        }) || [];
      } else {
        proxy.$ElMessage.error(res.msg);
      }
    })
  }
  getCamundaDeploymentId('10025').then((res: any) => {
    if (res.code == proxy.$passCode) {
      deploymentId.value = res.data;
    } else {
      proxy.$ElMessage.error(res.msg);
    }
  })
})

onActivated(() => {
  console.log("activated");
  getDictionaryList();
  getDimListData();
});


const getDatabaseList = () => {
  getDatabase({ connectStatus: 1 }).then((res: any) => {
    databaseList.value = [];
    if (res.code == proxy.$passCode) {
      databaseList.value = res.data || [];
    } else {
      ElMessage.error(res.msg);
    }
  })
};

const getDictionaryList = () => {
  getDictionary({}).then((res: any) => {
    dictionaryList.value = [];
    if (res.code == proxy.$passCode) {
      dictionaryList.value = res.data || [];
      dimOrDictList.value[0].children = dictionaryList.value;
      dimOrDictList.value[0].disabled = !dictionaryList.value.length;
    } else {
      ElMessage.error(res.msg);
    }
  })
};

const getDimListData = () => {
  getDimList().then((res: any) => {
    dimListData.value = [];
    if (res.code == proxy.$passCode) {
      dimListData.value = res.data?.map(r => {
        return {
          guid: r.guid,
          chName: r.chName,
          subjectDomainName: r.subjectDomainName,
          parentGuid: '2'
        }
      }) || [];
      dimOrDictList.value[1].children = dimListData.value;
      dimOrDictList.value[1].disabled = !dimListData.value.length;
    } else {
      ElMessage.error(res.msg);
    }
  })
};

const getFieldTypeList = () => {
  getAllFlowData('字段类型').then((res: any) => {
    fieldTypes.value = [];
    if (res.code == proxy.$passCode) {
      fieldTypes.value = res.data || [];
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const getCharacterListData = () => {
  getAllFlowData('Mysql字符集').then((res: any) => {
    characterList.value = [];
    if (res.code == proxy.$passCode) {
      characterList.value = res.data || [];
    } else {
      ElMessage.error(res.msg);
    }
  })
}

/** 限制长度输入框只能输入整型数字,表,字段英文名称,限制输入字符,数字和下划线。 */
const inputLengthKeyUp = (regexp, scope, field, max: any = null, min: any = null) => {
  scope.row[field] = scope.row[field].replace(regexp, '');
  if (field == 'fieldLength' && scope.row.dataType == 'decimal') {
    max = 65;
  }
  /** 最大值设置2000 */
  if (max && scope.row[field] > max) {
    scope.row[field] = max;
  }
  if (min !== null && scope.row[field] != '' && scope.row[field] <= min) {
    scope.row[field] = min;
  }
}

/** 保存表 */
const saveTable = () => {
  let tableData = tableCreateInfo.value.tableData[0];
  if (!tableData.chName) {
    ElMessage({
      type: "error",
      message: "主题表名称不能为空",
    });
    return;
  }
  if (!tableData.dataServerName) {
    ElMessage({
      type: "error",
      message: "数据源不能为空",
    });
    return;
  }
  if (tableData.dataServerName.indexOf('-') > -1) {
    ElMessage.error('数据库表名称不能包含中划线,可以改为下划线');
    return;
  }
  if (!tableCreateInfo.value.inputNameValue) {
    ElMessage({
      type: "error",
      message: "主题表名称不能为空",
    });
    return;
  }
  let tableFields = tableCreateInfo.value.tableFields;
  if (!tableFields.length) {
    ElMessage({
      type: "error",
      message: "表字段不能为0行",
    });
    return;
  }
  // 若开启了字段标准,则不能为空。
  // 必须含有主键。若是聚合模型,则除了主键必须有聚合方式。
  let isSumModel = tableData.tableModel === 2;
  let hasPrimary = false;
  let enNames: any = [];
  let chNames: any = [];
  const regex = /^[a-zA-Z]/;
  for (const field of tableFields) {
    if (!field.enName) {
      ElMessage.error(`第 ${field.orderNum} 个字段的英文名称不能为空`);
      return;
    }
    if (!regex.test(field.enName)) {
      ElMessage.error(`第 ${field.orderNum} 个字段的英文名称必须以英文字符开头`);
      return;
    }
    if (!field.dataType) {
      ElMessage.error(`第 ${field.orderNum} 个字段的字段类型不能为空`);
      return;
    }
    if (enNames.indexOf(field.enName) > -1) {
      ElMessage.error(`字段的英文名称 ${field.enName} 不能重复`);
      return;
    }
    if (chNames.indexOf(field.chName) > -1) {
      ElMessage.error(`字段的中文名称 ${field.chName} 不能重复`);
      return;
    }
    if (field.dataType === "decimal" && (!field.fieldPrecision && field.fieldPrecision != 0)) {
      ElMessage.error(`第 ${field.orderNum} 个字段的字段类型为浮点型时,精度不能为空`);
      return;
    }
    if (field.dataType === "varchar" && (!field.fieldLength && field.fieldLength != 0)) {
      ElMessage.error(`第 ${field.orderNum} 个字段的字段类型为字符型时,长度不能为空`);
      return;
    }
    if (field.dataType === "char" && (!field.fieldLength && field.fieldLength != 0)) {
      ElMessage.error(`第 ${field.orderNum} 个字段的字段类型为单字符型时,长度不能为空`);
      return;
    }
    if (field.dataType === "decimal" && (!field.fieldLength && field.fieldLength != 0)) {
      ElMessage.error(`第 ${field.orderNum} 个字段的字段类型为浮点符型时,长度不能为空`);
      return;
    }
    if (field.isPrimary === 'Y') {
      hasPrimary = true;
      if (field.notNull != 'Y') {
        ElMessage.error(`第 ${field.orderNum} 个字段为主键,应设置为必填`);
        return;
      }
      if (field.dataType == 'text') {
        ElMessage.error(`第 ${field.orderNum} 个字段为主键,字段类型不能设置为‘大字段型’`);
        return;
      }
      if (field.dataType == 'json') {
        ElMessage.error(`第 ${field.orderNum} 个字段为主键,字段类型不能设置为‘JSON类型’`);
        return;
      }
      if (field.dataType == 'bit') {
        ElMessage.error(`第 ${field.orderNum} 个字段为主键,字段类型不能设置为‘布尔类型’`);
        return;
      }
    } else {
      if (!field.aggWay && isSumModel) {
        ElMessage.error(`聚合模型的非主键字段必须设置聚合方式`);
        return;
      }
    }
    if (field.isEdit) {
      if (checkDefault[field.dataType]) {
        if (!field.fieldLength) { }
        if (!checkDefault[field.dataType]({ row: field })) {
          return;
        }
      }
    }
    field.fieldStandardGuid = route.query.metaStandard;
    enNames.push(field.enName);
    chNames.push(field.chName);
  }
  if (!hasPrimary) {
    ElMessage.error(`字段至少有一个主键字段!`);
    return;
  }
  let addInfo = Object.assign({}, tableCreateInfo.value.tableData[0], {
    enName: tableCreateInfo.value.inputNameValue,
    tableCreateType: tableCreateInfo.value.tableCreateType,
    saveFlag: 1,
    layereAttribute: route.query.layereAttribute,
    dbType: dbType.value,
    dataState: 1,
    immediateApprove: true,
    partitionAttribute: !Object.keys(tableCreateInfo.value.partitionAttribute).length ? null : Object.assign({}, tableCreateInfo.value.partitionAttribute, {
      dynamicPartitionHistory: tableCreateInfo.value.partitionAttribute ? "Y" : 'N'
    }),
    subjectFieldAddDTOS: tableCreateInfo.value.tableFields.map((field, i) => {
      return Object.assign({}, field, { orderNum: i + 1 });
    })
  })
  if (!tableCreateInfo.value.guid) { //添加
    fullscreenLoading.value = true;
    saveSubjectTable(addInfo).then((res: any) => {
      fullscreenLoading.value = false;
      if (res.code == proxy.$passCode) {
        ElMessage.success('新建表提交成功!');
        router.push({
          name: 'metadataStandardQuery'
        });
        userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

//数据库选择改变,对应的表名称是否需要变化。需要根据此属性带出表名前缀,以及是否是doris数据库。
const selectDatabaseChange = (val) => {
  let d = databaseList.value.find(d => d.guid === val);
  if (d) {
    dbType.value = d.databaseType;
    tableCreateInfo.value.tableData[0].dataSourceGuid = d.guid;
    tableCreateInfo.value.tableData[0].dataServerName = d.databaseNameEn;
  } else {
    dbType.value = "";
    tableCreateInfo.value.tableData[0].dataSourceGuid = '';
    tableCreateInfo.value.tableData[0].dataServerName = '';
  }
  tableCreateInfo.value.tableFields.forEach((tableField: any) => {
    if (tableField['dataType'] === "datetime") {
      tableField.defaultValue = ""
    }
  })
};

/** 添加字段标准 */
const addField = () => {
  let len = tableCreateInfo.value.tableFields.length;
  tableCreateInfo.value.tableFields.push({
    orderNum: len + 1,
    isDim: "N",
    isPrimary: "N",
    notNull: "N",
    isEdit: true
  });
  //设置选中表格当前新增行。
  fieldStandardTableRef.value?.setCurrentRow(
    tableCreateInfo.value.tableFields[tableCreateInfo.value.tableFields.length - 1]
  );
  nextTick(() => {
    let bodyWrapper = fieldStandardTableRef.value?.$el.querySelector('.el-table__body');
    let domScroll = bodyWrapper.parentElement.parentElement;
    let rect = domScroll.getBoundingClientRect();
    let maxNum = len + 1;
    if (maxNum * 36 > rect.height + domScroll.scrollTop) {
      fieldStandardTableRef.value?.setScrollTop(maxNum * 36 - rect.height + 2)
    }
  })
};

/** 勾选字段标准选中变化。 */
const selectionFieldsChange = (val) => {
  selectTableFieldRows.value = val;
};

/**
 * 上移规则:
 * 勾选多个时先从最上面开始逐个上移一行,若已经移到最上面一行,则不处理。
 */
const moveUp = () => {
  let selectRows = fieldStandardTableRef.value?.getSelectionRows();
  if (!selectRows.length) {
    ElMessage.error('请先选择需要勾选的数据进行上移');
    return;
  }
  let data = tableCreateInfo.value.tableFields;
  let selectRowIndexs: number[] = [];
  let minNum: number = 0;
  selectRows.forEach((row, i) => {
    let orderNum = data.findIndex(d => d === row) + 1;
    if (orderNum == 1) {
      selectRowIndexs.push(orderNum);
      minNum = orderNum;
      return;
    }
    let topNum = orderNum - 1;
    if (selectRowIndexs.includes(topNum)) {
      //下一行也是选中的,则不做转换。
      return;
    }
    if (i === 0) {
      minNum = topNum;
    }
    row.orderNum = topNum;
    let changeRow = data[topNum - 1];
    changeRow.orderNum = orderNum;
    selectRowIndexs.push(topNum);
    data[topNum] = changeRow;
    data[topNum - 1] = row;
  });
  nextTick().then(() => {
    let bodyWrapper = fieldStandardTableRef.value?.$el.querySelector('.el-table__body');
    let domScroll = bodyWrapper.parentElement.parentElement;
    if ((minNum * 36 - 38) < domScroll.scrollTop) {
      let top = domScroll.scrollTop - 38;
      fieldStandardTableRef.value?.setScrollTop(top < 0 ? 0 : top)
    }
  });
}

/**
 * 下移规则:
 * 勾选多个时先从最下面开始逐个下移一行,若已经移到最下面一行,则不处理。
 */
const moveDown = () => {
  let selectRows = fieldStandardTableRef.value?.getSelectionRows();
  if (!selectRows.length) {
    ElMessage.error('请先选择需要勾选的数据进行下移');
    return;
  }
  let data = tableCreateInfo.value.tableFields;
  let selectRowIndexs: number[] = [];
  let maxNum: number = 0;
  selectRows.slice(0).reverse().forEach((row, i) => {
    let orderNum = data.findIndex(d => d === row) + 1;
    if (orderNum === data.length) {
      maxNum = orderNum;
      selectRowIndexs.push(orderNum);
      return;
    }
    if (selectRowIndexs.includes(orderNum + 1)) {
      //下一行也是选中的,则不做转换。
      return;
    }
    let bottomNum = orderNum + 1;
    row.orderNum = bottomNum;
    if (i === 0) {
      maxNum = bottomNum;
    }
    let changeRow = data[bottomNum - 1];
    changeRow.orderNum = orderNum;
    selectRowIndexs.push(bottomNum);
    data[orderNum - 1] = changeRow;
    data[bottomNum - 1] = row;
  });
  nextTick(() => {
    let bodyWrapper = fieldStandardTableRef.value?.$el.querySelector('.el-table__body');
    let domScroll = bodyWrapper.parentElement.parentElement;
    let rect = domScroll.getBoundingClientRect();
    if (maxNum * 36 > rect.height + domScroll.scrollTop) {
      fieldStandardTableRef.value?.setScrollTop(maxNum * 36 - rect.height + 2)
    }
  })
}

/** 批量删除字段标准 */
const delFeilds = () => {
  if (selectTableFieldRows.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择需要删除的字段",
    });
    return;
  }
  if (tableCreateInfo.value.isCreate) {
    if (selectTableFieldRows.value.find((row: any) => row.isPrimary === 'Y')) {
      ElMessage.error('已建表不能删除主键字段');
      return;
    }
  }
  let hasCreateField = selectTableFieldRows.value.some((row: any) => row.isCreate === 'Y');
  ElMessageBox.confirm(hasCreateField && hasSubjectData.value ? '已选择的字段中含有已创建的表字段且有数据,此操作将永久删除,是否继续?' : "此操作将永久删除,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //此删除是直接从库里删除,还是点击保存后再删除呢??如果是入库删除,后,调用接口获取数据。
      let tableFields = tableCreateInfo.value.tableFields;
      selectTableFieldRows.value.forEach((r: any) => {
        let index = tableFields.findIndex((t: any) => t.orderNum === r.orderNum);
        if (index !== -1) {
          tableFields.splice(index, 1);
        }
      });
      fieldStandardTableRef.value?.clearSelection();
      tableCreateInfo.value.tableFields.forEach((field, i) => {
        field.orderNum = i + 1;
      });
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

//点击编辑按钮
const handleFieldClickEdit = (scope) => {
  scope.row['isEdit'] = true;
};

//点击保存按钮
const handleFieldClickSave = (scope) => {
  if (!scope.row.enName) {
    ElMessage({
      type: "error",
      message: "字段英文名不能为空!",
    });
    return;
  }
  if (checkDefault[scope.row.dataType]) {
    if (!scope.row.fieldLength) { }
    if (!checkDefault[scope.row.dataType](scope)) {
      return
    }
  }
  scope.row['isEdit'] = false;
};

const handleFieldDelete = (scope) => {
  ElMessageBox.confirm(scope.row['isCreate'] === 'Y' && hasSubjectData.value ? '该字段已被创建且表中有数据,此操作将永久删除,是否继续?' : "此操作将永久删除,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //此删除是直接从库里删除,还是点击保存后再删除呢??如果是入库删除,后,调用接口获取数据。
      let tableFields = tableCreateInfo.value.tableFields;
      tableFields.splice(scope.$index, 1);
      tableCreateInfo.value.tableFields.forEach((field, i) => {
        field.orderNum = i + 1;
      });
      tableCreateInfo.value.tableFields.forEach((field, i) => {
        field.orderNum = i + 1;
      });
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
}

const dataTypeChange = (val, scope) => {
  scope.row['defaultValue'] = ''
  scope.row['fieldLength'] = undefined
  scope.row['fieldPrecision'] = undefined

}

/*** 以下是处理数据字典或维表的树形选择框。 */

const dimOrDictList: any = ref([{
  guid: '1',
  chName: '数据字典',
  children: dictionaryList.value,
  isLeaf: false,
  disabled: !dictionaryList.value.length,
}, {
  guid: '2',
  chName: '维度',
  isLeaf: false,
  disabled: !dimListData.value.length,
  children: dimListData.value
}]);

const dimOrDictInputFilterMethod = (v, data) => {
  return data.label?.includes(v) || data.chName?.includes(v);
};

const dimOrDictSelectRef = ref();

const dimOrDictSelectNode = ref();

const handleDictSelectNodeChange = (node) => {
  dimOrDictSelectNode.value = node;
}

const handleDictionaryChange = (val, scope) => {
  if (!val) {
    scope.row.dictionaryGuid = '';
    scope.row.dimGuid = '';
    scope.row.dictionaryChName = '';
    scope.row.dimChName = '';
    return;
  }
  let info = dimOrDictSelectNode.value;
  if (!info) {
    return;
  }
  if (info.parentGuid == '2') {
    scope.row.dimGuid = val;
    scope.row.dimChName = dimListData.value.find(d => d.guid === val)?.chName;
    scope.row.dictionaryGuid = '';
    scope.row.dictionaryChName = '';
  } else {
    scope.row.dictionaryGuid = val;
    scope.row.dictionaryChName = dictionaryList.value.find(d => d.guid === val)?.chName;
    scope.row.dimGuid = '';
    scope.row.dimChName = '';
  }
}

/** 扩展属性弹出对话框 */
const expandPropertyDialogRef = ref();

/** 扩展属性弹出对话框 */
const handleClickExpand = () => {
  expandPropertyDialogRef.value?.handleClickExpand();
}

const expandDialogValueChange = (val) => {
  tableCreateInfo.value.partitionAttribute = val;
  expandProperties.value = val;
}

</script>

<template>
  <div class="table_tool_wrap" v-loading.fullscreen.lock="fullscreenLoading">
    <div class="tools_btns">
      <!-- <el-button type="primary" :disabled="isLook" @click="saveDraftTable" v-preReClick>保存为草稿</el-button> -->
      <el-button type="primary" :disabled="isLook" @click="saveTable" v-preReClick>提交</el-button>
    </div>
    <el-table ref="tableRef" :data="tableCreateInfo.tableData" v-loading="tableCreateInfoLoading"
      :highlight-current-row="true" stripe border height="100%" tooltip-effect="light" row-key="guid" :style="{
        width: '100%',
        height: 'auto',
        display: 'inline-block',
      }">
      <el-table-column prop="dataSourceGuid" label="数据源" width="200px" align="left" show-overflow-tooltip>
        <template #header>
          <span>数据源</span>
          <span v-if="!isLook" style="color:red;margin-left: 2px;">*</span>
        </template>
        <template #default="scope">
          <el-select v-if="!isLook" v-model="scope.row['dataSourceGuid']" placeholder="请选择"
            :disabled="tableCreateInfo.isCreate" @change="(val) => selectDatabaseChange(val)" clearable filterable>
            <el-option v-for="opt in databaseList" :key="opt['guid']" :label="opt['databaseNameZh']"
              :value="opt['guid']" />
          </el-select>
          <span v-else>{{ scope.row["dataServerChName"] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enName" label="数据库表" width="200px" align="left" show-overflow-tooltip>
        <template #header>
          <span>数据库表</span>
          <span v-if="!isLook" style="color:red;margin-left: 2px;">*</span>
        </template>
        <template #default="scope">
          <template v-if="!isLook">
            <div class="prefix-or-suffix-cell">
              <el-input :disabled="tableCreateInfo.isCreate" v-model.trim="tableCreateInfo.inputNameValue"
                :maxlength="50" placeholder="必填" />
            </div>
          </template>
          <span v-else>{{ scope.row["enName"] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="chName" label="主题表名称" width="200px" align="left" show-overflow-tooltip>
        <template #header>
          <span>主题表名称</span>
          <span v-if="!isLook" style="color:red;margin-left: 2px;">*</span>
        </template>
        <template #default="scope">
          <el-input v-if="!isLook" v-model.trim="scope.row['chName']" placeholder="必填" :maxlength="50" />
          <span v-else>{{ scope.row["chName"] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="subjectDomain" label="主题域" width="180px" align="left" show-overflow-tooltip>
        <template #default="scope">
          <el-input v-if="!isLook" disabled v-model="scope.row['subjectDomain']" />
          <span v-else>{{ scope.row["subjectDomain"] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tableModel" label="表模型" :width="isLook ? '100px' : '150px'" align="left"
        show-overflow-tooltip>
        <template #default="scope">
          <el-select v-if="dbType == 'doris' && !isLook" v-model="scope.row['tableModel']" placeholder="请选择"
            :disabled="tableCreateInfo.isCreate">
            <el-option v-for="opt in tableModels" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
          </el-select>
          <span v-else-if="dbType == 'doris'">{{tableModels.find(t => t.value === scope.row["tableModel"])?.label ||
            '-'
          }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="tableCategory" label="表分类" :width="isLook ? '100px' : '150px'" align="left"
        show-overflow-tooltip>
        <template #default="scope">
          <el-select v-if="!isLook" v-model="scope.row['tableCategory']" placeholder="请选择">
            <el-option v-for="opt in tableCategoryList" :key="opt['value']" :label="opt['label']"
              :value="opt['value']" />
          </el-select>
          <span v-else>{{tableCategoryList.find(t => t.value === scope.row["tableCategory"])?.label || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="syncPolicy" label="同步策略" :width="isLook ? '100px' : '150px'" align="left"
        show-overflow-tooltip>
        <template #default="scope">
          <el-select v-if="!isLook" v-model="scope.row['syncPolicy']" placeholder="请选择">
            <el-option v-for="opt in syncPolicys" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
          </el-select>
          <span v-else>{{syncPolicys.find(s => s.value === scope.row["syncPolicy"])?.label || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="characterSet" label="字符集" :width="isLook ? '100px' : '150px'" align="left"
        show-overflow-tooltip>
        <template #default="scope">
          <el-select v-if="!isLook" v-model="scope.row['characterSet']" placeholder="请选择"
            :disabled="tableCreateInfo.isCreate">
            <el-option v-for="opt in characterList" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
          </el-select>
          <span v-else>{{characterList.find(c => c.value === scope.row["characterSet"])?.label || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="220px" align="left" show-overflow-tooltip>
        <template #default="scope">
          <el-input v-if="!isLook" v-model.trim="scope.row['description']" />
          <span v-else>{{ scope.row["description"] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100px" align="left" fixed="right" show-overflow-tooltip>
        <template #default="scope">
          <span class="text_btn" @click="handleClickExpand()" v-preReClick>扩展属性</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="tools_btns">
      <el-button type="primary" :disabled="isLook" @click="addField">新增</el-button>
      <el-button @click="moveUp" :disabled="isLook">上移</el-button>
      <el-button @click="moveDown" :disabled="isLook">下移</el-button>
      <el-button @click="delFeilds" :disabled="isLook">批量删除</el-button>
    </div>
    <div class="table_panel">
      <el-table ref="fieldStandardTableRef" :data="tableCreateInfo.tableFields" v-loading="tableFieldsLoading"
        :highlight-current-row="true" stripe border height="100%" row-key="guid"
        @selection-change="selectionFieldsChange" tooltip-effect="light" :style="{
          width: '100%',
          'max-height': 'calc(100% - 16px)',
          display: 'inline-block',
        }">
        <el-table-column type="selection" v-if="!isLook" :width="32" align="center" />
        <el-table-column label="排序" type="index" width="56px" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="chName" label="字段中文名称" width="150px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-input v-if="scope.row['isEdit']" :placeholder="'请输入'" v-model.trim="scope.row['chName']" />
            <span v-else>{{ scope.row["chName"] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="enName" label="字段英文名" width="150px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-input v-if="scope.row['isEdit'] && !(scope.row['guid'] && tableCreateInfo.isCreate)"
              v-model.trim="scope.row['enName']" placeholder="必填"
              @input="inputLengthKeyUp(/[^a-zA-Z0-9_]/g, scope, 'enName')" />
            <span v-else>{{ scope.row["enName"] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="字段类型" width="120px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-select v-if="scope.row['isEdit'] && !(tableCreateInfo.isCreate && scope.row['isCreate'] === 'Y')"
              v-model="scope.row['dataType']" placeholder="请选择" @change="(val) => dataTypeChange(val, scope)">
              <el-option v-for="opt in fieldTypes" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
            </el-select>
            <span v-else>{{fieldTypes.find(f => f.value === scope.row["dataType"])?.label || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fieldLength" label="长度" width="115px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-input
              v-if="scope.row['isEdit'] && !(tableCreateInfo.isCreate && scope.row['isCreate'] === 'Y') && (scope.row['dataType'] == 'varchar' || scope.row['dataType'] == 'decimal' || scope.row['dataType'] == 'char')"
              v-model.trim="scope.row['fieldLength']" placeholder="必填"
              @input="inputLengthKeyUp(/\D/g, scope, 'fieldLength', 2000, 1)" />
            <span v-else>{{ scope.row["fieldLength"] == null ? '-' : scope.row["fieldLength"] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fieldPrecision" label="精度" width="115px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-input
              v-if="scope.row['isEdit'] && !(tableCreateInfo.isCreate && scope.row['isCreate'] === 'Y') && scope.row['dataType'] == 'decimal'"
              v-model.trim="scope.row['fieldPrecision']" placeholder="必填"
              @input="inputLengthKeyUp(/\D/g, scope, 'fieldPrecision', 30, 1)" />
            <span v-else>{{ scope.row["fieldPrecision"] == null ? '-' : scope.row["fieldPrecision"] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dimOrdictionaryGuid" label="关联维度/字典" width="130px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-tree-select ref="dimOrDictSelectRef" v-if="scope.row['isEdit']" filterable clearable
              :data="dimOrDictList" v-model="scope.row['dimOrdictionaryGuid']" node-key="guid"
              :default-expanded-keys="scope.row['dictionaryGuid'] ? ['1'] : (scope.row['dimGuid'] ? ['2'] : [])"
              placeholder="请选择" :filter-node-method="dimOrDictInputFilterMethod" :props="{
                label: 'chName',
                value: 'guid',
                children: 'children',
                isLeaf: 'isLeaf'
              }" @change="(v) => handleDictionaryChange(v, scope)" @current-change="handleDictSelectNodeChange">
              <template #default="{ node, data }">
                <template v-if="node.level > 1 && data.parentGuid == '2'">
                  <span>{{ data["chName"] + `(${data["subjectDomainName"]})` }}</span>
                </template>
                <span v-else>{{ data['chName'] }}</span>
              </template>
            </el-tree-select>
            <span v-else>{{ (scope.row['dictionaryGuid'] ? scope.row["dictionaryChName"] : (scope.row['dimGuid'] ?
              scope.row['dimChName'] : '-')) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isPrimary" label="是否主键" width="90px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-select v-if="scope.row['isEdit'] && !tableCreateInfo.isCreate" v-model="scope.row['isPrimary']"
              placeholder="请选择">
              <el-option v-for="opt in isNotList" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
            </el-select>
            <span v-else>{{ scope.row["isPrimary"] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="tableCreateInfo.tableData[0].tableModel == 2" prop="aggWay" label="聚合方式" width="120px"
          align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-select v-if="scope.row['isEdit']" v-model="scope.row['aggWay']" placeholder="请选择">
              <el-option v-for="opt in aggMethodList" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
            </el-select>
            <span v-else>{{ scope.row["aggWay"] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="notNull" label="是否必填" width="90px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <el-select v-if="scope.row['isEdit'] && !(scope.row.isCreate == 'Y' && scope.row['notNull'] == 'N')"
              v-model="scope.row['notNull']" placeholder="请选择">
              <el-option v-for="opt in isNotList" :key="opt['value']" :label="opt['label']" :value="opt['value']" />
            </el-select>
            <span v-else>{{ scope.row["notNull"] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="defaultValue" label="默认值" width="205px" align="left" show-overflow-tooltip>
          <template #default="scope">
            <tableDefaultValue :scope="scope" :dbType="dbType"
              :readonly="dbType == 'doris' && scope.row.isCreate == 'Y'"></tableDefaultValue>
          </template>
        </el-table-column>
        <el-table-column v-if="!isLook" label="操作" width="100px" align="left" fixed="right" show-overflow-tooltip>
          <template #default="scope">
            <template v-if="!(tableCreateInfo.isCreate && scope.row['isPrimary'] === 'Y')">
              <span class="text_btn" v-if="!scope.row['isEdit']" @click="handleFieldClickEdit(scope)"
                v-preReClick>编辑</span>
              <span class="text_btn" v-else @click="handleFieldClickSave(scope)" v-preReClick>保存</span>
              <el-divider direction="vertical" />
              <span class="text_btn" @click="handleFieldDelete(scope)">删除</span>
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <ContentWrap title="流程审批" description="" :isExpand="flowExpand" :expand-swicth="true" class="mb16"
      @expand="(v) => flowExpand = v">
      <ApprovalProcess v-if="deploymentId" :deploymentId="deploymentId" :definitionId="''">
      </ApprovalProcess>
    </ContentWrap>
    <expandPropertyDialog ref="expandPropertyDialogRef" :is-look="isLook" :partitionAttribute="expandProperties"
      :table-create-info="tableCreateInfo" @expandValueChange="expandDialogValueChange" />
  </div>
</template>

<style lang="scss" scoped>
.table_tool_wrap {
  width: 100%;
  height: 100%;
  padding: 0 16px;
  overflow: hidden auto;

  .tools_btns {
    padding: 8px 0;
  }

  :deep(.el-table) {
    .cell {

      .prefix-or-suffix-cell {
        display: inline-flex;
        align-items: center;
      }
    }
  }

  .table_panel {
    height: 268px;

    :deep(.el-table) {
      & td.el-table__cell {
        padding: 2px 0;
        height: 36px;
      }
    }
  }
}

:deep(.el-dialog) {
  .dialog-form-inline {
    .checkbox_input {
      display: flex;
      flex-direction: column;

      .input_panel {
        margin: 0;
      }
    }

    .select_group {
      .el-form-item__content>.el-input {
        margin-top: 21px;
      }
    }

    .radio_panel {
      .panel_content {
        display: none;
      }
    }
  }
}
</style>