<template>
	<a-form
		:label-col="{ span: 2 }"
		:model="formState"
		:wrapper-col="{ span: 22 }"
		autocomplete="off"
		labelAlign="left"
		name="basic"
		:rules="rules"
		@finish="onFinish"
		@finishFailed="useUpdateMethod.formFail"
	>
		<a-form-item label="表编号" name="tableName">
			<span v-if="props.id">{{ formState.tableName }}</span>
			<a-input v-else v-model:value="formState.tableName" placeholder="请输入表编号信息" />
		</a-form-item>
		<a-form-item label="表名称" name="tableComment">
			<a-input v-model:value="formState.tableComment" placeholder="请输入表名称信息" />
		</a-form-item>
		<a-form-item label="表结构">
			<TableColumnsManage
				ref="tableColumnsManage"
				:default-column-list="defaultColumnNameList"
				:list="showDataList"
				@addRow="handleClickAddRow()"
				@remove="handeRemoveItem"
			/>
		</a-form-item>
		<a-form-item :wrapper-col="{ offset: 4, span: 14 }">
			<a-button html-type="submit" style="margin-left: 10px" type="primary">确定</a-button>
			<a-button style="margin-left: 10px" @click="useUpdateMethod.handleCancel()">取消</a-button>
		</a-form-item>
	</a-form>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import requestMethod from '../../../api/dynamic/table'
import TableColumnsManage from './table-columns/Manage.vue'
import { DynamicFormTableColumnVo } from '../../../entity/dynamic/dynamic-form-table'
import { updateMethod } from '../../../components/form/method'
import { messageMethod } from '../../../utils/message-util'
import defaultColumnList from './table-columns/default-column-list'
import { QueryObjectType } from '../../../http/request-model'
import { DEFAULT_DYNAMIC_TABLE_PREFIX } from '../common'

const props = defineProps<{
	id?: string
	/**
	 * 默认的外键关联
	 */
	tableId?: string
	tableTitle?: string
}>()

// 操作页面的公用方法
const useUpdateMethod = updateMethod()

// 获取到表格组件ref
const tableColumnsManage = ref<InstanceType<typeof TableColumnsManage>>(null)

// 表单字段列表table_1645680625587
const dataList = ref<Array<DynamicFormTableColumnVo>>([])

const showDataList = computed<Array<DynamicFormTableColumnVo>>(() => dataList.value.filter(item => item.saveType !== 3))

const rules = {
	tableName: [
		{ trigger: ['change', 'blur'], message: '请输入数据表编号', required: true, whitespace: true },
		{ trigger: ['change', 'blur'], message: '数据表编号长度控制在5-32位', min: 5, max: 32 },
		{ trigger: ['change', 'blur'], message: '数据表编号只能为：字母、数字、_', pattern: '^[A-Za-z0-9_]+$' }
	],
	tableComment: [
		{ trigger: ['change', 'blur'], message: '请输入数据表名称', required: true, whitespace: true },
		{ trigger: ['change', 'blur'], message: '数据表名称长度控制在2-16位', min: 2, max: 16 }
	]
}

interface FormState {
	// 表单编号（唯一）
	tableName: string
	// 表单名称（中文）
	tableComment: string
	// 表类型、模块
	tableType: string
	// 表内容
	tableContent: string
	version: number
}

const formState = reactive<FormState>({
	tableName: '',
	tableComment: '',
	tableType: '',
	tableContent: '',
	version: 0
})

// 默认字段的名称
const defaultColumnNameList = computed<string[]>(() => defaultColumnList.map(item => item.columnName))

// 操作类型add或者update
let operationType = 'add'
// 表格名称
let tableName = ''

/**
 * 信息初始化
 */
const init = () => {
	new Promise(resolve => {
		if (props.id) {
			requestMethod.getById(props.id).then(data => {
				tableName = data.data.tableName
				formState.tableName = data.data.tableName.replace(DEFAULT_DYNAMIC_TABLE_PREFIX, '')
				formState.tableComment = data.data.tableComment
				formState.tableType = data.data.tableType
				formState.tableContent = data.data.tableContent
				formState.version = data.data.version || 0
				dataList.value.push(...data.data.columnList)
				resolve('update')
			})
		} else {
			formState.tableName = `table_${new Date().getTime()}`
			dataList.value.push(...defaultColumnList)
			// 判断有没有默认的外键字段
			if (props.tableId) {
				dataList.value.push(getFkTableColumn(props.tableId, props.tableTitle || ''))
			}
			resolve('add')
		}
	}).then(type => {
		operationType = type as string
	})
}

/**
 * 提交表单
 * @param value
 */
const onFinish = async (value: FormState) => {
	const columnList = dataList.value
	if (columnList.length === 0) {
		messageMethod.error('字段信息不能为空')
		return
	}
	// 判断如果有
	columnList.forEach(item => {
		if (/^add_\d+$/.test(item.id)) {
			item.id = ''
			item.saveType = 0
		}
	})
	const data = {
		...(value as unknown as QueryObjectType),
		version: formState.version || 0,
		tableName: operationType === 'add' ? formState.tableName : tableName,
		columnList
	}
	if (operationType === 'add') {
		const resultModel = await requestMethod.add({ ...(data as unknown as QueryObjectType) })
		messageMethod.success(resultModel.message)
		useUpdateMethod.handleSave()
	} else {
		const resultModel = await requestMethod.update({
			...data,
			id: props.id
		})
		messageMethod.success(resultModel.message)
		useUpdateMethod.handleSave()
	}
}

/**
 * 添加一行数据
 */
const handleClickAddRow = () => {
	dataList.value.push(getDefaultData())
}

const getFkTableColumn = (tableId: string, tableName: string): DynamicFormTableColumnVo => {
	return {
		columnComment: tableName,
		showTextField: '',
		columnKey: '',
		columnName: `column_${new Date().getTime()}`,
		columnKeyId: tableId,
		columnKeyType: 3,
		columnSize: '32',
		columnType: 'varchar',
		defaultValue: '',
		fkTableId: '',
		id: `add_${new Date().getTime()}`,
		isRequired: 0,
		saveType: 0,
		scoreCode: 0,
		searchType: 0,
		showType: 1,
		tableName: '',
		updateType: 0,
		gmtCreate: '',
		gmtModified: ''
	}
}

const getDefaultData = (): DynamicFormTableColumnVo => {
	return {
		columnComment: '',
		showTextField: '',
		columnKey: '',
		columnName: `column_${new Date().getTime()}`,
		columnKeyId: 'varchar',
		columnKeyType: 1,
		columnSize: '50',
		columnType: 'varchar',
		defaultValue: '',
		fkTableId: '',
		id: `add_${new Date().getTime()}`,
		isRequired: 0,
		saveType: 0,
		scoreCode: 0,
		searchType: 0,
		showType: 1,
		tableName: '',
		updateType: 0,
		gmtCreate: '',
		gmtModified: ''
	}
}

/**
 * 移除选项信息
 * @param id
 */
const handeRemoveItem = (id: string) => {
	if (id) {
		const index = dataList.value.findIndex(item => item.id == id) || -1
		if (index >= 0) {
			dataList.value[index].saveType = 3
			messageMethod.success('移除成功')
		}
	}
}

void init()
</script>

<style scoped></style>
