<template>
  <div class="step4">
    <div
      v-for="(tableConfig, kindex) in generatorConfig?.tableStructureConfigs"
      :key="kindex"
    >
      <a-table
        :columns="tableColumns"
        :data-source="[tableConfig]"
        :pagination="false"
        :defaultExpandAllRows="true"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'tableName'">
            <a-input
              v-model:value="record.tableName"
              :placeholder="t('请填写数据表名称')"
              @blur="handleBlur(record)"
            />
          </template>
          <template v-else-if="column.dataIndex === 'isMain'">
            <span>
              <a-tag :color="record.isMain ? 'blue' : 'orange'">
                {{ record.isMain ? t("主表") : record.isSubForm ? t("附表") : t("次表") }}
              </a-tag>
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'tableComment'">
            <a-input v-model:value="record.tableComment" :placeholder="t('请填写备注')" />
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button
              type="primary"
              @click="addTableField(tableConfig.tableFieldConfigs, record.tableName)"
              >新增表字段</a-button
            >
          </template>
        </template>
        <template #expandedRowRender>
          <a-table
            :columns="fieldColumns"
            :data-source="tableConfig.tableFieldConfigs"
            :pagination="false"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'fieldName'">
                <a-input
                  v-model:value="record.fieldName"
                  :placeholder="t(`请填写{title}`, { title: column.title })"
                  :disabled="disabledFields.includes(record.key)"
                />
              </template>
              <template v-else-if="column.dataIndex === 'fieldLength'">
                <a-input
                  v-model:value.number="record.fieldLength"
                  :placeholder="t('请填写字段长度')"
                  :disabled="disabledFields.includes(record.key)"
                />
              </template>
              <template v-else-if="column.dataIndex === 'fieldComment'">
                <a-input
                  v-model:value.number="record.fieldComment"
                  :placeholder="t('请填写备注')"
                  :disabled="disabledFields.includes(record.key)"
                />
              </template>
              <template v-else-if="column.dataIndex === 'fieldType'">
                <a-select
                  v-model:value="record.fieldType"
                  style="width: 100%"
                  :placeholder="t('请选择数据格式')"
                  :disabled="disabledFields.includes(record.key)"
                  allowClear
                  @change="(value) => handleTypeChange(value, record)"
                >
                  <a-select-option
                    :value="type.value"
                    v-for="(type, idx) in fieldTypeList"
                    :key="idx"
                  >
                    {{ type.label }}
                  </a-select-option>
                </a-select>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <div
                  style="color: #ff8080"
                  @click="
                    () => {
                      tableConfig.tableFieldConfigs.splice(index, 1);
                    }
                  "
                >
                  删除
                </div>
              </template>
            </template>
          </a-table>
        </template>
      </a-table>
    </div>

    <TableNameModal
      @register="registerTableName"
      @success="handleEditSuccess"
      @cancel="handleCancel"
    />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, inject, ref, Ref } from "vue";

import { TableNameModal } from "/@/components/CreateCodeStep";
import { snakeCase } from "lodash-es";
import { GeneratorConfig } from "/@/model/generator/generatorConfig";
import { useMessage } from "/@/hooks/web/useMessage";
import { validateAITableName } from "/@/api/system/generator";

import { useI18n } from "/@/hooks/web/useI18n";
import { useModal } from "/@/components/Modal";
import { FieldInfo, TableInfo } from "/@/components/Designer";
import { buildUUID } from "/@/utils/uuid";
import { isBoolean } from "/@/utils/is";

const { t } = useI18n();
const { notification, createMessage } = useMessage();

const emit = defineEmits(["validateTable", "cancel"]);

const validateTable = ref(false);

const tableColumns = [
  {
    title: t("数据表名称"),
    dataIndex: "tableName",
    align: "center",
  },
  {
    title: t("数据表类别"),
    dataIndex: "isMain",
    align: "center",
    width: 200,
  },
  {
    title: t("备注"),
    dataIndex: "tableComment",
    align: "center",
  },
  {
    title: t("操作"),
    dataIndex: "action",
    align: "center",
  },
];

const fieldColumns = [
  {
    title: t("字段名"),
    dataIndex: "fieldName",
    align: "center",
  },
  {
    title: t("字段长度"),
    dataIndex: "fieldLength",
    align: "center",
  },
  {
    title: t("数据格式"),
    dataIndex: "fieldType",
    align: "center",
  },
  {
    title: t("备注"),
    dataIndex: "fieldComment",
    align: "center",
  },
  {
    title: t("操作"),
    dataIndex: "action",
    align: "center",
  },
];

const fieldTypeList = [
  {
    label: t("短文本"),
    value: 0,
  },
  {
    label: t("长文本（适用于多行文本等组件）"),
    value: 1,
  },
  {
    label: t("整数"),
    value: 2,
  },
  {
    label: t("小数"),
    value: 3,
  },
  {
    label: t("日期"),
    value: 4,
  },
  {
    label: t("日期时间"),
    value: 5,
  },
  {
    label: t("外键"),
    value: 6,
  },
  {
    label: t("长整数"),
    value: 7,
  },
  {
    label: t("时间"),
    value: 8,
  },
];

const generatorConfig = inject<GeneratorConfig>("generatorConfig");

const isFieldUpper = inject<Ref<boolean>>("isFieldUpper", ref(false));

const disabledFields = [
  "create_user_id",
  "create_user_name",
  "create_date",
  "modify_user_id",
  "modify_date",
  "delete_mark",
  "enabled_mark",
  "rule_user_id",
];
const props = defineProps({
  //是否是自定义表单生成代码
  isFormGenerator: {
    type: Boolean,
    default: false,
  },
  //是否是编辑状态
  isUpdate: {
    type: Boolean,
    default: false,
  },
  //新增时的表名集合
  beforeTableNames: {
    type: Array,
    default: () => [],
  },
});

const [registerTableName, { openModal, closeModal }] = useModal();
const tableInfo = inject<Ref<TableInfo[]>>("tableInfo", ref([]));
onMounted(() => {});
function addTableField(tableconfig, tableName) {
  tableconfig.push({
    key: buildUUID().replaceAll("-", ""),
    fieldName: "",
    fieldLength: 500,
    fieldType: 0,
    fieldComment: "",
    tableName,
  });
}
const handleBlur = (record) => {
  const name = snakeCase(record.tableName);
  record.tableName = isFieldUpper.value ? name.toUpperCase() : name;
};

const handleTypeChange = (value, record) => {
  if (value !== 0) {
    record.fieldLength = null;
  } else {
    record.fieldLength = 500;
  }
};

//验证当前步骤的数据
const validateStep = async (): Promise<boolean> => {
  try {
    const { tableStructureConfigs } = generatorConfig!;

    const tableNames: string[] = tableStructureConfigs!.map((x) => x.tableName);

    const reg = /^[a-zA-Z0-9_]*$/;
    //判断表名是否符合要求
    const isTableNotSuccess = tableStructureConfigs?.some((config: any) => {
      return !reg.test(config.tableName);
    });

    if (isTableNotSuccess) {
      notification.error({
        message: t("提示"),
        description: "表名只能包括字母、数字、下划线",
      }); //提示消息
      return false;
    }
    //判断字段名是否符合要求
    const isFieldNotSuccess = tableStructureConfigs?.some((config: any) => {
      const isNotPassValidation = config.tableFieldConfigs.some((fieldConfig: any) => {
        return (
          !reg.test(fieldConfig.fieldName) ||
          fieldConfig.fieldName.length > 30 ||
          fieldConfig.fieldName.length <= 0
        );
      });
      return isNotPassValidation;
    });
    if (isFieldNotSuccess) {
      notification.error({
        message: t("提示"),
        description:
          "字段名不能为空，且字段名必须以小写字母开头，只能包括小写字母、数字、下划线，并且不能超过30个字符",
      }); //提示消息
      return false;
    }
    const notHasRepeatName = tableStructureConfigs?.every((config) => {
      const nameArr = config.tableFieldConfigs.map((x) => x.fieldName);
      return [...new Set(nameArr)].length === nameArr.length;
    });
    if (!notHasRepeatName) {
      notification.error({
        message: t("提示"),
        description: t("同一个表内，不能有相同字段名"),
      }); //提示消息
      return false;
    }
    const testTableNames = tableNames.filter((x) => {
      return !props.beforeTableNames.includes(x);
    });
    const params = {
      id: generatorConfig!.databaseId!,
      tableNames: props.isUpdate ? testTableNames.toString() : tableNames.toString(),
    };

    tableInfo.value = [];

    let infos: any = [];

    if (tableStructureConfigs) {
      let flag = false;
      for (let i = 0; i < tableStructureConfigs.length; i++) {
        let o = tableStructureConfigs[i];
        let table = {
          name: o.tableName,
          isMain: o.isMain,
          isSubForm: o.isSubForm,
          fields: [] as FieldInfo[],
        };
        const fields: FieldInfo[] = [];
        // let isPk = false;
        o.tableFieldConfigs.forEach((k) => {
          // if (k.fieldName == o.pkField) isPk = true;
          fields.push({
            name: k.fieldName || "",
            length: k.fieldLength || 0,
            type: k.fieldType,
            isPk: false,
            isNullable: true,
          });
        });
        table.fields = fields;
        tableInfo.value.push(table);
        infos.push({
          tableName: o.tableName,
          isMain: o.isMain,
          pkField: o.pkField,
          pkType: "Long",
          relationField: !o.isSubForm && !o.isMain ? "" : undefined,
          relationTableField: !o.isSubForm && !o.isMain ? "" : undefined,
          isSubForm: isBoolean(o.isSubForm)
            ? o.isSubForm
            : !o.isMain && !o.parentTable
            ? true
            : false,
          parentTable: o.parentTable,
        });
        if (!o.isMain && !o.isSubForm) {
          const obj = tableStructureConfigs?.find((x) => x.tableName == o.parentTable);
          if (obj && obj.key && o.parentKey !== obj.key) {
            o.parentKey = obj.key;
          } else if (obj && !obj.key) {
            createMessage.warning("AI生成表结构有key值为空，请回上一步重新生成！");
            flag = true;
            break;
          } else if (!o.key) {
            createMessage.warning("AI生成表结构有key值为空，请回上一步重新生成！");
            flag = true;
            break;
          }
        }
      }
      if (flag) return false;
      generatorConfig!.tableConfigs = infos;
    }

    if (!props.isUpdate || (!props.isUpdate && testTableNames.length)) {
      await validateAITableName(params);
    }

    if (props.isUpdate) {
      if (!validateTable.value) {
        openModal();
        return false;
      }
    }
  } catch (error) {
    return false;
  }
  validateTable.value = false;
  return true;
};
async function handleEditSuccess() {
  validateTable.value = true;
  closeModal();
  emit("validateTable");
}
function handleCancel() {
  emit("cancel");
}
defineExpose({ validateStep });
</script>
<style lang="less" scoped>
.step4 {
  padding-top: 30px;

  p {
    color: @text-color;
  }
}

:deep(.ant-tag-orange),
:deep(.ant-tag-blue) {
  background: #fff;
  font-size: 13px;
}

:deep(.ant-spin-nested-loading) {
  overflow: hidden; //去掉表格嵌套子表滚动条
}

.node-title {
  border-bottom: 1px solid #e5e7eb;
  padding: 10px;
}
</style>
