// 流程设计 - 流程线 - 表达式 弹窗
<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:title="getI18n('system', 'SYSTEM_Process_ConditionExpressionSelect')"
		:closable="true"
		:maskClosable="false"
		@cancel="onResetButtonClick()"
		:width="'80%'"
	>
		<a-form
			:model="formState"
			:label-col="{ span: 3 }"
			:wrapper-col="{ span: 21 }"
			ref="formRef"
		>
			<a-row>
				<a-col :span="24">
					<!-- 表达式 -->
					<a-form-item
						:label="
							getI18n(
								'system',
								'SYSTEM_Process_ConditionExpressionSelect'
							)
						"
						ref="conditionView"
						name="conditionView"
					>
						<a-input
							autoComplete="off"
							:allowClear="true"
							v-model:value="formState.conditionView"
							:placeholder="
								getI18n('common', 'Common_Please_Select', [
									getI18n(
										'system',
										'SYSTEM_Process_ConditionExpressionSelect'
									),
								])
							"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<!-- 可用表达式 -->
					<a-form-item
						:label="
							getI18n(
								'system',
								'SYSTEM_Process_AvailableExpressions'
							)
						"
						ref="conditionDefault"
						name="conditionDefault"
					>
						<template
							v-for="(tag, idx) in conditionDefaultTags"
							:key="idx"
						>
							<a-checkable-tag
								@change="() => handleChange(tag.value)"
							>
								{{ `${tag.label}：${tag.value}` }}
							</a-checkable-tag>
						</template>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>

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

			<!-- 操作 -->
			<template #operation="{ record }">
				<a
					@click="onConditionSelect(record.formName)"
					href="javascript:;"
					>{{ getI18n('common', 'Common_Select') }}</a
				>
			</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 style from './index.module.less'
import { getI18n } from '@/utils/i18n'
import { defineComponent, ref, watch, reactive } from 'vue' // PropType
import { message } from 'ant-design-vue'
import { CloseOutlined, SaveOutlined } from '@ant-design/icons-vue'

import { ConditionTagsModel } from '@/types/process'

// import { AntdPaginationType, AntdTableChangePageType } from '@/types/antd'
import { GetFormItemParamsModel } from '@/api/formitem/model'
import { FormItemModel } from '@/types/formitem'
import { getFormItemListApi } from '@/api/formitem'
import { RequestResult, PaginationData } from '@/utils/request/model'
import { getJCFormsDetailByIdApi } from '@/api/form-engine'

import { getViewText, removeDuplicate } from '@/utils/tool/translateValue'
import { ProcessConstant } from '@/utils/constant'

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',
	},
	// 表单字段
	{
		title: getI18n('system', 'SYSTEM_Formitem_FormName'),
		dataIndex: 'formName',
		slots: { customRender: 'formName' },
		align: 'center',
	},
	// 来源
	{
		title: getI18n('system', 'SYSTEM_Process_FormFieldsSource'),
		dataIndex: 'type',
		align: 'center',
		customRender: ({ text }) =>
			getViewText(
				Object.values(ProcessConstant.formType),
				text || 'form'
			),
		width: 100,
	},
	// 操作
	{
		title: getI18n('common', 'Common_Action'),
		align: 'center',
		key: 'operation',
		slots: { customRender: 'operation' },
		width: 100,
	},
]

export default defineComponent({
	components: {
		CloseOutlined,
		SaveOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 选择的 条件表达式
		flowConditionExpressionValue: {
			type: String,
			required: false,
			default: '',
		},
		// 查询表单字段的表单id值
		flowConditionFormData: {
			type: String,
			required: false,
			default: '',
		},
	},
	emits: ['confirm-add-modal-refresh', 'confirm-add-modal-cancel'],
	setup(props, context) {
		// 弹窗是否展示
		let confirmModalVisibleValue = ref(props.confirmModalVisible)
		// 按钮loading
		const submitButtonLoading = ref<boolean>(false)

		// 选择的条件string
		const selectConditionView = ref<string>()

		// 可用的表达式，接口返回的默认的表达式
		const conditionDefaultTags = ref<ConditionTagsModel[]>([
			{ value: '${userId}', label: '登录人Id' },
			{ value: '${departments}', label: '登录人部门' },
			{ value: '${positions}', label: '登录人岗位' },
			{ value: '${start_userId}', label: '发起人Id' },
			{ value: '${start_departments}', label: '登录人部门' },
			{ value: '${start_positions}', label: '发起人岗位' },
		])

		const formRef = ref()
		const formState = reactive<{
			conditionView?: string
			conditionDefault?: string
		}>({
			conditionView: '',
			conditionDefault: '',
		})

		// 表单字段列表数据
		const tableLoading = ref<boolean>(false)
		const tableData = ref<FormItemModel[]>([])
		// 列表分页
		// 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 getFormFieldsItemList = async (id: string, formTypes: string) => {
			tableLoading.value = true
			let paramObj: GetFormItemParamsModel = {
				formId: id,
				size: -1,
			}

			if (formTypes === 'jcform') {
				const res = await getJCFormsDetailByIdApi(
					paramObj.formId || ''
				).finally(() => {
					tableLoading.value = false
				})
				let _tableFormEngineData: FormItemModel[] = res.data?.map(
					(v: FormItemModel) => {
						return {
							columnName: v.columnName,
							formId: v.formId,
							formName: v.formName,
							name: v.name,
							id: v.formName,
							type: formTypes,
						}
					}
				)
				tableData.value = removeDuplicate([
					...tableData.value,
					..._tableFormEngineData,
				])
				return
			}
			const res: RequestResult<PaginationData<FormItemModel>> =
				await getFormItemListApi(paramObj).finally(() => {
					tableLoading.value = false
				})
			if (Array.isArray(res.data)) {
				let _tableFormData: FormItemModel[] = JSON.parse(
					JSON.stringify(res.data)
				).map((v: FormItemModel) => {
					return {
						columnName: v.columnName,
						formId: v.formId,
						formName: v.formName,
						name: v.name,
						id: v.formName,
						type: formTypes,
					}
				})
				tableData.value = removeDuplicate([
					...tableData.value,
					..._tableFormData,
				])
			}
		}

		// 默认条件 tag选中
		const handleChange = (value: string) => {
			formState.conditionDefault = value
			formState.conditionView += value
		}

		// 列表表单字段 选中
		const onConditionSelect = (val: string) => {
			formState.conditionView += '${' + val + '}'
		}

		// 取消按钮
		const onResetButtonClick = () => {
			tableData.value = []
			tableLoading.value = false
			confirmModalVisibleValue.value = false
			formState.conditionDefault = ''
			formState.conditionView = ''
			context.emit('confirm-add-modal-cancel')
		}
		// 确定按钮被点击
		const onSubmitButtonClick = () => {
			context.emit('confirm-add-modal-refresh', formState.conditionView)
			message.success(getI18n('common', 'Common_Success'))
		}

		watch(
			() => props.confirmModalVisible,
			newValue => {
				!newValue && onResetButtonClick()
				confirmModalVisibleValue.value = newValue

				props.flowConditionExpressionValue &&
					(formState.conditionView =
						props.flowConditionExpressionValue)
				if (props.flowConditionFormData) {
					JSON.parse(props.flowConditionFormData).map(v => {
						v && getFormFieldsItemList(v.id, v.type)
					})
					// const _resopnse = Promise.all(res).then()
				}
			},
			{ deep: true, immediate: true }
		)

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

			selectConditionView,

			formRef,
			formState,
			conditionDefaultTags,
			handleChange,
			tableLoading,
			tableData,
			columns,
			onConditionSelect,
		}
	},
})
</script>
