// 流程模板列表
<template>
	<a-card style="padding-top: 0 !important" class="base-card-full-screen">
		<a-row>
			<a-col span="4" style="border: 1px solid #eee">
				<!-- 流程分类树 -->
				<process-category-tree
					@on-select-dept-id="onProcessCategoryTreeSelect"
				/>
			</a-col>
			<a-col span="20" style="padding-left: 1em">
				<!-- 搜索 -->
				<process-design-search
					:search-loading="searchLoading"
					@handle-search="onSearchButtonClick"
					@handle-reset="onResetButtonClick"
				/>

				<!-- 新增流程 按钮 -->
				<!-- v-if="
					getButtonPermission(
						CommonConstant.permissionKeys.processSave.value
					)
				" -->
				<div style="display: flex; justify-content: space-between">
					<a-button
						type="primary"
						@click="onProcessAddClick"
						style="margin-right: 1em"
					>
						<plus-outlined />
						{{ getI18n('system', 'SYSTEM_Process_ProcessAddBtn') }}
					</a-button>
				</div>
				<!-- 列表 -->
				<a-table
					:rowKey="record => record.id"
					:columns="columns"
					:loading="tableLoading"
					:data-source="processsList"
					:bordered="true"
					:pagination="tablePagination"
					@change="onTableChange"
					style="margin-top: 1em"
				>
					<!-- 流程名称 -->
					<template #name="{ record }">
						<div style="text-align: left">{{ record.name }}</div>
					</template>
					<!-- 流程描述 -->
					<template #remark="{ record }">
						<div style="text-align: left">{{ record.remark }}</div>
					</template>
					<!-- 发布状态 -->
					<!-- "record.status?.toString() === ProcessConstant.processStatus.disable.value" -->
					<template #pubstatus="{ record }">
						<div
							v-if="
								record.status?.toString() ===
									ProcessConstant.processStatus.enable
										.value && record.curVersion
							"
						>
							{{ '已发布' }}
						</div>
						<div
							v-else-if="
								record.status?.toString() ===
									ProcessConstant.processStatus.enable
										.value && !record.curVersion
							"
						>
							{{ '未发布' }}
						</div>
						<div v-else>
							{{ '-' }}
						</div>
					</template>
					<!-- 操作按钮 -->
					<template #operation="{ record }">
						<!-- 流程设计 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.processDesignDesign.value
								) && record.status == 1
							" -->
						<a
							v-if="record.status == 1"
							href="javascript:;"
							:class="style['table-button']"
							@click="onProcessDesignClick(record)"
							>{{ getI18n('system', 'SYSTEM_Process_Design') }}</a
						>
						<!-- 编辑 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys.processUpdate
										.value
								)
							" -->
						<a
							href="javascript:;"
							:class="style['table-button']"
							@click="onUpdateButtonClick(record.id)"
							>{{ getI18n('common', 'Common_Edit') }}</a
						>
						<!-- 删除 -->
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys.processDelete
										.value
								)
							" -->
						<a
							href="javascript:;"
							:class="style['table-button']"
							class="textC-red"
							@click="onDeleteButtonClick(record.id)"
							>{{ getI18n('common', 'Common_Delete') }}</a
						>
					</template>
				</a-table>
			</a-col>
		</a-row>
	</a-card>

	<!-- 确认删除 -->
	<base-operational-qualification
		:confirm-modal-visible="confirmModalDeleteVisible"
		@confirm-modal-ok="onDeleteOkClick"
		@confirm-modal-cancel="onDeleteCancelClick"
		:ok-loading="deleteButtonLoading"
	/>

	<!-- 导入是否覆盖 -->
	<base-operational-qualification
		:confirm-modal-visible="confirmModalImportVisible"
		:ok-loading="importButtonLoading"
		:text="importText"
		:cancelButtonText="CommonConstant.isAdmin.no.label"
		:okButtonText="CommonConstant.isAdmin.yes.label"
		@confirm-modal-ok="onImportOkClick"
		@confirm-modal-cancel="onImportCancelClick"
	/>

	<!-- 流程设计 新增/编辑弹窗 -->
	<process-design-form-modal
		:confirm-modal-visible="confirmAddModalVisible"
		@confirm-add-modal-refresh="onAddRefreshClick"
		@confirm-add-modal-cancel="onAddCancelClick"
		:process-id="processId"
		:tree-select-category-id="processsListParams.categoryId"
	/>

	<!-- 流程设计 - bpmn编辑器、版本管理 -->
	<process-design-publish-editor-modal
		:confirm-modal-visible="confirmModalProcessDesignVisible"
		:process-design-id="processDesignId"
		:process-design-key="processDesignKey"
		@confirm-modal-close="onProcessDesignCloseClick"
	/>
</template>

<script lang="ts">
import dayjs from 'dayjs'
import { getI18n } from '@/utils/i18n'
import style from './index.module.less'
import { message } from 'ant-design-vue'
import {
	PlusOutlined,
	UploadOutlined,
	DownloadOutlined,
} from '@ant-design/icons-vue'

import { defineComponent, onMounted, reactive, ref } from 'vue' //  reactive ref,  PropType  watch,

import {
	ProcessCategoryTree,
	ProcessDesignSearch,
	ProcessDesignFormModal,
	ProcessDesignPublishEditorModal,
} from '../components'

import { AntdPaginationType, AntdTableChangePageType } from '@/types/antd'
import { PaginationData, RequestResult } from '@/utils/request/model'
import { ProcessConstant, CommonConstant } from '@/utils/constant'
import { ProcessManagementModel } from '@/types/process'
import {
	deleteProcessApi,
	getProcessListApi,
	processDesignDataExport,
	processDesignDataImport,
} from '@/api/process-management'
import {
	GetProcessListParamsModel,
	DeleteProcessParamsModel,
	ProcessDesignDataExportParamsModel,
} from '@/api/process-management/model'
import { getViewText } from '@/utils/tool/translateValue' // getButtonPermission

import { USER_INFO_KEY } from '@/global/cacheKey'
import Storage from 'web-storage-cache'
import { UserInfo } from '@/types/store'

const columns = [
	// 流程名称
	{
		title: getI18n('system', 'SYSTEM_Process_Name'),
		dataIndex: 'name',
		align: 'center',
		fixed: 'left',
		slots: { customRender: 'name' },
		width: '28%',
	},
	// 流程描述
	{
		title: getI18n('system', 'SYSTEM_Process_Remark'),
		dataIndex: 'remark',
		align: 'center',
		slots: { customRender: 'remark' },
		width: '25%',
	},
	// 状态  启用/禁用
	{
		title: getI18n('system', 'SYSTEM_Category_Status'),
		dataIndex: 'status',
		align: 'center',
		customRender: ({ text }) => {
			return getViewText(
				Object.values(ProcessConstant.processStatus),
				text?.toString()
			)
		},
		width: '10%',
	},
	// 发布状态  已发布/未发布/-
	{
		title: getI18n('system', 'SYSTEM_Process_PublishingStatus'),
		dataIndex: 'pubstatus',
		align: 'center',
		slots: { customRender: 'pubstatus' },
		width: '10%',
	},
	// 更新时间
	{
		title: getI18n('system', 'SYSTEM_Process_UpdateTime'),
		dataIndex: 'updateTime',
		align: 'center',
		width: '13%',
		sorter: (a: ProcessManagementModel, b: ProcessManagementModel) =>
			dayjs(a.updateTime).valueOf() - dayjs(b.updateTime).valueOf(),
	},
	// 操作
	{
		title: getI18n('common', 'Common_Action'),
		align: 'center',
		key: 'operation',
		fixed: 'right',
		width: '14%',
		slots: { customRender: 'operation' },
	},
]

export default defineComponent({
	name: 'ProcessManagementList',
	components: {
		PlusOutlined,
		UploadOutlined,
		DownloadOutlined,
		ProcessCategoryTree,
		ProcessDesignSearch,
		ProcessDesignFormModal,
		ProcessDesignPublishEditorModal,
	},
	setup() {
		// 缓存中获取用户信息
		const localStorage = new Storage()
		const userInfo = reactive<UserInfo>(localStorage.get(USER_INFO_KEY))

		// 搜索按钮loading
		const searchLoading = ref<boolean>(false)
		// 列表loading
		const tableLoading = ref<boolean>(false)
		// 获取列表参数
		const processsListParams = reactive<GetProcessListParamsModel>({
			current: 1,
			size: 10,
		})

		// 列表数据
		const processsList = ref<ProcessManagementModel[]>([])
		// 列表分页
		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 mergeSearchParams = (val: GetProcessListParamsModel) => {
			processsListParams.name = val.name

			processsListParams.size = 10
			processsListParams.current = 1
		}

		// 获取表单列表数据
		const getProcessList = async () => {
			tableLoading.value = true
			const res: RequestResult<PaginationData<ProcessManagementModel>> =
				await getProcessListApi(processsListParams).finally(() => {
					tableLoading.value = false
					searchLoading.value = false
				})

			processsList.value = res.data
			tablePagination.current = res.pageinfo.currentPage
			tablePagination.pageSize = res.pageinfo.perPage
			tablePagination.total = res.pageinfo.total
		}
		// 列表change事件
		const onTableChange = (page: AntdTableChangePageType) => {
			processsListParams.size = page.pageSize
			processsListParams.current = page.current
			getProcessList()
		}
		// 搜索按钮事件
		const onSearchButtonClick = (params: GetProcessListParamsModel) => {
			searchLoading.value = true
			mergeSearchParams(params)
			getProcessList()
		}
		// 重置按钮事件
		const onResetButtonClick = (params: GetProcessListParamsModel) => {
			searchLoading.value = true
			processsListParams.size = 10
			processsListParams.current = 1
			mergeSearchParams(params)
			getProcessList()
			// context.emit('on-clear-tree-node')
		}

		const processId = ref<string>()
		const confirmAddModalVisible = ref<boolean>(false)
		// 新增
		const onProcessAddClick = () => {
			confirmAddModalVisible.value = true
		}
		// 编辑
		const onUpdateButtonClick = (id: string) => {
			processId.value = id
			confirmAddModalVisible.value = true
		}

		// 新增/编辑弹框取消按钮
		const onAddCancelClick = () => {
			processId.value = undefined
			confirmAddModalVisible.value = false
		}

		// 新增/编辑弹框确认按钮
		const onAddRefreshClick = async () => {
			processsListParams.size = 10
			processsListParams.current = 1
			await getProcessList()
			onAddCancelClick()
		}

		const confirmModalDeleteVisible = ref<boolean>(false) // 确认删除面板
		const deleteButtonLoading = ref<boolean>(false) // 确认删除按钮loading
		const deleteId = ref<string>('') // 删除参数
		// 删除按钮点击事件
		const onDeleteButtonClick = (id: string) => {
			confirmModalDeleteVisible.value = true
			deleteId.value = id
		}
		// 确认删除
		const onDeleteOkClick = async () => {
			let params: DeleteProcessParamsModel = {
				id: deleteId.value,
			}
			deleteButtonLoading.value = true
			await deleteProcessApi(params)
				.then(res => {
					if (res.data && res.data.code !== 200) {
						message.warning(
							res.data.msg || getI18n('common', 'Common_Failure')
						)
					} else {
						message.success(getI18n('common', 'Common_Success'))
					}
				})
				.finally(() => {
					deleteButtonLoading.value = false
					confirmModalDeleteVisible.value = false
				})

			// 如果是最后一页的最后一条数据，确认删除后查询上一页
			let _current = Math.ceil(
				(tablePagination.total - 1) / tablePagination.pageSize
			)
			processsListParams.current =
				processsListParams.current &&
				(processsListParams.current > _current
					? _current
					: processsListParams.current)

			await getProcessList()
		}
		// 取消删除
		const onDeleteCancelClick = () => {
			confirmModalDeleteVisible.value = false
		}

		// 流程设计点击
		const confirmModalProcessDesignVisible = ref<boolean>(false)
		const processDesignId = ref<string>() // 已发布状态传id
		const processDesignKey = ref<string>()
		// const processStatus = ref<string>() // 发布状态
		const onProcessDesignClick = (record: ProcessManagementModel) => {
			processDesignId.value = record.id
			processDesignKey.value = record.flowId
			confirmModalProcessDesignVisible.value = true
		}
		const onProcessDesignCloseClick = async () => {
			processDesignId.value = undefined
			processDesignKey.value = undefined
			confirmModalProcessDesignVisible.value = false
			await getProcessList()
		}

		const exportLoading = ref<boolean>(false)
		// 导出
		const onExportClick = async () => {
			exportLoading.value = true
			let params: ProcessDesignDataExportParamsModel = {
				applicationId: userInfo.applicationId,
				model: 1,
			}
			await processDesignDataExport(params).finally(() => {
				exportLoading.value = false
			})
		}

		// 导入弹窗 - 是否覆盖
		const importText = ref(
			getI18n('system', 'SYSTEM_Process_ImportReWrite')
		)
		const confirmModalImportVisible = ref<boolean>(false)
		const importButtonLoading = ref<boolean>(false) // 弹窗是否按钮
		const importLoading = ref<boolean>(false) // 列表导入按钮
		const importDataTemp = ref<string | Blob>('')
		//
		const resetImportData = () => {
			confirmModalImportVisible.value = false
			importButtonLoading.value = false
			importDataTemp.value = ''
		}
		// 覆盖
		const onImportOkClick = async () => {
			importButtonLoading.value = true

			await processDesignDataImport(
				importDataTemp.value,
				CommonConstant.isAdmin.yes.value.toString()
			).finally(() => {
				importLoading.value = false
				resetImportData()
			})
		}
		// 不覆盖
		const onImportCancelClick = async () => {
			importButtonLoading.value = true

			await processDesignDataImport(
				importDataTemp.value,
				CommonConstant.isAdmin.no.value.toString()
			).finally(() => {
				importLoading.value = false
				resetImportData()
			})
		}

		// 导入
		const onImportClick = async (data: { file: any | Blob }) => {
			const reg = new RegExp(/^data$/gi)
			if (
				data.file.name &&
				reg.test(
					data.file.name.substring(
						data.file.name.lastIndexOf('.') + 1
					)
				)
			) {
				importLoading.value = true
				confirmModalImportVisible.value = true
				importDataTemp.value = data.file
			} else {
				message.warning('请导入.data类型的文件！')
			}
		}

		// 左侧树选择的节点参数
		const onProcessCategoryTreeSelect = async (val: string) => {
			processsListParams.categoryId = val
			processsListParams.size = 10
			processsListParams.current = 1
			await getProcessList()
		}

		onMounted(() => {
			getProcessList()

			// if (
			// 	!getButtonPermission([
			// 		CommonConstant.permissionKeys.processSave.value, // 流程新增
			// 		CommonConstant.permissionKeys.processUpdate.value, // 流程编辑
			// 		CommonConstant.permissionKeys.processDelete.value, // 流程删除
			// 		CommonConstant.permissionKeys.processDesignDesign.value, // 流程设计
			// 	])
			// ) {
			// 	if (
			// 		columns.length > 0 &&
			// 		columns[columns.length - 1].key == 'operation'
			// 	) {
			// 		columns.pop()
			// 	}
			// }
		})
		return {
			ProcessConstant,
			style,
			getI18n, // 国际化

			searchLoading,
			tableLoading, // 列表loading
			processsList, // 列表数据
			columns,
			tablePagination,
			processId,
			confirmAddModalVisible,
			onAddRefreshClick,
			onAddCancelClick,

			confirmModalDeleteVisible,
			deleteButtonLoading,
			onDeleteOkClick,
			onDeleteCancelClick,

			onSearchButtonClick, // 搜索按钮事件
			onResetButtonClick, // 重置按钮事件
			onTableChange, // 列表change事件
			getViewText,

			onProcessAddClick,
			onUpdateButtonClick,
			onDeleteButtonClick,

			onProcessDesignClick,
			processDesignId,
			processDesignKey,
			confirmModalProcessDesignVisible,
			onProcessDesignCloseClick,

			onProcessCategoryTreeSelect,
			processsListParams,
			CommonConstant,
			// getButtonPermission,

			exportLoading,
			importLoading,
			onExportClick,
			onImportClick,
			importText,
			confirmModalImportVisible,
			importButtonLoading,
			onImportOkClick,
			onImportCancelClick,
		}
	},
})
</script>
