<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:closable="false"
		:title="
			getI18n(
				'system',
				dataSourceId
					? 'SYSTEM_Edit_Data_Source'
					: 'SYSTEM_Add_Data_Source'
			)
		"
		: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_Data_Source_Name')"
				name="name"
			>
				<a-input
					autoComplete="off"
					v-model:value="formState.name"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Data_Source_Name'),
						])
					"
				/>
			</a-form-item>
			<!-- 类型 -->
			<a-form-item 
				:label="getI18n('system', 'SYSTEM_Data_Source_Type')"
				name="type"
			>
				<dict-select
					:parentId="CommonConstant.dictKey.type.value"
					:label="getI18n('system', 'SYSTEM_Data_Source_Type')"
					:value="formState.type"
					@on-change="onTypeChange"
				/>
			</a-form-item>
			<!-- 连接地址 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Data_Source_Url')"
				name="url"
			>
				<a-input
					autoComplete="off"
					v-model:value="formState.url"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Data_Source_Url'),
						])
					"
				/>
			</a-form-item>
			<!-- 用户名 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Data_Source_User_Name')"
				name="username"
			>
				<a-input
					autoComplete="off"
					v-model:value="formState.username"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Data_Source_User_Name'),
						])
					"
				/>
			</a-form-item>
			<!-- 密码 -->
			
			<a-form-item  v-if="ispwd"
				:label="getI18n('system', 'SYSTEM_Data_Source_Password')"
				name="password"
			>
				<a-input
					autoComplete="off"
					v-model:value="formState.password"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Data_Source_Password'),
						])
					"
				/>
			</a-form-item>
			<!-- 备注 -->
			<a-form-item
				:label="getI18n('system', 'SYSTEM_Data_Source_Remark')"
				name="remark"
			>
				<a-textarea
					v-model:value="formState.remark"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Data_Source_Remark'),
						])
					"
					:rows="3"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button
				type="primary"
				:loading="submitButtonLoading"
				@click="onTestButtonClick"
			>
				<send-outlined />
				<!-- 测试连接 -->
				{{ getI18n('system', 'SYSTEM_Data_Source_Test') }}
			</a-button>
			<a-button
				type="primary"
				:loading="submitButtonLoading"
				@click="onSubmitButtonClick"
			>
				<save-outlined />
				<!-- 确定 -->
				{{ getI18n('common', 'Common_Certain') }}
			</a-button>
			<a-button
				@click="
					() => {
						$emit('confirm-modal-cancel'), initFormStateData()
					}
				"
				:loading="submitButtonLoading"
			>
				<close-outlined />
				<!-- 取消 -->
				{{ getI18n('common', 'Common_Remove') }}
			</a-button>
		</template>
	</a-modal>
</template>
<script lang="ts">
import { DictSelect } from '@/views/components'
import {
	getDataSourceByIdApi,
	saveDataSourceApi,
	updateDataSourceApi,
	testConnectApi,
} from '@/api/data-source'
// import { getDataSourceListApi, getDataTableByIdApi } from '@/api/data-source'
import router from '@/router'
import { DataSourceModel } from '@/types/dataSource'
import { getI18n } from '@/utils/i18n'
import { RequestResult } from '@/utils/request/model'
import { message } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { defineComponent, reactive, ref, watch } from 'vue'
import { CommonConstant } from '@/utils/constant/index'
import { encode } from 'js-base64'
import {
	CloseOutlined,
	SaveOutlined,
	SendOutlined,
} from '@ant-design/icons-vue'

export default defineComponent({
	components: {
		DictSelect,
		CloseOutlined,
		SaveOutlined,
		SendOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 编辑所需要的id
		dataSourceId: {
			type: String,
			default: '',
		},
	},
	emits: ['confirm-modal-cancel', 'confirm-modal-refresh'],
	setup(props, context) {
		const ispwd = ref<boolean>(true)
		// 弹窗是否展示
		let confirmModalVisibleValue = ref(props.confirmModalVisible)
		const pageLoading = ref<boolean>(false)
		const submitButtonLoading = ref<boolean>(false)
		const formRef = ref()
		const formState = reactive<DataSourceModel>({})
		// 校验规则
		const formRules = {
			// 数据源名称
			name: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_Name'),
					]),
					trigger: 'change',
				},
			],
			// 连接地址
			url: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_Url'),
					]),
					trigger: 'change',
				},
			],
			// 类型
			type: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_Type'),
					]),
					trigger: 'change',
				},
			],
			// 用户名
			username: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_User_Name'),
					]),
					trigger: 'change',
				},
			],
			// 密码
			password: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_Password'),
					]),
					trigger: 'change',
				},
			],
			// 备注
			remark: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Data_Source_Remark'),
					]),
					trigger: 'change',
				},
			],
		}
		// 类型改变
		const onTypeChange = (val: string) => {
			formState.type = val
			formRef.value.validate('type')
		}
		// 初始化表单
		const initFormStateData = () => {
			formState.name = undefined
			formState.type = undefined
			formState.url = undefined
			formState.username = undefined
			formState.password = undefined
			formState.remark = undefined

			formRef.value && formRef.value.resetFields()
		}
		
		// 提交按钮被点击
		const onSubmitButtonClick = () => {
			formRef.value.validate().then(async () => {
				// 参数
				const params: DataSourceModel = {
					name: formState.name,
					type: formState.type,
					url: formState.url,
					username: formState.username,
					password: encode(formState.password),
					remark: formState.remark,
				}
				if (props.dataSourceId) {
					params.id = props.dataSourceId
					submitButtonLoading.value = true
					params.password = formState.password
					await updateDataSourceApi(params).finally(() => {
						submitButtonLoading.value = false
					})
				} else {
					submitButtonLoading.value = true
					await saveDataSourceApi(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 onTestButtonClick = () => {
			formRef.value.validate().then(async () => {
				submitButtonLoading.value = true
				props.dataSourceId
				// 参数
				const params: DataSourceModel = {
					name: formState.name,
					type: formState.type,
					url: formState.url,
					username: formState.username,
					password: encode(formState.password),
					remark: formState.remark,
				}
				if (props.dataSourceId) {
                     params.password = formState.password
				}
				await testConnectApi(params)
					.then(() => {
						Modal.success({
							title: getI18n(
								'system',
								'SYSTEM_Data_Source_Test_Success'
							),
							content: getI18n(
								'system',
								'SYSTEM_Data_Source_Test_Address',
								[formState.url || '']
							),
							okText: getI18n('common', 'Common_Certain'),
						})
					})
					.finally(() => {
						submitButtonLoading.value = false
					})
			})
			// .catch(()=>{
			// 		Modal.error({
			// 		title: getI18n('system', 'SYSTEM_Data_Source_Test_Fail'),
			// 		content: getI18n('system', 'SYSTEM_Data_Source_Test_Address',[formState.url||'']),
			// 		okText:getI18n('common', 'Common_Certain'),
			// 	});
			// }
			// )
		}

		// 修改时单条查询
		const getDataSourceById = async (id: string) => {
			const getDataSourceByIdRes: RequestResult<DataSourceModel> =
				await getDataSourceByIdApi({ id: id })
			formState.name = getDataSourceByIdRes.data[0].name
			formState.type = getDataSourceByIdRes.data[0].type
			formState.url = getDataSourceByIdRes.data[0].url
			formState.username = getDataSourceByIdRes.data[0].username
			formState.password = getDataSourceByIdRes.data[0].password
			formState.remark = getDataSourceByIdRes.data[0].remark
		}
		watch(
			() => props.confirmModalVisible,
			newValue => {
				confirmModalVisibleValue.value = newValue
			}
		)
		watch(
			() => props.dataSourceId,
			newValue => {
				newValue ? getDataSourceById(newValue) : initFormStateData()
			}
		)
		watch(
			() => props.dataSourceId,
			newValue => {
				if(newValue){
					ispwd.value = false 
				}else{
					ispwd.value = true
				}
				
			}
		)
		return {
			confirmModalVisibleValue,
			pageLoading,
			submitButtonLoading,
			formRef,
			formState,
			formRules,
			router,
			CommonConstant,
			ispwd,
			getI18n,
			onSubmitButtonClick,
			onTestButtonClick,
			initFormStateData,
			onTypeChange,
		}
	},
})
</script>
