<template>
    <el-dialog :title="title" v-model="visible" width="80%" append-to-body
               :close-on-click-modal="false" draggable @closed="onCancel">
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="100px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('createTable.tableName')" prop="tableName">
                        <el-input v-model="form.tableName" :placeholder="t('createTable.inputTableNameTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('createTable.comments')" prop="comments">
                        <el-input v-model="form.comments" :placeholder="t('createTable.inputCommentsTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('createTable.databaseType')" prop="databaseType">
                        <el-select v-model="form.databaseType" :placeholder="t('createTable.databaseType')">
                            <el-option v-for="(item, index) in DIC_PROP.DATABASE_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('createTable.pkPolicy')" prop="pkPolicy">
                        <el-select v-model="form.pkPolicy" :placeholder="t('createTable.inputPkPolicyTip')" clearable>
                            <el-option label="ID_WORKER(分布式自增)" value="ID_WORKER"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('createTable.primaryKey')" prop="primaryKey">
                        <el-select v-model="form.primaryKey" :placeholder="t('createTable.inputPrimaryKeyTip')" clearable>
                            <el-option v-for="(item, index) in form.columns" :key="index" :label="item.name" :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="24" class="mb20">
                    <el-form-item :label="t('createTable.columnInfo')" prop="columns">
                        <el-table :data="form.columns" border style="width: 100%" max-height="500">
                            <el-table-column type="index" :label="t('createTable.index')" width="80">
                                <template #header>
                                    <el-button icon="Plus" size="small" type="primary" circle @click="onAddItem"></el-button>
                                </template>
                                <template #default="scope">
                                    <el-button icon="Minus" size="small" type="danger" circle @click="handleDelete(scope.$index, scope.row)"></el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" :label="t('createTable.name')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-model="scope.row.name" :placeholder="t('createTable.name')"/>
                                </template>
                            </el-table-column>
                            <el-table-column prop="comment" :label="t('createTable.comment')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-model="scope.row.comment" :placeholder="t('createTable.comment')"/>
                                </template>
                            </el-table-column>
                            <el-table-column prop="typeName" :label="t('createTable.typeName')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-select v-model="scope.row.typeName" :placeholder="t('createTable.typeName')" clearable filterable>
                                        <el-option v-for="(item, index) in DIC_PROP.COLUMN_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="precision" :label="t('createTable.precision')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input-number :min="0" :max="10000" v-model="scope.row.precision" :placeholder="t('createTable.precision')"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column prop="scale" :label="t('createTable.scale')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input-number :min="0" :max="10000" v-model="scope.row.scale" :placeholder="t('createTable.scale')"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column prop="defaultValue" :label="t('createTable.defaultValue')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-model="scope.row.defaultValue" :placeholder="t('createTable.defaultValue')"/>
                                </template>
                            </el-table-column>
<!--                            <el-table-column prop="primary" :label="t('createTable.primaryKey')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-radio-group v-model="scope.row.primary">
                                        <el-radio v-for="(item, index) in DIC_PROP.YES_OR_NO_NUM" :key="index" :label="item.value" >
                                            {{ getLabelByLanguage(item) }}
                                        </el-radio>
                                    </el-radio-group>
                                </template>
                            </el-table-column>-->
                            <el-table-column prop="nullable" :label="t('createTable.nullable')"  show-overflow-tooltip>
                                <template #default="scope">
                                    <el-radio-group v-model="scope.row.nullable">
                                        <el-radio v-for="(item, index) in DIC_PROP.YES_OR_NO_NUM" :key="index" :label="item.value" >
                                            {{ getLabelByLanguage(item) }}
                                        </el-radio>
                                    </el-radio-group>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <template #footer v-if="operType !== 'view'">
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
        </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="CreateTableDialog">

    import {useMessage, useMessageBox} from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/order/create-table'
    import { useI18n } from "vue-i18n"
    import {rule, validateNull} from '/@/utils/validate';
    import {utils} from "/@/flow/designer/utils/common";
    const emit = defineEmits(['refreshDone', 'refresh']);

    const { t } = useI18n();

    // 定义变量内容
    const dataFormRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const operType = ref(false);
    const title = ref('');
    // 定义字典

    // 提交表单数据
    const form = reactive({
        tableName: '',
        comments: '',
        databaseType: 'MySQL',
        pkPolicy: 'ID_WORKER',
        columns: [],
    });

    /**
     * 校验数据源名
     * @param {校验数据源名} rule
     * @param {*} value
     * @param {*} callback
     */
    let validateDsName = (rule, value, callback) => {
        let re = /(?=.*[a-z]|[A-Z])(?=.*_)/;
        if (value && (!(re).test(value))) {
            callback(new Error('数据源名称不合法, 组名_数据源名形式'))
        } else {
            callback()
        }
    }

    // 定义校验规则
    const dataRules = ref({
        tableName: [
            {required: true, message: '表名称不能为空', trigger: 'blur'},
            {max: 32, message: '长度在 32 个字符', trigger: 'blur'},
            {validator: validateDsName, trigger: 'blur'}
        ],
        comments: [{required: true, message: '表注释不能为空', trigger: 'blur'}],
        databaseType: [{required: true, message: '数据库类型不能为空', trigger: 'blur'}],
        pkPolicy: [{required: true, message: '主键策略不能为空', trigger: 'blur'}],
        primaryKey: [{required: true, message: '主键字段不能为空', trigger: 'blur'}],
        columns: [{required: true, message: '字段信息不能为空', trigger: 'blur'}],
    })

    // 打开弹窗
    const openDialog = (type: string, id: string) => {
        visible.value = true
        operType.value = type;
        form.id = ''

        if (type === 'add') {
            title.value = t('common.addBtn');
        } else if (type === 'edit') {
            title.value = t('common.editBtn');
        } else if (type === 'view') {
            title.value = t('common.viewBtn');
        }

        // 重置表单数据
        nextTick(() => {
            dataFormRef.value?.resetFields();
            if (!id) onAddItem()
        });

        // 获取CreateTable信息
        if (id) {
            form.id = id
            getCreateTableData(id)
        }
    };

    const isOnSubmitRef = ref(false);
    const onCancel = async () => {
        emit('refreshDone', form.tableName, operType.value, isOnSubmitRef.value);
    }

    // 提交
    const onSubmit = async () => {
        const valid = await dataFormRef.value.validate().catch(() => {});
        if (!valid) return false;

        try {
            if (form.id) {
                await useMessageBox().confirm("注意若已有表中存在数据时，修改字段类型可能会报错。请确保数据值可自由转换");
            }
        } catch {
            return;
        }

        try {
            loading.value = true;
            form.columnInfo = JSON.stringify(form.columns)
            let columns = {}
            form.columns.forEach(each => {
                if (validateNull(each.defaultValue)) each.defaultValue = null
                columns[each.name] = each
            })
            form.columnsInfo = JSON.stringify(columns)
            await addObj(form);
            useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            isOnSubmitRef.value = true;
            emit('refresh');
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    // 初始化表单数据
    const getCreateTableData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            let columnInfo = res.data.columnInfo;
            res.data.columns = validateNull(columnInfo) ? [] : JSON.parse(columnInfo);
            Object.assign(form, res.data)
        }).finally(() => {
            loading.value = false
        })
    };

    const onAddItem = () => {
        let find = form.columns.find(f => f.name === 'id');
        if (find) {
            let obj = {name: '', comment: '', typeName: '', precision: 0, scale: 0, defaultValue: null, nullable: 1, uniId: utils.getId()};
            form.columns.push(obj);
            return
        }
        // primary 1是0否，默认-1
        let id = {name: 'id', comment: '主键', typeName: 'bigint', precision: 20, scale: 0, defaultValue: null, nullable: 0, uniId: utils.getId()};
        let create_user = {name: 'create_user', comment: '创建人', typeName: 'bigint', precision: 20, scale: 0, defaultValue: null, nullable: 0, uniId: utils.getId()};
        let create_time = {name: 'create_time', comment: '创建时间', typeName: 'date', precision: 0, scale: 0, defaultValue: null, nullable: 1, uniId: utils.getId()};
        form.columns.push(id);
        form.columns.push(create_user);
        form.columns.push(create_time);
        form.primaryKey = id.name
    }

    const handleDelete = (index: number, row: any) => {
        if (row.name === 'id' || row.name === 'create_user' || row.name === 'create_time') {
            useMessage().warning("不能删除【主键】、【创建人】、【创建时间】");
            return
        }
        form.columns.splice(index, 1)
    }

    // 暴露变量
    defineExpose({
        openDialog
    });
</script>
