<template>
	<div>

		<el-card :body-style="cardBodyStyle">
			<el-form label-width="auto" ref="ruleFormRef" :model="form" :rules="rules" status-icon :inline="true">
				<el-form-item label="数据库" prop="dbType">
					<el-input v-model="form.dbType" style="width: 200px; " disabled>
					</el-input>
				</el-form-item>
				<el-form-item label="表空间" prop="tablespace" v-if="form.dbType=='oracle'">
					<el-input v-model="form.tablespace" style="width: 200px;" clearable @input="handleInputTablespace">
					</el-input>
					<el-select v-if="tablespaces.length>0" v-model="form.tablespace" style="width: 200px">
						<el-option v-for="item in tablespaces" :key="item.VALUE" :label="item.LABEL"
							:value="item.VALUE" />
					</el-select>
				</el-form-item>


				<el-form-item label=" ">
					<el-button @click="handleQueryDBType(ruleFormRef)">检测数据库</el-button>
					<el-button type="info" @click="handleReadDB(ruleFormRef)">读取数据库</el-button>
					<el-button type="warning" @click="handleAddField()">添加字段</el-button>
					<el-button type="danger" @click="handleAddDefault()">添加默认字段</el-button>

				</el-form-item>
			</el-form>
		</el-card>

		<el-card :body-style="cardBodyStyle">
			<el-table :data="tableData" border highlight-current-row @row-click="handleCurrentChange"
				:row-class-name="tableRowClassName">
				<el-table-column prop="id" label="id" width="60" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="fieldName" label="字段名" width="140" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="fieldComment" label="注释" width="140" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="fieldType" label="字段类型" width="140" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="dataLength" label="长度" width="80" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="dataPrecision" label="精度" width="80" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="nullFlag" label="非空" width="80" header-align="center" align="center"
					show-overflow-tooltip>
					<template #default="scope">
						<el-checkbox v-model="scope.row.nullFlag" disabled true-label="1" false-label="0"></el-checkbox>
					</template>
				</el-table-column>
				<el-table-column prop="pkFlag" label="主键" width="80" header-align="center" align="center"
					show-overflow-tooltip>
					<template #default="scope">
						<el-checkbox v-model="scope.row.pkFlag" disabled true-label="1" false-label="0"></el-checkbox>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="260px" header-align="center" align="center">
					<template #default="scope">
						<el-button type="primary" circle @click="handleUp(scope.row,scope.$index)"><el-icon>
								<Top />
							</el-icon>
						</el-button>
						<el-button type="primary" circle @click="handleDown(scope.row,scope.$index)"><el-icon>
								<Bottom />
							</el-icon>
						</el-button>
						<el-button type="warning" circle @click="handleEdit(scope.$index,scope.row )"><el-icon>
								<Edit />
							</el-icon></el-button>
						<el-button type="danger" circle @click="handleDelete(scope.$index,scope.row )"><el-icon>
								<Delete />
							</el-icon></el-button>
					</template>
				</el-table-column>


			</el-table>
		</el-card>



		<el-dialog :close-on-click-modal="false" draggable v-model="dialogVisible" width="700px">
			<el-form label-width="80px" :inline="true" ref="tableFieldRef" :model="tableField" :rules="tableFieldRules">
				<el-form-item label="字段名" prop="fieldName">
					<el-input v-model="tableField.fieldName" @input="handleInputFieldName" style="width: 200px">
					</el-input>
				</el-form-item>
				<el-form-item label="注释" prop="fieldComment">
					<el-input v-model="tableField.fieldComment" style="width: 200px">
					</el-input>
				</el-form-item>
				<el-form-item label="字段类型">
					<el-select v-model="tableField.fieldType" style="width: 200px">
						<el-option v-for="item in fieldTypeOptions" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<!--        <el-form-item label="主键">
          <el-checkbox v-model="tableField.pkFlag" true-label="1" false-label="0"></el-checkbox>
        </el-form-item> -->
				<el-form-item label="非空">
					<el-checkbox v-model="tableField.nullFlag" true-label="1" false-label="0"></el-checkbox>
				</el-form-item>
				<el-form-item label="长度">
					<el-input-number v-model="tableField.dataLength" :min="0" style="width: 120px;">
					</el-input-number>
				</el-form-item>
				<el-form-item label="精度">
					<el-input-number v-model="tableField.dataPrecision" :min="0" style="width: 120px;">
					</el-input-number>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="success" @click="handleComfirm(tableFieldRef)">确定</el-button>
				<el-button type="danger" @click="handleComfirmCancel">取消</el-button>
			</template>
		</el-dialog>

	</div>

</template>

<script setup>
	import {
		ref,
		reactive,
		onBeforeMount,
		getCurrentInstance
	} from 'vue'
	const {
		proxy
	} = getCurrentInstance()

	import style from '@/tools/style'
	const cardBodyStyle = ref(style.card)
	const inputStyle = ref(style.input)

	onBeforeMount(() => {
		handleQueryDBType()
	})

	const props = defineProps({
		// title: String, // 类型
		// likes: {
		//   type: Number,
		//   default: 0 // 默认值
		// },
		// isPublished: {
		//   type: Boolean,
		//   required: true // 必需的
		// },
		tableName: String
	})

	const form = ref({
		tableName: '',
		serviceName: '',
		moduleName: '',
		tablespace: '',
		javaPath: '',
		vuePath: '',
		appPath: ''
	})
	const tablespaces = ref([])
	const ruleFormRef = ref()
	const rules = reactive({
		tablespace: [{
			required: true,
			message: '请输入表空间',
			trigger: 'change' | 'blur',
		}]
	})



	const handleInputTableName = (value) => {
		form.value.tableName = value.toUpperCase()
	}

	const handleInputTablespace = (value) => {
		form.value.tablespace = value.toUpperCase()
	}




	const handleInputFieldName = (value) => {
		tableField.value.fieldName = value.toUpperCase()
	}
	const handleServiceNameInput = (value) => {

	}

	const tableData = ref([])
	const tableRowClassName = ({
		row,
		rowIndex
	}) => {
		row.sort = rowIndex + 1;
	}
	const selectedRowIndex = ref(0)

	const fieldTypeOptions = ref([])

	const handleQueryDBType = () => {

		var url = 'framework/Generate/queryDBType'
		var param = {}
		proxy.$axios.get(url, param).then(response => {
			if (response.data.code == 0) {
				ElMessage({
					message: response.data.data.dbType,
					type: 'success'
				})
				form.value.dbType = response.data.data.dbType
				if (form.value.javaPath == null || form.value.javaPath == '') {
					form.value.javaPath = response.data.data.javaPath
				}

				if (form.value.vuePath == null || form.value.vuePath == '') {
					form.value.vuePath = response.data.data.vuePath
				}
				if (form.value.appPath == null || form.value.appPath == '') {
					form.value.appPath = response.data.data.appPath
				}
				if (form.value.h5Path == null || form.value.h5Path == '') {
					form.value.h5Path = response.data.data.h5Path
				}


				console.log(response.data.data.tablespaces)
				if (form.value.dbType == 'oracle') {
					tablespaces.value = response.data.data.tablespaces
					fieldTypeOptions.value = [{
						value: 'VARCHAR2',
						label: 'VARCHAR2'
					}, {
						value: 'NUMBER',
						label: 'NUMBER'
					}, {
						value: 'DATE',
						label: 'DATE'
					}]

					{
						tablespace: [{
							required: true,
							message: '请输入表空间',
							trigger: 'change' | 'blur',
						}]
					}


				} else if (form.value.dbType == 'mysql') {
					tablespaces.value = []
					fieldTypeOptions.value = [{
						value: 'varchar',
						label: 'varchar'
					}, {
						value: 'int',
						label: 'int'
					}, {
						value: 'float',
						label: 'float'
					}, {
						value: 'double',
						label: 'double'
					}, {
						value: 'date',
						label: 'date'
					}, {
						value: 'datetime',
						label: 'datetime'
					}]


				}
			} else {
				tablespaces.value = []
				ElMessage({
					message: '操作失败' + response.data.msg,
					type: 'error'
				})
			}
		})
	}


	const handleReadDB = (ruleFormRef) => {
		ruleFormRef.validateField(['tableName', 'dbType'], valid => {
			if (valid) {
				var url = 'framework/Generate/query'
				var param = {
					tableName: props.tableName //form.value.tableName
				}
				proxy.$axios.post(url, param).then(response => {
					if (response.data.code == 0) {
						form.value.tablespace = response.data.data.tablespace
						tableData.value = response.data.data.fields
					} else {
						ElMessage({
							message: '操作失败' + response.data.msg,
							type: 'error'
						})
						tableData.value = []
					}
				})
			} else {
				console.log('error submit!!');
				return false;
			}
		})
	}

	const handleSearch = () => { 
		var url = 'framework/LowCode/query'
		var param = {
			tableName: props.tableName
		}
		proxy.$axios.get(url, param).then(response => {
			if (response.data.code == 0) {
				form.value = response.data.data
				tableData.value = response.data.data.fields
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
				tableData.value = []
			}
		})
	}




	const tableField = ref({
		fieldName: '',
		fieldType: 'VARCHAR2',
		fieldComment: '',
		dataLength: 0,
		dataPrecision: 0,
		nullFlag: '0',
		pkFlag: '0',

		controllerType: '',
		inputFlag: false,
		requireFlag: false,

		queryFlag: false,
		fuzzyFlag: false,
		dateFlag: false,
	})


	const tableFieldRules = reactive({
		fieldName: [{
			required: true,
			message: '不能为空',
			trigger: 'blur' | 'change'
		}],
		fieldComment: [{
			required: true,
			message: '不能为空',
			trigger: 'blur' | 'change'
		}],
	})





	const dialogVisible = ref(false)
	const handleAddField = () => {
		if (form.value.dbType == null || form.value.dbType == '') {
			ElMessage({
				message: '请先检测数据库',
				type: 'error'
			})
			return
		}
		tableField.value = {
			fieldName: '',
			fieldType: '',
			fieldComment: '',
			dataLength: 0,
			dataPrecision: 0,
			nullFlag: '0',
			pkFlag: '0',
			flag: 'add'
		}
		dialogVisible.value = true
	}
	const handleAddDefault = () => {
		if (form.value.dbType == null || form.value.dbType == '') {
			ElMessage({
				message: '请先检测数据库',
				type: 'error'
			})
			return
		}
		var url = 'framework/LowCode/queryDefault'
		var param = {
			dbType: form.value.dbType
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {
				tableData.value = tableData.value.concat(response.data.data)
			} else {
				ElMessage({
					message: '操作失败' + response.data.msg,
					type: 'error'
				})
			}
		})
	}

	const tableFieldRef = ref()
	const handleComfirm = (tableFieldRef) => {
		tableFieldRef.validate((valid, fields) => {
			if (valid) {
				if (tableField.value.flag == 'add') {
					tableData.value.splice(selectedRowIndex.value, 0, tableField.value)
				}
				dialogVisible.value = false
			} else {
				console.log('error submit!!');
				return false;
			}
		})
	}
	const handleComfirmCancel = () => {
		dialogVisible.value = false
	}


	const handleUp = (row, index) => {
		if (index == 0) {
			return
		}
		var temp = row
		tableData.value.splice(index, 1)
		tableData.value.splice(index - 1, 0, temp)
	}
	const handleDown = (row, index) => {
		if (index == tableData.value.length - 1) {
			return
		}
		var temp = row
		tableData.value.splice(index, 1)
		tableData.value.splice(index + 1, 0, temp)
	}
	const handleCurrentChange = (val) => {
		if (val) {
			selectedRowIndex.value = val.sort
		} else {
			selectedRowIndex.value = 0
		}
	}
	const handleEdit = (index, row) => {
		tableField.value = row
		tableField.value.flag = 'modify'
		dialogVisible.value = true
	}

	const handleDelete = (index, row) => {
		tableData.value.splice(index, 1)
		var url = 'framework/LowCode/remove'
		var param = {
			id: row.id,
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {

			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
			}
		})
	}


	const handleSave = (callback) => {
		if (form.value.dbType == 'oracle') {
			if (form.value.tablespace == '') {
				ElMessage({
					type: 'error',
					message: 'oracle必须填写表空间'
				});
				return
			}
		}
		form.value.tableName = props.tableName
		// ruleFormRef.validateField(['tablespace', 'dbType'], valid => {
		// 	if (valid) {
		var url = 'framework/LowCode/save'
		var param = {
			form: JSON.stringify(form.value),
			json: JSON.stringify(tableData.value)
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {
				ElMessage({
					type: 'success',
					message: '操作成功!'
				});
				handleSearch()
				callback()
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
			}
		})
		// } else {
		// 	console.log('error submit!!')
		// 	return false
		// }
		//})
	}




	const handleCreate = (ruleFormRef) => {
		var v = []
		if (form.value.dbType == 'oracle') {
			v = ['tableName', 'dbType', 'tablespace']
		} else {
			v = ['tableName', 'dbType']
		}
		ruleFormRef.validateField(v, valid => {
			if (valid) {
				var url = 'framework/Generate/create'
				var param = {
					form: JSON.stringify(form.value),
					json: JSON.stringify(tableData.value)
				}
				proxy.$axios.post(url, param).then(response => {
					if (response.data.code == 0) {
						ElMessage({
							type: 'success',
							message: response.data.data
						})
					} else {
						ElMessage({
							type: 'error',
							message: '操作失败!' + response.data.msg
						})
					}
				})
			} else {
				console.log('error submit!!')
				return false
			}
		})
	}


	const handleCreateSqlOracle = (ruleFormRef) => {
		ruleFormRef.validateField(['tableName', 'dbType', 'tablespace'], valid => {
			if (valid) {
				createSql('oracle')
			} else {
				console.log('error submit!!');
				return false;
			}
		})


	}
	const handleCreateSqlMysql = (ruleFormRef) => {
		ruleFormRef.validateField(['tableName', 'dbType'], valid => {
			if (valid) {
				createSql('mysql')
			} else {
				console.log('error submit!!');
				return false;
			}
		})

	}
	const createSql = (dbType) => {
		var url = 'framework/Generate/createSql'
		var param = {
			form: JSON.stringify(form.value),
			json: JSON.stringify(tableData.value),
			dbType: dbType
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {
				ElMessage({
					type: 'success',
					message: response.data.data
				});
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
			}
		})
	}



	defineExpose({
		ruleFormRef,
		handleSearch,
		handleSave,
		form
	})
</script>

<style>
</style>