<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="800"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    style="top: 40px"
    title="从SQL导入"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="数据库类型:" name="dbType">
        <a-select v-model:value="form.dbType" style="width: 100%" placeholder="请选择数据库类型">
          <a-select-option :value="tyItem.dictCode" v-for="tyItem in sqlTypeList" :key="tyItem.dictId">{{
            tyItem.dictName
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="Create Table:" name="createTableSql">
        <a-textarea v-model:value="form.createTableSql" placeholder="请输入Create Table" :rows="20" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup name="SheetSqlImport">
import { ref, onMounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { ModelApi } from '../../api/ModelApi';
import { encode } from 'js-base64';
import { SysDictTypeApi } from '@/components/DictSelect/api/SysDictTypeApi';

const props = defineProps({
  visible: Boolean,
  businessId: String,
  businessCategoryId: String,
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 表单数据
const form = ref({
  businessId: props.businessId,
  businessCategoryId: props.businessCategoryId
});

const formRef = ref(null);

// 验证规则
const rules = reactive({
  dbType: [{ required: true, message: '请选择数据库类型', type: 'string', trigger: 'change' }],
  createTableSql: [{ required: true, message: '请输入Create Table', type: 'string', trigger: 'blur' }]
});
// 数据库类型列表
const sqlTypeList = ref([]);

onMounted(() => {
  getSqlTypeList();
});

// 获取数据库类型列表
const getSqlTypeList = async () => {
  sqlTypeList.value = await SysDictTypeApi.getDictListByParams({ dictTypeCode: 'SQL_IMPORT_TYPE' });
  if (sqlTypeList.value.length > 0) {
    form.value.dbType = sqlTypeList.value[0].dictCode;
  }
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  await formRef.value.validate();
  let params = {
    ...form.value
  };
  params.createTableSql = encode(form.value.createTableSql);
  // 修改加载框为正在加载
  loading.value = true;
  ModelApi.sqlImport(params)
    .then(async result => {
      // 移除加载框
      loading.value = false;
      // 提示添加成功
      message.success('已成功导入' + result.data + '条');
      // 关闭弹框，通过控制visible的值，传递给父组件
      updateVisible(false);
      // 触发父组件done事件
      emits('done');
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>

<style></style>
