// 流程管理 新增/编辑弹框
<template>
	<a-modal
		v-model:visible="confirmModalVisibleValue"
		:confirm-loading="submitButtonLoading"
		:title="
			getI18n(
				'system',
				processId
					? 'SYSTEM_Process_ProcessEdit'
					: 'SYSTEM_Process_ProcessAdd'
			)
		"
		:closable="false"
		:maskClosable="false"
		@cancel="$emit('confirm-add-modal-cancel')"
		:width="1000"
	>
		<a-form
			:model="formState"
			:label-col="{ span: 6 }"
			:wrapper-col="{ span: 18 }"
			:rules="formRules"
			ref="formRef"
		>
			<a-row>
				<!-- 流程名称 -->
				<a-col :span="12">
					<a-form-item
						:label="getI18n('system', 'SYSTEM_Process_Name')"
						ref="name"
						name="name"
					>
						<a-input
							:maxLength="100"
							v-model:value="formState.name"
							:placeholder="
								getI18n('common', 'Common_Please_Enter', [
									getI18n('system', 'SYSTEM_Process_Name'),
								])
							"
						/>
					</a-form-item>
				</a-col>

				<!-- 流程分类 -->
				<a-col :span="12">
					<a-form-item
						:label="getI18n('system', 'SYSTEM_Process_Category')"
						ref="categoryId"
						name="categoryId"
					>
						<a-tree-select
							:loading="processCategoryListLoading"
							:tree-data="processCategoryList"
							:dropdown-style="{
								maxHeight: '400px',
								overflow: 'auto',
							}"
							:placeholder="
								getI18n('common', 'Common_Please_Select', [
									getI18n(
										'system',
										'SYSTEM_Process_Category'
									),
								])
							"
							:replaceFields="{
								title: 'title',
								key: 'key',
								value: 'key',
							}"
							@change="onCategoryChange"
							v-model:value="formState.categoryId"
							style="width: 100%"
							allow-clear
							tree-default-expand-all
						/>
					</a-form-item>
				</a-col>

				<!-- 流程状态 -->
				<a-col :span="12">
					<a-form-item
						:label="getI18n('system', 'SYSTEM_Category_Status')"
						ref="status"
						name="status"
					>
						<a-radio-group v-model:value="formState.status">
							<a-radio
								:style="radioStyle"
								v-for="i in ProcessConstant.processStatus"
								:key="i.value"
								:value="i.value"
							>
								{{ i.label }}
							</a-radio>
						</a-radio-group>
					</a-form-item>
				</a-col>

				<!-- 流程描述 -->
				<a-col :span="24">
					<a-form-item
						:label="getI18n('system', 'SYSTEM_Process_Remark')"
						ref="remark"
						name="remark"
						:label-col="{ span: 3 }"
						:wrapper-col="{ span: 21 }"
					>
						<a-textarea
							:maxLength="100"
							:row="4"
							v-model:value="formState.remark"
							:placeholder="
								getI18n('common', 'Common_Please_Enter', [
									getI18n('system', 'SYSTEM_Process_Remark'),
								])
							"
						/>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<!-- 保存 -->
			<a-button
				type="primary"
				:loading="submitButtonLoading"
				@click="onSubmitButtonClick"
			>
				<save-outlined />
				{{ getI18n('common', 'Common_Save') }}
			</a-button>
			<!-- 取消 -->
			<a-button
				@click="onCloseButtonClick"
				:loading="submitButtonLoading"
			>
				<close-outlined />
				{{ getI18n('common', 'Common_Remove') }}
			</a-button>
		</template>
	</a-modal>
</template>
<script lang="ts">
import router from '@/router'
import { getI18n } from '@/utils/i18n'
import { message } from 'ant-design-vue'
import { CloseOutlined, SaveOutlined } from '@ant-design/icons-vue'

import { defineComponent, reactive, ref, watch } from 'vue'
import { RequestResult } from '@/utils/request/model'

import { ProcessConstant } from '@/utils/constant'
import {
	ProcessManagementModel,
	ProcessCategoryModel,
	ProcessCategoryTreeModel,
} from '@/types/process'

import {
	addProcessApi,
	getProcessByIdApi,
	updateProcessApi,
} from '@/api/process-management'

import { getProcessCategoryRoleTreeApi } from '@/api/process-category'

export default defineComponent({
	name: 'ProcessDesignFormModal',
	components: {
		CloseOutlined,
		SaveOutlined,
	},
	props: {
		// 操作确认弹出层是否展示
		confirmModalVisible: {
			type: Boolean,
			required: false,
			default: false,
		},
		// 编辑所需要的id
		processId: {
			type: String,
			default: '',
		},
		// 左侧树选中的 分类Id
		treeSelectCategoryId: {
			type: String,
			default: '',
		},
	},
	emits: ['confirm-add-modal-refresh', 'confirm-add-modal-cancel'],
	setup(props, context) {
		// 弹窗是否展示
		const confirmModalVisibleValue = ref<boolean>(props.confirmModalVisible)

		// 列表loading
		const pageLoading = ref<boolean>(false)
		// 按钮loading
		const submitButtonLoading = ref<boolean>(false)

		// 表单数据
		const formRef = ref()
		const formState = reactive<{
			id?: string // 主键Id
			name?: string // 流程名称
			remark?: string // 描述
			status?: string // 启用状态 1启用0禁用
			categoryId?: string // 流程分类 id
		}>({})

		// 表单校验规则
		const formRules = {
			// 流程名称
			name: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Process_Name'),
					]),
					trigger: 'change',
				},
			],
			// 描述
			remark: [
				{
					required: false,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Process_Remark'),
					]),
					trigger: 'change',
				},
			],
			// 流程分类
			categoryId: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						getI18n('system', 'SYSTEM_Process_Category'),
					]),
					trigger: 'change',
				},
			],
			// 启用状态
			status: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Select', [
						getI18n('system', 'SYSTEM_Category_Status'),
					]),
					// type: 'number',
					trigger: 'change',
				},
			],
		}

		// 重置数据
		const onResetButtonClick = () => {
			formState.id = undefined // 主键Id
			formState.name = undefined // 流程名称
			formState.remark = undefined // 描述
			formState.categoryId = undefined //
			formState.status = undefined // 启用状态 1启用0禁用
			confirmModalVisibleValue.value = false
			formRef.value.resetFields()
		}
		// 取消按钮
		const onCloseButtonClick = () => {
			onResetButtonClick()
			context.emit('confirm-add-modal-cancel')
		}

		const processCategoryListLoading = ref<boolean>(false)
		const processCategoryList = ref<ProcessCategoryModel[]>([])
		// 获取流程分类
		const getProcessCategoryList = async () => {
			processCategoryListLoading.value = true

			const res: RequestResult<ProcessCategoryTreeModel[]> =
				await getProcessCategoryRoleTreeApi().finally(() => {
					processCategoryListLoading.value = false
				})
			processCategoryList.value = JSON.parse(JSON.stringify(res.data))
		}

		// 分类改变
		const onCategoryChange = (value: string) => {
			formState.categoryId = value
		}

		// 修改时单条查询
		const getCadreMotionById = async (id: string) => {
			const res: RequestResult<ProcessManagementModel> =
				await getProcessByIdApi({
					id: id,
				})

			formState.remark = res.data[0].remark
			formState.categoryId = res.data[0].categoryId
			formState.status = res.data[0].status?.toString()
			formState.id = res.data[0].id
			formState.name = res.data[0].name
		}

		// 提交按钮被点击
		const onSubmitButtonClick = () => {
			formRef.value.validate().then(async () => {
				// 参数
				let params: ProcessManagementModel = {
					remark: formState.remark,
					categoryId: formState.categoryId,
					status: formState.status,
					name: formState.name,
				}

				if (props.processId) {
					params.id = props.processId

					submitButtonLoading.value = true
					await updateProcessApi(params).finally(() => {
						submitButtonLoading.value = false
					})
				} else {
					submitButtonLoading.value = true
					await addProcessApi(params).finally(() => {
						submitButtonLoading.value = false
					})
				}
				
				message.success(getI18n('common', 'Common_Success'))
				onResetButtonClick()
				context.emit('confirm-add-modal-refresh')
			})
		}

		watch(
			() => props.processId,
			async newValue => {
				newValue && (await getCadreMotionById(newValue))
			}
		)

		watch(
			() => props.confirmModalVisible,
			async newValue => {
				confirmModalVisibleValue.value = newValue
				newValue && (await getProcessCategoryList())
			}
		)

		watch(
			() => props.treeSelectCategoryId,
			newVal => {
				newVal && (formState.categoryId = newVal)
			},
			{ deep: true, immediate: true }
		)

		return {
			confirmModalVisibleValue,
			pageLoading,
			submitButtonLoading,
			formRef,
			formState,
			formRules,
			ProcessConstant,
			router,
			radioStyle: {
				display: 'inline-block',
				height: '30px',
				lineHeight: '30px',
			},
			getI18n,
			onSubmitButtonClick,
			onCloseButtonClick,

			processCategoryListLoading,
			processCategoryList,
			onCategoryChange,
		}
	},
})
</script>
