// 表单管理
<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_Form_Name') }}</label>
					<a-input
						:placeholder="
							getI18n('common', 'Common_Please_Enter', [
								getI18n('system', 'SYSTEM_Form_Name'),
							])
						"
						v-model:value="formParams.name"
					/>
				</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.formSave.value
						)
					" -->
				<a-button
					type="primary"
					@click="onFormAddClick"
					style="margin-right: 1em"
				>
					<plus-outlined />
					{{ getI18n('common', 'Common_Add') }}
				</a-button>
				<!-- 删除按钮 -->
				<!-- <a-button
					type="primary"
					danger
					:disabled="!hasSelected"
					@click="onFormsDeleteClick"
				>
					{{ getI18n('common', 'Common_Delete') }}
				</a-button> -->
				<!-- 数据源管理 -->
				<a-button
					type="primary"
					@click="onDataSourceClick"
					style="margin-right: 1em"
				>
					<plus-outlined />
					{{ getI18n('system', 'SYSTEM_Data_Source_Management') }}
				</a-button>
			</div>

			<a-table
				style="margin-top: 1em"
				:rowKey="records => records.id"
				:columns="columns"
				:loading="tableLoading"
				:data-source="formList"
				:bordered="true"
				:pagination="tablePagination"
				@change="onTableChange"
				:class="style['custom-table']"
			>
				<template #operation="{ record }">
					<div>
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys.formField
										.value
								)
							" -->
						<!-- 字段设置 -->
						<a
							href="javascript:;"
							:class="style['table-button']"
							@click="() => onFormItemClick(record)"
							>{{ getI18n('system', 'SYSTEM_Form_Item') }}</a
						>
						<!-- 编辑 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys.formUpdate
										.value
								)
							" -->
						<a
							href="javascript:;"
							@click="() => onFormEditClick(record.id)"
							style="margin-left: 8px"
							:class="style['table-button']"
							>{{ getI18n('common', 'Common_Edit') }}</a
						>
						<!-- 删除 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys.formDelete
										.value
								)
							" -->
						<a
							href="javascript:;"
							class="textC-red"
							:class="style['table-button']"
							@click="onFormDeleteClick(record.id)"
							style="margin-left: 8px"
							>{{ getI18n('common', 'Common_Delete') }}</a
						>
					</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"
	/>

	<!-- 新增/编辑弹窗 -->
	<form-modal
		:confirmModalVisible="confirmAddModalVisible"
		@confirm-modal-cancel="onAddCancelClick"
		@confirm-modal-refresh="getFormList"
		:formId="formId"
	/>
</template>
<script lang="ts">
import { GetFormParamsModel } from '@/api/form/model'
import {
	ReloadOutlined,
	SearchOutlined,
	PlusOutlined,
} from '@ant-design/icons-vue'
import { FormModel } from '@/types/form'
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 { getFormListApi, removeFormApi } from '@/api/form'
import { RequestResult, PaginationData } from '@/utils/request/model'
import { FormModal } from '../components'
import { message } from 'ant-design-vue'
import router from '@/router'

import { PageEnum } from '@/enums/pageEnum'
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_Form_Name'),
		dataIndex: 'name',
		align: 'center',
		width: '30%',
	},
	// 表名
	{
		title: getI18n('system', 'SYSTEM_Form_Table_Name'),
		dataIndex: 'tableName',
		align: 'center',
		width: '25%',
	},
	// 数据源ID
	{
		title: getI18n('system', 'SYSTEM_Form_Data_Source'),
		dataIndex: 'datasourceName',
		align: 'center',
		width: '10%',
	},
	// 备注
	{
		title: getI18n('system', 'SYSTEM_Form_Remark'),
		dataIndex: 'remark',
		align: 'center',
		width: '20%',
	},
	// 操作
	{
		title: getI18n('common', 'Common_Action'),
		align: 'center',
		key: 'operation',
		width: '15%',
		slots: { customRender: 'operation' },
	},
]

export default defineComponent({
	components: {
		FormModal,
		ReloadOutlined,
		SearchOutlined,
		PlusOutlined,
	},
	setup() {
		const route = useRoute()
		// 是否展示弹窗
		const confirmAddModalVisible = ref<boolean>(false)
		// tableId
		const formId = ref<string>('')
		// tableName
		const tableName = ref<string>('')
		// 搜索按钮loading
		const searchLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		// 列表参数
		const formParams = reactive<GetFormParamsModel>({
			current: 1,
			size: 10,
		})
		const formList = ref<FormModel[]>([])
		// 选中数据（深拷贝）
		// const selectedRowData = ref<FormModel[]>([])
		// 列表多选
		// 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: GetFormParamsModel = {
				size: formParams.size,
				current: formParams.current,
			}
			formParams.name && (paramObj.name = formParams.name)
			const res: RequestResult<PaginationData<FormModel>> =
				await getFormListApi(paramObj).finally(() => {
					tableLoading.value = false
					searchLoading.value = false
				})
			formList.value = res.data
			tablePagination.current = res.pageinfo.currentPage
			tablePagination.pageSize = res.pageinfo.perPage
			tablePagination.total = res.pageinfo.total
		}
		// 列表change事件
		const onTableChange = (page: AntdTableChangePageType) => {
			formParams.size = page.pageSize
			formParams.current = page.current
			getFormList()
		}
		// 搜索按钮事件
		const onSearchClick = async () => {
			searchLoading.value = true
			await getFormList()
		}
		// 重置按钮事件
		const onResetClick = () => {
			searchLoading.value = true
			formParams.name = undefined
			formParams.size = 10
			formParams.current = 1
			getFormList()
		}
		// 新增表单事件
		const onFormAddClick = () => {
			confirmAddModalVisible.value = true
		}
		// 修改表单事件
		const onFormEditClick = (id: string) => {
			formId.value = id
			confirmAddModalVisible.value = true
		}
		// 取消新增/修改事件
		const onAddCancelClick = () => {
			formParams.name = ''
			formId.value = ''
			confirmAddModalVisible.value = false
		}

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

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

			confirmModalDeleteVisible.value = false
			await getFormList()
		}
		// 取消删除
		const onDeleteCancelClick = () => {
			confirmModalDeleteVisible.value = false
		}
		// 是否选中多选框
		// const hasSelected = computed(
		// 	() => tableSelectedRowKeys.value.length > 0
		// )

		// 列表删除
		// const onFormsDeleteClick = () => {
		// 	confirmModalDeleteVisible.value = true
		// 	deleteId.value = tableSelectedRowKeys.value.toString()
		// }

		const onFormItemClick = (data: FormModel) => {
			// id, tableName
			if (route.path === PageEnum.BASE_Form_List_View) {
				router.push({
					name: 'FormItemListView',
					params: {
						id: data.id,
					},
				})
			} else {
				router.push({
					name: 'FormItemList',
					params: {
						id: data.id,
					},
				})
			}
		}
		// 删除表单事件
		// const onFormDeleteClick = async (id: string) => {
		// 	tableLoading.value = true
		// 	await removeFormApi({ id })
		// 	message.success(getI18n('common', 'Common_Success'))
		// 	await getFormList()
		// }

		// 跳转数据管理列表
		const onDataSourceClick = () => {
			router.push({ name: 'DataSource' })
		}

		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.formSave.value, // 表单管理新增
			// 		CommonConstant.permissionKeys.formUpdate.value, // 表单管理编辑
			// 		CommonConstant.permissionKeys.formDelete.value, // 表单管理删除
			// 		CommonConstant.permissionKeys.formField.value, // 表单管理字段设置
			// 	])
			// ) {
			// 	if (
			// 		columns.length > 0 &&
			// 		columns[columns.length - 1].key == 'operation'
			// 	) {
			// 		columns.pop()
			// 	}
			// }
		})
		return {
			style,
			columns,
			searchLoading,
			tableLoading,
			formParams,
			formList,
			tablePagination,
			formId,
			tableName,
			confirmAddModalVisible,
			confirmModalDeleteVisible,
			deleteButtonLoading,

			onDeleteOkClick,
			onDeleteCancelClick,
			onAddCancelClick,
			getI18n,
			onSearchClick,
			onResetClick,
			onFormAddClick,
			onTableChange,
			onFormEditClick,
			onFormDeleteClick,
			onFormItemClick,
			getFormList,
			CommonConstant,
			// getButtonPermission,

			onDataSourceClick,
		}
	},
})
</script>
