<template>
	<!-- <base-search-label> -->
	<a-card class="base-card-full-screen">
		<a-card>
			<a-row>
				<!-- 数据源名称 -->
				<a-col :span="6" class="search-item">
					<label>{{
						getI18n('system', 'SYSTEM_Data_Source_Name')
					}}</label>
					<a-input
						autoComplete="off"
						:placeholder="
							getI18n('common', 'Common_Please_Enter', [
								getI18n('system', 'SYSTEM_Data_Source_Name'),
							])
						"
						v-model:value="dataParams.name"
					/>
				</a-col>
				<!-- 连接地址 -->
				<a-col :span="6" class="search-item">
					<label>{{
						getI18n('system', 'SYSTEM_Data_Source_Url')
					}}</label>
					<a-input
						autoComplete="off"
						:placeholder="
							getI18n('common', 'Common_Please_Enter', [
								getI18n('system', 'SYSTEM_Data_Source_Url'),
							])
						"
						v-model:value="dataParams.url"
					/>
				</a-col>
				<a-col :span="6">
					<div class="button-wrapper">
						<!-- 查询按钮 -->
						<a-button
							:loading="searchLoading"
							type="primary"
							@click="onSearchClick"
							class="button-item"
						>
							<search-outlined />
							{{ getI18n('common', 'Common_Search') }}
						</a-button>
						<!-- 重置按钮 -->
						<a-button
							:loading="searchLoading"
							@click="onResetClick"
							class="button-item"
						>
							<reload-outlined />
							{{ getI18n('common', 'Common_Clear') }}
						</a-button>
					</div>
				</a-col>
			</a-row>
		</a-card>
		<a-card>
			<div style="display: flex; justify-content: flex-start">
				<!-- 新增 -->
				<!-- v-if="
						getButtonPermission(
							CommonConstant.permissionKeys.datasourceSave.value
						)
					" -->
				<a-button
					type="primary"
					@click="onDataAddClick"
					style="margin-right: 1em"
				>
					<plus-outlined />
					{{ getI18n('common', 'Common_Add') }}
				</a-button>
				<!-- 删除按钮 -->
				<!-- <a-button
					type="primary"
					danger
					:disabled="!hasSelected"
					@click="onDatasDeleteClick"
				>
					{{ getI18n('common', 'Common_Delete') }}
				</a-button> -->
			</div>
			<a-table
				style="margin-top: 1em"
				:rowKey="record => record.id"
				:columns="columns"
				:loading="tableLoading"
				:data-source="dataSourceList"
				:bordered="true"
				:pagination="tablePagination"
				@change="onTableChange"
				:class="style['custom-table']"
			>
				<template #url="{ record }">
					<div style="text-align: left">{{ record.url }}</div>
				</template>
				<template #operation="{ record }">
					<div>
						<!-- 编辑 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.datasourceUpdate.value
								)
							" -->
						<a
							href="javascript:;"
							:class="style['table-button']"
							@click="() => onDataEditClick(record.id)"
							>{{ getI18n('common', 'Common_Edit') }}</a
						>
						<a
							href="javascript:;"
							:class="style['table-button']"
							@click="() => onEditPwdClick(record.id)">{{ getI18n('system', 'SYSTEM_Data_Source_uppwd') }}</a
						>
						<!-- 删除 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.datasourceDelete.value
								)
							" -->
						<a
							href="javascript:;"
							class="textC-red"
							:class="style['table-button']"
							@click="onDataDeleteClick(record.id)"
							style="margin-left: 1em"
							>{{ getI18n('common', 'Common_Delete') }}</a
						>
						<!-- </a-popconfirm> -->
					</div>
				</template>
			</a-table>
		</a-card>
	</a-card>

	<!-- 确认删除 -->
	<base-operational-qualification
		:confirm-modal-visible="confirmModalDeleteVisible"
		@confirm-modal-ok="onDeleteOkClick"
		@confirm-modal-cancel="onDeleteCancelClick"
		:ok-loading="deleteButtonLoading"
	/>

	<!-- 新增/编辑弹窗 -->
	<data-source-modal
		:confirmModalVisible="confirmAddModalVisible"
		@confirm-modal-cancel="onAddCancelClick"
		@confirm-modal-refresh="getFormList"
		:dataSourceId="dataSourceId"
	/>
	<data-source-edit-pwd
		:confirmModalVisible="confirmEditPwdModalVisible"
		@confirm-modal-cancel="onAddCancelClick"
		@confirm-modal-refresh="getFormList"
		:dataSourceId="dataSourceId"
	/>
</template>
<script lang="ts">
import {
	ReloadOutlined,
	SearchOutlined,
	PlusOutlined,
} from '@ant-design/icons-vue'
import { GetDataSourceParamsModel } from '@/api/data-source/model'
import { DataSourceModel } from '@/types/dataSource'
import { getI18n } from '@/utils/i18n'
import { defineComponent, onMounted, reactive, ref } from 'vue' // computed
import style from './index.module.less'
import { AntdPaginationType, AntdTableChangePageType } from '@/types/antd'
import { getDataSourceListApi, removeDataSourceApi } from '@/api/data-source'
import { RequestResult, PaginationData } from '@/utils/request/model'
import { DataSourceModal } from '../components'
import DataSourceEditPwd from '../components/DataSourceModalEditPwd.vue'
import { message } from 'ant-design-vue'

import { useRoute } from 'vue-router'
import Storage from 'web-storage-cache'
import { TOKEN_KEY } from '@/global/cacheKey'

import { CommonConstant } from '@/utils/constant'
// import { getButtonPermission } from '@/utils/tool/translateValue'

const columns = [
	// 数据源名称
	{
		title: getI18n('system', 'SYSTEM_Data_Source_Name'),
		dataIndex: 'name',
		align: 'center',
		width: '15%',
	},
	// 类型
	{
		title: getI18n('system', 'SYSTEM_Data_Source_Type'),
		dataIndex: 'type',
		align: 'center',
		width: '10%',
	},
	// 连接地址
	{
		title: getI18n('system', 'SYSTEM_Data_Source_Url'),
		dataIndex: 'url',
		align: 'center',
		width: '30%',
		slots: { customRender: 'url' },
	},
	// 用户名
	{
		title: getI18n('system', 'SYSTEM_Data_Source_User_Name'),
		dataIndex: 'username',
		align: 'center',
		width: '10%',
	},
	// 备注
	{
		title: getI18n('system', 'SYSTEM_Data_Source_Remark'),
		dataIndex: 'remark',
		align: 'center',
		width: '15%',
	},
	// 操作
	{
		title: getI18n('common', 'Common_Action'),
		align: 'center',
		key: 'operation',
		width: '15%',
		slots: { customRender: 'operation' },
	},
]

export default defineComponent({
	components: {
		DataSourceModal,
		DataSourceEditPwd,
		ReloadOutlined,
		SearchOutlined,
		PlusOutlined,
	},
	setup() {
		const route = useRoute()
		// 是否展示弹窗
		const confirmAddModalVisible = ref<boolean>(false)
		const confirmEditPwdModalVisible = ref<boolean>(false)
		// tableId
		const dataSourceId = ref<string>('')
		// 搜索按钮loading
		const searchLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		// 列表参数
		const dataParams = reactive<GetDataSourceParamsModel>({
			current: 1,
			size: 10,
		})
		const dataSourceList = ref<DataSourceModel[]>([])
		// 选中数据（深拷贝）
		// const selectedRowData = ref<DataSourceModel[]>([])
		// 列表多选
		// let tableSelectedRowKeys = ref<(string | number)[]>([])
		// 列表分页
		const tablePagination = reactive<AntdPaginationType>({
			current: 1,
			pageSize: 10,
			total: 0,
			showSizeChanger: true,
			showQuickJumper: true,
			pageSizeOptions: ['10', '20', '30', '40', '50'],
			showTotal: (total: number) =>
				getI18n('common', 'Common_Table_Total', [total.toString()]),
		})
		// 多选
		// const rowSelection = ref({
		// 	checkStrictly: false,
		// 	selectedRowKeys: tableSelectedRowKeys,
		// 	onChange: (key: (string | number)[], selectedRows) => {
		// 		selectedRowData.value = [
		// 			...selectedRowData.value,
		// 			...selectedRows,
		// 		]
		// 		tableSelectedRowKeys.value = key
		// 	},
		// })
		// 获取表单列表数据
		const getFormList = async () => {
			tableLoading.value = true
			let paramObj: GetDataSourceParamsModel = {
				size: dataParams.size,
				current: dataParams.current,
			}
			dataParams.name && (paramObj.name = dataParams.name)
			dataParams.url && (paramObj.url = dataParams.url)
			const getDataSourceListRes: RequestResult<
				PaginationData<DataSourceModel>
			> = await getDataSourceListApi(paramObj).finally(() => {
				tableLoading.value = false
				searchLoading.value = false
			})
			dataSourceList.value = getDataSourceListRes.data
			tablePagination.current = getDataSourceListRes.pageinfo.currentPage
			tablePagination.pageSize = getDataSourceListRes.pageinfo.perPage
			tablePagination.total = getDataSourceListRes.pageinfo.total
		}
		// 列表change事件
		const onTableChange = (page: AntdTableChangePageType) => {
			dataParams.size = page.pageSize
			dataParams.current = page.current
			getFormList()
		}
		// 搜索按钮事件
		const onSearchClick = async () => {
			searchLoading.value = true
			await getFormList()
		}
		// 重置按钮事件
		const onResetClick = () => {
			searchLoading.value = true
			dataParams.name = undefined
			dataParams.url = undefined
			dataParams.size = 10
			dataParams.current = 1
			getFormList()
		}
		// 新增表单事件
		const onDataAddClick = () => {
			confirmAddModalVisible.value = true
		}
		//修改密码
		const onEditPwdClick =(id: string) =>{
			dataSourceId.value = id
			confirmEditPwdModalVisible.value = true
		}
		// 修改表单事件
		const onDataEditClick = (id: string) => {
			dataSourceId.value = id
			confirmAddModalVisible.value = true
		}
		// 取消新增/修改事件
		const onAddCancelClick = () => {
			dataParams.name = ''
			dataSourceId.value = ''
			confirmAddModalVisible.value = false
			confirmEditPwdModalVisible.value = false
		}

		const confirmModalDeleteVisible = ref<boolean>(false) // 确认删除面板
		const deleteButtonLoading = ref<boolean>(false) // 确认删除按钮loading
		const deleteId = ref<string>('') // 删除参数
		// 删除按钮点击事件
		const onDataDeleteClick = (id: string) => {
			confirmModalDeleteVisible.value = true
			deleteId.value = id
		}
		// 确认删除
		const onDeleteOkClick = async () => {
			deleteButtonLoading.value = true
			await removeDataSourceApi({ id: deleteId.value }).finally(() => {
				deleteButtonLoading.value = false
			})
			message.success(getI18n('common', 'Common_Success'))

			// 如果是最后一页的最后一条数据，确认删除后查询上一页
			let _current = Math.ceil(
				(tablePagination.total - 1) / tablePagination.pageSize
			)
			dataParams.current =
				dataParams.current &&
				(dataParams.current > _current ? _current : dataParams.current)

			confirmModalDeleteVisible.value = false
			await getFormList()
		}
		// 取消删除
		const onDeleteCancelClick = () => {
			confirmModalDeleteVisible.value = false
		}

		onMounted(() => {
			if (route.query && route.query.token) {
				const localStorage = new Storage()
				localStorage.set(TOKEN_KEY, route.query.token?.toString())
				localStorage.set('token', route.query.token?.toString())
			}
			getFormList()

			// if (
			// 	!getButtonPermission([
			// 		CommonConstant.permissionKeys.datasourceSave.value, // 数据源管理新增
			// 		CommonConstant.permissionKeys.datasourceUpdate.value, // 数据源管理编辑
			// 		CommonConstant.permissionKeys.datasourceDelete.value, // 数据源管理删除
			// 	])
			// ) {
			// 	if (
			// 		columns.length > 0 &&
			// 		columns[columns.length - 1].key == 'operation'
			// 	) {
			// 		columns.pop()
			// 	}
			// }
		})
		return {
			style,
			columns,
			searchLoading,
			tableLoading,
			dataParams,
			dataSourceList,
			tablePagination,
			dataSourceId,
			confirmAddModalVisible,
			confirmEditPwdModalVisible,
			confirmModalDeleteVisible,
			deleteButtonLoading,
			// rowSelection,
			// hasSelected,
			// onDatasDeleteClick,
			onDeleteOkClick,
			onDeleteCancelClick,
			onAddCancelClick,
			getI18n,
			onSearchClick,
			onResetClick,
			onDataAddClick,
			onTableChange,
			onDataEditClick,
			onDataDeleteClick,
			getFormList,
			CommonConstant,
			onEditPwdClick,
			// getButtonPermission,
		}
	},
})
</script>
