// 流程管理 - 流程设计 - 用户任务节点 - 右侧权限按钮面板点击
<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:title="getI18n('system', 'SYSTEM_Process_PermissionButtonSelect')"
		:closable="true"
		:maskClosable="false"
		@cancel="onResetButtonClick()"
		:width="'80%'"
	>
		<div style="display: flex; justify-content: space-between">
			<!-- 新增 -->
			<a-button
				type="primary"
				@click="onFormItemAddTableRowClick"
				style="margin-right: 1em"
			>
				{{ getI18n('system', 'SYSTEM_Process_PermissionButtonAdd') }}
			</a-button>
		</div>

		<a-table
			style="margin-top: 1em"
			:rowKey="record => record.id"
			:columns="columns"
			:loading="tableLoading"
			:dataSource="formItemList"
			:bordered="true"
			:pagination="false"
			:scroll="{ y: 500 }"
			:row-selection="rowSelection"
		>
			<!-- 序号 -->
			<template #index="{ index }">{{ index + 1 }}</template>

			<!-- 名称 -->
			<template #label="{ record }">
				<a-input
					v-if="record.custom"
					style="width: 100%"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n(
								'system',
								'SYSTEM_Process_PermissionButtonName'
							),
						])
					"
					v-model:value="record.label"
				/>
				<template v-else>{{ record.label }}</template>
			</template>
			<!-- 方法名 -->
			<template #type="{ record }">
				<a-input
					v-if="record.custom"
					style="width: 100%"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n(
								'system',
								'SYSTEM_Process_PermissionButtonFunctionName'
							),
						])
					"
					v-model:value="record.type"
				/>
				<template v-else>{{ record.type }}</template>
			</template>
			<!-- 排序 -->
			<template #order="{ record }">
				<a-input-number
					v-if="record.custom"
					style="width: 100%"
					:maxLength="100"
					:precision="0"
					:min="0"
					:max="9999"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n(
								'system',
								'SYSTEM_Process_PermissionButtonSort'
							),
						])
					"
					v-model:value="record.order"
				/>
				<template v-else>{{ record.order }}</template>
			</template>
			<!-- 图标 -->
			<template #icon="{ record }">
				<!-- <BaseSvgIcon v-if="record.custom" name="customBtn" /> -->
				<a-input
					v-if="record.custom"
					style="width: 80%"
					:placeholder="
						getI18n('common', 'Common_Please_Enter', [
							getI18n(
								'system',
								'SYSTEM_Process_PermissionButtonIcon'
							),
						])
					"
					v-model:value="record.icon"
				/>
				<template v-else>
					<BaseSvgIcon :name="record.icon" />
					<span :class="style['svg-span']">{{ record.icon }}</span>
				</template>
			</template>

			<!-- 操作 -->
			<template #operation="{ record }">
				<a-popconfirm
					v-if="record.custom"
					:title="getI18n('common', 'Common_Delete_Tips')"
					@confirm="onFormItemDeleteClick(record.id)"
				>
					<a
						href="javascript:;"
						class="textC-red"
						style="margin-left: 8px"
						>{{ getI18n('common', 'Common_Delete') }}</a
					>
				</a-popconfirm>
			</template>
		</a-table>

		<template #footer>
			<a-button
				type="primary"
				:loading="submitButtonLoading"
				@click="onSubmitButtonClick"
			>
				<save-outlined />
				{{ getI18n('common', 'Common_Certain') }}
			</a-button>
			<a-button
				@click="onResetButtonClick"
				:loading="submitButtonLoading"
			>
				<close-outlined />
				{{ getI18n('common', 'Common_Remove') }}
			</a-button>
		</template>
	</a-modal>
</template>
<script lang="ts">
import { getI18n } from '@/utils/i18n'
import { defineComponent, ref, watch, PropType } from 'vue'
import style from './index.module.less'
import { PermissionButtonListModal } from '@/types/process'
import { message } from 'ant-design-vue'
import { getRandomString, validatenull } from '@/utils/tool/translateValue'
import { PermissionButtonConstatnt } from '@/utils/constant'
import { CloseOutlined, SaveOutlined } from '@ant-design/icons-vue'

export interface columnsModel {
	title?: string
	dataIndex?: string
	align?: string
	width?: number | string
	fixed?: string
	slots?: {}
	customRender?: any
	children?: {
		title?: string
		dataIndex?: string
		align?: string
		width?: number | string
	}[]
}

const columnsBase: columnsModel[] = [
	// 序号
	{
		title: getI18n('common', 'Common_Columns_Index'),
		dataIndex: 'index',
		slots: { customRender: 'index' },
		align: 'center',
		width: 80,
	},
	// 名称
	{
		title: getI18n('system', 'SYSTEM_Process_PermissionButtonName'),
		dataIndex: 'label',
		slots: { customRender: 'label' },
		align: 'center',
	},
	// 方法名
	{
		title: getI18n('system', 'SYSTEM_Process_PermissionButtonFunctionName'),
		dataIndex: 'type',
		slots: { customRender: 'type' },
		align: 'center',
	},
	// 排序
	{
		title: getI18n('system', 'SYSTEM_Process_PermissionButtonSort'),
		dataIndex: 'order',
		slots: { customRender: 'order' },
		align: 'center',
	},
	// 图标
	{
		title: getI18n('system', 'SYSTEM_Process_PermissionButtonIcon'),
		dataIndex: 'icon',
		slots: { customRender: 'icon' },
		align: 'center',
	},
]

export default defineComponent({
	components: {
		CloseOutlined,
		SaveOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 已选择的权限按钮
		selectPermissionButtonData: {
			type: Array as PropType<PermissionButtonListModal[]>,
			required: false,
			default: () => [],
		},
		// 只有设置了多重并行事件的 用户节点 权限按钮列表里才能显示 加签、减签按钮
		isShowAddSubSignBtn: {
			type: Boolean,
			required: false,
			default: false,
		},
	},
	emits: ['confirm-add-modal-refresh', 'confirm-add-modal-cancel'],
	setup(props, context) {
		// 弹窗是否展示
		let confirmModalVisibleValue = ref(props.confirmModalVisible)
		// 按钮loading
		const submitButtonLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		const columns = ref<columnsModel[]>([])
		columns.value = [...columnsBase]

		// 表单项列表数据
		const formItemList = ref<PermissionButtonListModal[]>([])

		// 选中数据（深拷贝）
		const selectedRowData = ref<PermissionButtonListModal[]>([
			PermissionButtonConstatnt.buttonList[0],
		])
		// 列表多选
		let tableSelectedRowKeys = ref<(string | number)[]>([
			PermissionButtonConstatnt.buttonList[0].id,
		])
		// 多选
		const rowSelection = ref({
			checkStrictly: false,
			selectedRowKeys: tableSelectedRowKeys,
			onChange: (key: (string | number)[], selectedRows) => {
				selectedRowData.value = [...selectedRows]
				var obj = {} // 利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数，第二个参数是acc的初始值
				selectedRowData.value = selectedRowData.value.reduce(
					(
						item: PermissionButtonListModal[],
						next: PermissionButtonListModal
					) => {
						obj[next.id!]
							? ''
							: (obj[next.id!] = true && item.push(next))
						return item
					},
					[]
				)
				tableSelectedRowKeys.value = key
			},
			getCheckboxProps: (record: PermissionButtonListModal) => ({
				disabled:
					record.id === PermissionButtonConstatnt.buttonList[0].id ||
					record.custom, // 'submit' Column configuration not to be checked
			}),
		})

		// 操作区删除按钮点击事件
		const onFormItemDeleteClick = (id: string) => {
			// table列表
			formItemList.value = formItemList.value.filter(
				item => id !== item.id
			)
			selectedRowData.value = selectedRowData.value.filter(
				item => id !== item.id
			)

			// 最后一条自定义按钮，删除操作栏
			if (!formItemList.value.some(v => v.custom)) {
				columns.value.pop()
			}
		}

		// 表单项新增行
		const onFormItemAddTableRowClick = () => {
			let newAddRowId = getRandomString()
			formItemList.value = [
				...formItemList.value,
				{
					id: newAddRowId,
					custom: true,
				},
			]
			// 添加操作栏
			if (
				columns.value[columns.value.length - 1].dataIndex !==
				'operation'
			) {
				columns.value.push({
					title: getI18n('common', 'Common_Action'),
					align: 'center',
					dataIndex: 'operation',
					slots: { customRender: 'operation' },
					width: 100,
				})
			}

			// 多选数据
			selectedRowData.value = [
				...selectedRowData.value,
				...formItemList.value.filter(f => f.id === newAddRowId),
			]
			tableSelectedRowKeys.value.push(newAddRowId)
		}

		// 取消按钮
		const onResetButtonClick = () => {
			context.emit('confirm-add-modal-cancel')
			confirmModalVisibleValue.value = false
			// table行 多选
			selectedRowData.value = [PermissionButtonConstatnt.buttonList[0]]
			tableSelectedRowKeys.value = [
				PermissionButtonConstatnt.buttonList[0].id,
			]
			formItemList.value = []
		}

		// 确定按钮被点击
		const onSubmitButtonClick = () => {
			// 去重
			var obj = {} // 利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数，第二个参数是acc的初始值
			selectedRowData.value = selectedRowData.value.reduce(
				(
					item: PermissionButtonListModal[],
					next: PermissionButtonListModal
				) => {
					obj[next.id!]
						? ''
						: (obj[next.id!] = true && item.push(next))
					return item
				},
				[]
			)

			let selectData = selectedRowData.value.map(v => {
				return {
					label: v.label,
					id: v.id,
					order: v.order,
					icon: v.icon,
					type: v.type,
					buttonStyle: v.buttonStyle || '',
					custom: v.custom || false,
					sign: v.sign || 'todo',
				}
			})
			context.emit('confirm-add-modal-refresh', selectData)
			message.success(getI18n('common', 'Common_Success'))
			onResetButtonClick()
		}

		watch(
			() => props.confirmModalVisible,
			async newValue => {
				confirmModalVisibleValue.value = newValue
				if (newValue) {
					if (props.isShowAddSubSignBtn) {
						formItemList.value =
							PermissionButtonConstatnt.buttonList
					} else {
						formItemList.value =
							PermissionButtonConstatnt.buttonList.filter(
								f => f.id !== 'addUser' && f.id !== 'removeUser'
							)
					}

					if (!validatenull(props.selectPermissionButtonData)) {
						let _selectFormFieldsData = [
							...props.selectPermissionButtonData,
						]
						// 自定义字段
						_selectFormFieldsData.map(v => {
							if (v.custom) {
								formItemList.value = [
									...formItemList.value,
									...[v],
								]
							}
						})

						let a = _selectFormFieldsData.filter(f => f.custom)
						if (!validatenull(a) && a.length > 0) {
							// 添加操作栏
							if (
								columns.value[columns.value.length - 1]
									.dataIndex !== 'operation'
							) {
								columns.value.push({
									title: getI18n('common', 'Common_Action'),
									align: 'center',
									dataIndex: 'operation',
									slots: { customRender: 'operation' },
									width: 100,
								})
							}
						}

						// 列表多选框
						selectedRowData.value = _selectFormFieldsData
						// 列表选中id
						tableSelectedRowKeys.value = _selectFormFieldsData.map(
							v => {
								return v.id || ''
							}
						)
					}
				}
			},
			{ deep: true, immediate: true }
		)

		return {
			style,
			confirmModalVisibleValue,
			submitButtonLoading,
			getI18n,
			onSubmitButtonClick,
			onResetButtonClick,
			columns,
			tableLoading,

			formItemList,
			rowSelection,
			onFormItemDeleteClick,
			onFormItemAddTableRowClick,
		}
	},
})
</script>
