<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:closable="false"
		:title="
			getI18n(
				'system',
				formId ? 'SYSTEM_Edit_Form_Name' : 'SYSTEM_Add_Form_Name'
			)
		"
		:maskClosable="false"
		:width="800"
	>
		<a-form
			:model="formState"
			:label-col="{ span: 6 }"
			:wrapper-col="{ span: 18 }"
			:rules="formRules"
			ref="formRef"
		>
			<!-- 表单名称 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Form_Name')"
				name="name"
			>
				<a-input
					autoComplete="off"
					v-model:value="formState.name"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Form_Name'),
						])
					"
				/>
			</a-form-item>
			<!-- 数据源 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Form_Data_Source')"
				name="datasourceId"
			>
				<a-select
					style="width: 100%"
					:allowClear="true"
					v-model:value="formState.datasourceId"
					:placeholder="
						getI18n('common', 'Common_Please_Select', [
							getI18n('system', 'SYSTEM_Form_Data_Source'),
						])
					"
					:options="dataSourceData"
					@change="onDataSourceChange"
				/>
			</a-form-item>
			<!-- 数据表 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Form_Table_Name')"
				name="tableName"
			>
				<a-select
					style="width: 100%"
					:allowClear="true"
					v-model:value="formState.tableName"
					:placeholder="
						getI18n('common', 'Common_Please_Select', [
							getI18n('system', 'SYSTEM_Form_Table_Name'),
						])
					"
					:options="dataTableData"
				/>
			</a-form-item>
			<!-- 备注 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Form_Remark')"
				name="remark"
			>
				<a-textarea
					v-model:value="formState.remark"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Form_Remark'),
						])
					"
					:rows="3"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button
				type="primary"
				:loading="submitButtonLoading"
				@click="onSubmitButtonClick"
			>
				<SaveOutlined />
				<!-- 确定 -->
				{{ getI18n('common', 'Common_Certain') }}
			</a-button>
			<a-button
				@click="
					() => {
						$emit('confirm-modal-cancel'), initFormStateData()
					}
				"
				:loading="submitButtonLoading"
			>
				<CloseOutlined />
				<!-- 取消 -->
				{{ getI18n('common', 'Common_Remove') }}
			</a-button>
		</template>
	</a-modal>
</template>
<script lang="ts">
import { CloseOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { getFormByIdApi, saveFormApi, updateFormApi } from '@/api/form'
import { getDataSourceListApi, getDataTableByIdApi } from '@/api/data-source'
import router from '@/router'
import { FormModel } from '@/types/form'
import { DataSourceModel } from '@/types/dataSource'
import { getI18n } from '@/utils/i18n'
import { RequestResult, PaginationData } from '@/utils/request/model'
import { message } from 'ant-design-vue'
import { defineComponent, reactive, ref, watch } from 'vue' // onMounted

export default defineComponent({
	components: {
		CloseOutlined,
		SaveOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 编辑所需要的id
		formId: {
			type: String,
			default: '',
		},
	},
	emits: ['confirm-modal-cancel', 'confirm-modal-refresh'],
	setup(props, context) {
		// 弹窗是否展示
		let confirmModalVisibleValue = ref(props.confirmModalVisible)
		const pageLoading = ref<boolean>(false)
		const submitButtonLoading = ref<boolean>(false)
		const formRef = ref()
		const formState = reactive<FormModel>({
			// 表单名称
			name: '',
			// 表单备注
			remark: '',
		})
		// 校验规则
		const formRules = {
			// 表单名称
			name: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Form_Name'),
					]),
					trigger: 'change',
				},
			],
			// 数据源
			datasourceId: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Select', [
						getI18n('system', 'SYSTEM_Form_Data_Source'),
					]),
					trigger: 'change',
				},
			],
			// 数据表
			tableName: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Select', [
						getI18n('system', 'SYSTEM_Form_Table_Name'),
					]),
					trigger: 'change',
				},
			],
			// 表单备注
			remark: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Form_Remark'),
					]),
					trigger: 'change',
				},
			],
		}
		// 初始化表单
		const initFormStateData = () => {
			formState.name = undefined
			formState.remark = undefined
			formState.datasourceId = undefined
			formState.tableName = undefined
		}
		// 提交按钮被点击
		const onSubmitButtonClick = () => {
			formRef.value.validate().then(async () => {
				// 参数
				const params: FormModel = {
					name: formState.name,
					remark: formState.remark,
					datasourceId: formState.datasourceId,
					tableName: formState.tableName,
				}
				if (props.formId) {
					params.id = props.formId
					submitButtonLoading.value = true
					await updateFormApi(params).finally(() => {
						submitButtonLoading.value = false
					})
				} else {
					submitButtonLoading.value = true
					await saveFormApi(params).finally(() => {
						submitButtonLoading.value = false
					})
				}
				message.success(getI18n('common', 'Common_Success'))
				context.emit('confirm-modal-cancel')
				initFormStateData()
				confirmModalVisibleValue.value = false
				context.emit('confirm-modal-refresh')
			})
		}
		// 数据表列表
		const dataTableData = ref<DataSourceModel[]>([])
		const onDataSourceChange = async (id: string) => {
			// formState.tableName = undefined
			// 初始化数据表列表
			const dataTableDataResult: RequestResult<DataSourceModel[]> =
				await getDataTableByIdApi({ id: id })
			dataTableData.value = JSON.parse(
				JSON.stringify(dataTableDataResult.data)
					.replace(/tableComment/g, 'label')
					.replace(/tableName/g, 'value')
			).map(v => {
				return {
					label: v.label || v.value,
					value: v.value,
				}
			})
		}
		// 修改时单条查询
		const getFormById = async (id: string) => {
			const getFormByIdRes: RequestResult<FormModel> =
				await getFormByIdApi({ id: id })
			if (getFormByIdRes.data[0].datasourceId) {
				onDataSourceChange(getFormByIdRes.data[0].datasourceId)
			}
			formState.name = getFormByIdRes.data[0].name
			formState.datasourceId = getFormByIdRes.data[0].datasourceId
			formState.tableName = getFormByIdRes.data[0].tableName
			formState.remark = getFormByIdRes.data[0].remark
		}
		// 数据源列表
		const dataSourceData = ref<DataSourceModel[]>([])
		// 初始化数据源列表
		const getDataSourceList = async () => {
			const dataSourceDataResult: RequestResult<
				PaginationData<DataSourceModel>
			> = await getDataSourceListApi({
				fileds: 'id,name',
			})
			if(dataSourceDataResult.data){
				dataSourceData.value = JSON.parse(
					JSON.stringify(dataSourceDataResult.data)
						.replace(/name/g, 'label')
						.replace(/id/g, 'value')
				)
		    }
		}

		watch(
			() => props.confirmModalVisible,
			async newValue => {
				confirmModalVisibleValue.value = newValue
				newValue && (await getDataSourceList())
			}
		)
		watch(
			() => props.formId,
			newValue => {
				newValue ? getFormById(newValue) : initFormStateData()
			}
		)
		// onMounted(() => {
		// 	getDataSourceList()
		// })
		return {
			confirmModalVisibleValue,
			pageLoading,
			submitButtonLoading,
			formRef,
			formState,
			formRules,
			router,
			dataSourceData,
			dataTableData,
			getI18n,
			onSubmitButtonClick,
			initFormStateData,
			onDataSourceChange,
		}
	},
})
</script>
