<template>
	<a-card class="base-card-full-screen">
		<div style="display: flex; justify-content: space-between">
			<div>
				<!-- 新增 -->
				<a-button
					type="primary"
					@click="onFormItemAddTableRowClick"
					style="margin-right: 1em"
				>
					{{ getI18n('common', 'Common_Add') }}
				</a-button>
				<!-- 从数据源导入 -->
				<a-button
					v-if="canImport"
					type="primary"
					@click="onImportDataSourceClick"
					style="margin-right: 1em"
					:loading="importLoading"
				>
					{{ getI18n('system', 'SYSTEM_Import_Data_Source') }}
				</a-button>
				<!-- 保存 -->
				<a-button
					type="primary"
					@click="onFormItemSaveClick"
					:loading="saveButtonLoading"
					style="margin-right: 1em"
				>
					{{ getI18n('common', 'Common_Save') }}
				</a-button>
				<!-- 删除按钮 -->
				<a-button
					type="primary"
					danger
					:disabled="!hasSelected"
					@click="onFormItemsDeleteClick"
					style="margin-right: 1em"
				>
					{{ getI18n('common', 'Common_Delete') }}
				</a-button>
				<!-- 返回 -->
				<a-button @click="onGobackClick">
					{{ getI18n('common', 'Common_Back') }}
				</a-button>
			</div>
		</div>
		<a-table
			style="margin-top: 1em"
			:rowKey="record => record.id"
			:columns="columns"
			:loading="tableLoading"
			:dataSource="formItemList"
			:bordered="true"
			:pagination="false"
			:row-selection="rowSelection"
		>
			<!-- :row-selection="rowSelection" -->
			<template #index="{ index }">{{ index + 1 }}</template>

			<!-- 名称 -->
			<template #name="{ record }">
				<a-input
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Formitem_name'),
						])
					"
					:value="record.name"
					@change="
						e =>
							handleFormItemTableDataChange(
								e.target.value,
								record.id,
								'name'
							)
					"
				/>
			</template>
			<!-- 物理列名 -->
			<template #columnName="{ record }">
				<a-input
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Formitem_Column_Name'),
						])
					"
					:value="record.columnName"
					@change="
						e =>
							handleFormItemTableDataChange(
								e.target.value,
								record.id,
								'columnName'
							)
					"
				/>
			</template>
			<!-- 表单字段 -->
			<template #formName="{ record }">
				<a-input
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Formitem_FormName'),
						])
					"
					:value="record.formName"
					@change="
						e =>
							handleFormItemTableDataChange(
								e.target.value,
								record.id,
								'formName'
							)
					"
				/>
			</template>
			<!-- 类型 -->
			<template #type="{ record }">
				<a-input
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n('system', 'SYSTEM_Formitem_Type'),
						])
					"
					:value="record.type"
					@change="
						e =>
							handleFormItemTableDataChange(
								e.target.value,
								record.id,
								'type'
							)
					"
				/>
			</template>
			<!-- 操作 -->
			<template #operation="{ record }">
				<a
					href="javascript:;"
					class="textC-red"
					@click="onFormItemDeleteClick(record.id)"
					style="margin-left: 8px"
					>{{ getI18n('common', 'Common_Delete') }}</a
				>
			</template>
		</a-table>
		<a-button
			style="width: 100%; margin-top: 16px; margin-bottom: 8px"
			type="dashed"
			@click="onFormItemAddTableRowClick"
		>
			<plus-outlined />
		</a-button>
	</a-card>
	<!-- 确认删除 -->
	<base-operational-qualification
		:confirm-modal-visible="confirmModalDeleteVisible"
		@confirm-modal-ok="onDeleteOkClick"
		@confirm-modal-cancel="onDeleteCancelClick"
		:ok-loading="deleteButtonLoading"
	/>
</template>
<script lang="ts">
import { GetFormItemParamsModel } from '@/api/formitem/model'
import { FormItemModel } from '@/types/formitem'
import { DataSourceModel } from '@/types/dataSource'
import { getI18n } from '@/utils/i18n'
import { defineComponent, onMounted, reactive, ref, computed } from 'vue'
import style from './index.module.less'
import { getFormItemListApi, updateFormItemApi } from '@/api/formitem'
import { importDataSourceApi } from '@/api/data-source'
import { ImportDataSourceParamsModel } from '@/api/data-source/model'
import { RequestResult, PaginationData } from '@/utils/request/model'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import router from '@/router'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getRandomString } from '@/utils/tool/translateValue'

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

import { FormModel } from '@/types/form'
import { getFormByIdApi } from '@/api/form'

const columns = [
	// 序号
	{
		title: getI18n('common', 'Common_Columns_Index'),
		dataIndex: 'index',
		slots: { customRender: 'index' },
		align: 'center',
		width: 80,
	},
	// 名称
	{
		title: getI18n('system', 'SYSTEM_Formitem_name'),
		dataIndex: 'name',
		slots: { customRender: 'name' },
		align: 'center',
		width: '25%',
	},
	// 物理列名
	{
		title: getI18n('system', 'SYSTEM_Formitem_Column_Name'),
		dataIndex: 'columnName',
		slots: { customRender: 'columnName' },
		align: 'center',
		width: '25%',
	},
	// 表单字段
	{
		title: getI18n('system', 'SYSTEM_Formitem_FormName'),
		dataIndex: 'formName',
		slots: { customRender: 'formName' },
		align: 'center',
		width: '20%',
	},
	// 类型
	{
		title: getI18n('system', 'SYSTEM_Formitem_Type'),
		dataIndex: 'type',
		slots: { customRender: 'type' },
		align: 'center',
		width: '10%',
	},
	// 操作
	{
		title: getI18n('common', 'Common_Action'),
		align: 'center',
		key: 'operation',
		slots: { customRender: 'operation' },
		width: '10%',
	},
]

export default defineComponent({
	components: { PlusOutlined },
	setup() {
		// 路由
		const route = useRoute()
		// 是否展示弹窗
		const confirmAddModalVisible = ref<boolean>(false)
		// 查询表单详情 - 获取数据源接口参数
		const formState = reactive<FormModel>({})
		// 是否显示 导入数据源按钮
		const canImport = ref<boolean>(false)
		// 按钮loading
		const saveButtonLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		// 列表参数
		const formParams = reactive<GetFormItemParamsModel>({
			formId: route.params.id ? route.params.id.toString() : '',
		})
		// 表单项列表数据
		const formItemList = ref([
			{
				id: getRandomString(),
			},
		])
		// 获取表单列表数据
		const getFormItemList = async () => {
			tableLoading.value = true
			let paramObj: GetFormItemParamsModel = {}
			formParams.formId && (paramObj.formId = formParams.formId)
			paramObj.size = -1
			const getFormListRes: RequestResult<PaginationData<FormItemModel>> =
				await getFormItemListApi(paramObj).finally(() => {
					tableLoading.value = false
				})
			if (Array.isArray(getFormListRes.data)) {
				formItemList.value = JSON.parse(
					JSON.stringify(getFormListRes.data)
				)
			}
		}
		// 选中数据（深拷贝）
		const selectedRowData = ref<FormItemModel[]>([])
		// 列表多选
		let tableSelectedRowKeys = ref<(string | number)[]>([])
		const confirmModalDeleteVisible = ref<boolean>(false) // 确认删除面板
		const deleteButtonLoading = ref<boolean>(false) // 确认删除按钮loading
		const deleteId = ref<string>('') // 删除参数
		// 操作区删除按钮点击事件
		const onFormItemDeleteClick = (id: string) => {
			confirmModalDeleteVisible.value = true
			deleteId.value = id
		}
		// 多选
		const rowSelection = ref({
			checkStrictly: false,
			selectedRowKeys: tableSelectedRowKeys,
			onChange: (key: (string | number)[], selectedRows) => {
				selectedRowData.value = [
					...selectedRowData.value,
					...selectedRows,
				]
				tableSelectedRowKeys.value = key
			},
		})
		// 批量删除按钮点击事件
		const onFormItemsDeleteClick = () => {
			confirmModalDeleteVisible.value = true
			deleteId.value = tableSelectedRowKeys.value.toString()
		}
		// 确认删除
		const onDeleteOkClick = async () => {
			deleteButtonLoading.value = true
			const deleteIds = deleteId.value.split(',')
			deleteIds.forEach(items => {
				const newData = [...formItemList.value]
				formItemList.value = newData.filter(item => items !== item.id)
			})
			tableSelectedRowKeys.value = []
			message.success(getI18n('common', 'Common_Success'))
			deleteButtonLoading.value = false
			confirmModalDeleteVisible.value = false
		}
		// 取消删除
		const onDeleteCancelClick = () => {
			confirmModalDeleteVisible.value = false
		}
		// 表单项改变
		const handleFormItemTableDataChange = (
			value: string,
			key: string,
			column: string | number
		) => {
			const newData = [...formItemList.value]
			const target = newData.filter(item => key == item.id)[0]
			if (target) {
				target[column] = value
				formItemList.value = newData
			}
		}
		// 表单项新增行
		const onFormItemAddTableRowClick = () => {
			formItemList.value = [
				...formItemList.value,
				{
					id: getRandomString(),
				},
			]
		}
		// 表单项删除行
		// const onFormItemDeleteRowClick = (id: string) => {
		// 	const newData = [...formItemList.value]
		// 	formItemList.value = newData.filter(item => id !== item.id)
		// }

		// 是否选中多选框
		const hasSelected = computed(
			() => tableSelectedRowKeys.value.length > 0
		)

		// 保存按钮点击
		const onFormItemSaveClick = async () => {
			// 表单项
			let _formItemDataSourceData = JSON.parse(
				JSON.stringify(formItemList.value)
			)
			let formItemParams = []
			if (
				Array.isArray(_formItemDataSourceData) &&
				_formItemDataSourceData.length != 0
			) {
				_formItemDataSourceData = _formItemDataSourceData.filter(
					f => f.name && f.columnName && f.type && f.formName
				)
				if (
					_formItemDataSourceData.length != formItemList.value.length
				) {
					message.info(getI18n('system', 'SYSTEM_Formitem_Add_All'))
					return
				}
				formItemParams = _formItemDataSourceData?.map(m => {
					return {
						name: m.name,
						columnName: m.columnName,
						formName: m.formName,
						type: m.type,
					}
				})
			}
			const params = {
				items: formItemParams,
			}
			saveButtonLoading.value = true
			await updateFormItemApi(formParams.formId || '', params).finally(
				() => {
					saveButtonLoading.value = false
				}
			)
			message.success(getI18n('common', 'Common_Success'))
			getFormItemList()
		}

		// 数据源导入loading
		const importLoading = ref<boolean>(false)
		// 从数据源导入按钮点击
		const onImportDataSourceClick = async () => {
			importLoading.value = true

			let params: ImportDataSourceParamsModel = {
				id: formState.datasourceId || '',
				table: formState.tableName || '',
			}

			const res: RequestResult<PaginationData<DataSourceModel>> =
				await importDataSourceApi(params).finally(() => {
					importLoading.value = false
				})
			if (Array.isArray(res.data)) {
				formItemList.value = JSON.parse(
					JSON.stringify(res.data)
						.replace(/columnComment/g, 'name')
						.replace(/dataType/g, 'type')
				).map(m => {
					return {
						id: getRandomString(),
						name: m.name,
						columnName: m.columnName,
						formName: m.formName,
						type: m.type,
					}
				})
			}
			message.success(getI18n('common', 'Common_Success'))
		}

		// 修改时单条查询
		const getFormById = async (id: string) => {
			if (!id) return
			const res: RequestResult<FormModel> = await getFormByIdApi({
				id: id,
			})

			canImport.value = res.data[0].datasourceId ? true : false
			formState.name = res.data[0].name
			formState.datasourceId = res.data[0].datasourceId
			formState.tableName = res.data[0].tableName
			formState.remark = res.data[0].remark
		}

		// 列表返回
		const onGobackClick = () => {
			router.push({
				name: 'FormList',
			})
		}
		onMounted(async () => {
			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())
			}
			await getFormById(route.params.id ? route.params.id.toString() : '')
			await getFormItemList()
		})
		return {
			style,
			columns,
			tableLoading,
			importLoading,
			formParams,
			formItemList,
			saveButtonLoading,
			confirmAddModalVisible,
			confirmModalDeleteVisible,
			deleteButtonLoading,
			rowSelection,
			hasSelected,
			canImport,
			onFormItemDeleteClick,
			onFormItemsDeleteClick,
			onDeleteOkClick,
			onDeleteCancelClick,
			getI18n,
			onFormItemSaveClick,
			onGobackClick,
			getFormItemList,
			onFormItemAddTableRowClick,
			// onFormItemDeleteRowClick,
			onImportDataSourceClick,
			handleFormItemTableDataChange,
			getRandomString,
		}
	},
})
</script>
