// 流程管理 - 流程设计 - 服务组件任务节点 - 右侧常规面板 - 服务组件点击
<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:title="getI18n('system', 'SYSTEM_Process_MicroflowSelect')"
		:closable="true"
		:maskClosable="false"
		@cancel="onResetButtonClick()"
		:width="'80%'"
	>
		<a-card>
			<a-row>
				<!-- microflow名称 -->
				<a-col :span="6" class="search-item">
					<label>{{
						getI18n('system', 'SYSTEM_Microflow_Management_Name')
					}}</label>
					<a-input
						:placeholder="
							getI18n('common', 'Common_Please_Enter', [
								getI18n(
									'system',
									'SYSTEM_Microflow_Management_Name'
								),
							])
						"
						v-model:value="microflowParams.name"
					/>
				</a-col>
				<a-col :span="6">
					<div class="button-wrapper">
						<!-- 查询按钮 -->
						<a-button
							:loading="searchLoading"
							type="primary"
							@click="onSearchClick"
							class="button-item"
						>
							{{ getI18n('common', 'Common_Search') }}
						</a-button>
						<!-- 重置按钮 -->
						<a-button
							:loading="searchLoading"
							@click="onResetClick"
							class="button-item"
						>
							{{ getI18n('common', 'Common_Clear') }}
						</a-button>
					</div>
				</a-col>
			</a-row>
		</a-card>

		<a-card>
			<a-table
				style="margin-top: 1em"
				:rowKey="records => records.id"
				:columns="columns"
				:loading="tableLoading"
				:data-source="microflowList"
				:bordered="true"
				:pagination="tablePagination"
				:row-selection="rowSelection"
				@change="onTableChange"
				:class="style['custom-table']"
			/>
		</a-card>

		<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 { defineComponent, reactive, ref, watch, PropType } from 'vue' // computed onMounted,

import { getI18n } from '@/utils/i18n'
import style from './index.module.less'
import { message } from 'ant-design-vue'
import { validatenull } from '@/utils/tool/translateValue'

import { getViewText, getDayText } from '@/utils/tool/translateValue'
import { MicroflowManagementConstatnt } from '@/utils/constant'

import { RequestResult, PaginationData } from '@/utils/request/model'
import { AntdPaginationType, AntdTableChangePageType } from '@/types/antd'
import { MicroflowManagementListModel } from '@/types/microflowManagement'
import { getMicroflowManagementListApi } from '@/api/microflow'
import { GetMicroflowManagementListParamsModel } from '@/api/microflow/model'
import { CloseOutlined, SaveOutlined } from '@ant-design/icons-vue'

const columns = [
	// 名称
	{
		title: getI18n('system', 'SYSTEM_Microflow_Management_Name'),
		dataIndex: 'name',
		align: 'center',
		width: '40%',
	},
	// 联系人
	{
		title: getI18n('system', 'SYSTEM_Microflow_Management_Username'),
		dataIndex: 'contact',
		align: 'center',
		width: '15%',
	},
	// 联系电话
	{
		title: getI18n('system', 'SYSTEM_Microflow_Management_Contact'),
		dataIndex: 'tel',
		align: 'center',
		width: '15%',
	},
	// 状态
	{
		title: getI18n('system', 'SYSTEM_Microflow_Management_Status'),
		dataIndex: 'status',
		customRender: ({ text }) =>
			getViewText(
				MicroflowManagementConstatnt.detailStatus,
				text?.toString()
			),
		align: 'center',
		width: '15%',
	},
	// 注册时间
	{
		title: getI18n('system', 'SYSTEM_Microflow_Management_CreateDate'),
		dataIndex: 'createTime',
		customRender: ({ text }) => getDayText(text, 'YYYY.MM.DD HH:mm:ss'),
		align: 'center',
		width: '15%',
	},
]

export default defineComponent({
	components: {
		CloseOutlined,
		SaveOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 已选择的微流程
		selectData: {
			type: Array as PropType<MicroflowManagementListModel[]>,
			required: false,
			default: () => [],
		},
	},
	emits: ['confirm-add-modal-refresh', 'confirm-add-modal-cancel'],
	setup(props, context) {
		// const route = useRoute()
		// 是否展示弹窗
		const confirmAddModalVisible = ref<boolean>(false)
		// tableId
		const microflowId = ref<string>()
		// 搜索按钮loading
		const searchLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		// 列表参数
		const microflowParams = reactive<GetMicroflowManagementListParamsModel>(
			{
				current: 1,
				size: 10,
			}
		)
		// 数据列表
		const microflowList = ref<MicroflowManagementListModel[]>([])
		// 列表分页
		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 getBwuManagementList = async () => {
			tableLoading.value = true
			let paramObj: GetMicroflowManagementListParamsModel = {
				size: microflowParams.size,
				current: microflowParams.current,
				fileds: 'id,name',
			}
			microflowParams.name && (paramObj.name = microflowParams.name)

			const res: RequestResult<
				PaginationData<MicroflowManagementListModel>
			> = await getMicroflowManagementListApi(paramObj).finally(() => {
				tableLoading.value = false
				searchLoading.value = false
			})
			microflowList.value = res.data.records
			tablePagination.current = res.data.current
			tablePagination.pageSize = res.data.size
			tablePagination.total = res.data.total
		}

		// 列表change事件
		const onTableChange = (page: AntdTableChangePageType) => {
			microflowParams.size = page.pageSize
			microflowParams.current = page.current
			getBwuManagementList()
		}
		// 搜索按钮事件
		const onSearchClick = async () => {
			searchLoading.value = true
			await getBwuManagementList()
		}
		// 重置按钮事件
		const onResetClick = () => {
			searchLoading.value = true
			microflowParams.name = undefined
			microflowParams.size = 10
			microflowParams.current = 1
			microflowId.value = undefined
			getBwuManagementList()
		}

		// 弹窗是否展示
		let confirmModalVisibleValue = ref(props.confirmModalVisible)
		// 按钮loading
		const submitButtonLoading = ref<boolean>(false)

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

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

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

			let selectData = selectedRowData.value.map(v => {
				return {
					id: v.id,
					name: v.name,
					microflowName: v.name,
					// privateKey: v.privateKey,
					// publicKey: v.publicKey,
					// contact: v.contact,
					// tel: v.tel,
				}
			})
			context.emit('confirm-add-modal-refresh', selectData)
			message.success(getI18n('common', 'Common_Success'))
			onResetButtonClick()
		}

		watch(
			() => props.confirmModalVisible,
			async newValue => {
				confirmModalVisibleValue.value = newValue
				if (newValue) {
					await getBwuManagementList()

					if (!validatenull(props.selectData)) {
						let _selectFormFieldsData = [...props.selectData]
						// 列表多选框
						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,

			rowSelection,

			searchLoading,
			microflowParams,
			microflowList,
			tablePagination,
			microflowId,
			confirmAddModalVisible,
			onSearchClick,
			onResetClick,
			onTableChange,
		}
	},
})
</script>
