<template>
	<div class="flow-flowForm-container">
		<el-card shadow="hover">
			<div class="flow-flowForm-search mb15">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
					<el-row>
						<el-col :span="8" class="colBlock">
							<el-form-item :label="t('message.flowForm.formName')" prop="name">
								<el-input v-model="tableData.param.name" :placeholder="t('message.flowForm.enterFormName')" clearable @keyup.enter.native="flowFormList" />
							</el-form-item>
						</el-col>
						<el-col :span="8" class="colBlock">
							<el-form-item :label="t('message.flowForm.status')" prop="status">
								<el-select v-model="tableData.param.status" :placeholder="t('message.flowForm.selectStatus')" clearable style="width: 160px">
									<el-option v-for="dict in flow_form_status" :key="dict.value" :label="dict.label" :value="dict.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="!showAll ? 'colBlock' : 'colNone'">
							<el-form-item>
								<el-button type="primary" @click="flowFormList"
									><el-icon><ele-Search /></el-icon>{{ t('message.flowForm.search') }}</el-button
								>
								<el-button @click="resetQuery(queryRef)"
									><el-icon><ele-Refresh /></el-icon>{{ t('message.flowForm.reset') }}</el-button
								>
								<el-button type="primary" link @click="toggleSearch">
									{{ word }}
									<el-icon v-show="showAll"><ele-ArrowUp /></el-icon>
									<el-icon v-show="!showAll"><ele-ArrowDown /></el-icon>
								</el-button>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
							<el-form-item :label="t('message.flowForm.createTime')" prop="createdAt">
								<el-date-picker
									clearable
									style="width: 200px"
									v-model="tableData.param.createdAt"
									format="YYYY-MM-DD HH:mm:ss"
									value-format="YYYY-MM-DD HH:mm:ss"
									type="datetime"
									:placeholder="t('message.flowForm.selectCreateTime')"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
							<el-form-item>
								<el-button type="primary" @click="flowFormList"
									><el-icon><ele-Search /></el-icon>{{ t('message.flowForm.search') }}</el-button
								>
								<el-button @click="resetQuery(queryRef)"
									><el-icon><ele-Refresh /></el-icon>{{ t('message.flowForm.reset') }}</el-button
								>
								<el-button type="primary" link @click="toggleSearch">
									{{ word }}
									<el-icon v-show="showAll"><ele-ArrowUp /></el-icon>
									<el-icon v-show="!showAll"><ele-ArrowDown /></el-icon>
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button type="primary" @click="handleAdd" v-auth="'add'"
							><el-icon><ele-Plus /></el-icon>{{ t('message.flowForm.add') }}</el-button
						>
					</el-col>
					<el-col :span="1.5">
						<el-button type="success" :disabled="single" @click="handleUpdate(null)" v-auth="'edit'"
							><el-icon><ele-Edit /></el-icon>{{ t('message.flowForm.edit') }}</el-button
						>
					</el-col>
					<el-col :span="1.5">
						<el-button type="danger" :disabled="multiple" @click="handleDelete(null)" v-auth="'del'"
							><el-icon><ele-Delete /></el-icon>{{ t('message.flowForm.delete') }}</el-button
						>
					</el-col>
					<el-col :span="1.5">
						<el-button type="info" @click="handleImport"
							><el-icon><ele-Upload /></el-icon>{{ t('message.flowForm.import') }}</el-button
						>
					</el-col>
					<el-col :span="1.5">
						<el-button type="primary" :disabled="multiple" @click="handleExport"
							><el-icon><ele-Download /></el-icon>{{ t('message.flowForm.export') }}</el-button
						>
					</el-col>
				</el-row>
			</div>
			<el-table v-loading="loading" :data="tableData.data" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column :label="t('message.flowForm.primaryKey')" align="center" prop="id" min-width="150px" />
				<el-table-column :label="t('message.flowForm.formName')" align="center" prop="name" min-width="150px" />
				<el-table-column :label="t('message.flowForm.status')" align="center" prop="status" :formatter="statusFormat" min-width="150px" />
				<el-table-column :label="t('message.flowForm.deploymentStatus')" align="center" prop="status" :formatter="isPubFormat" min-width="150px" />
				<el-table-column :label="t('message.flowForm.remark')" align="center" prop="remark" min-width="150px" />
				<el-table-column :label="t('message.flowForm.createTime')" align="center" prop="createdAt" min-width="150px">
					<template #default="scope">
						<span>{{ proxy.parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
					</template>
				</el-table-column>
				<el-table-column :label="t('message.flowForm.creator')" align="center" prop="createdBy" min-width="150px" />
				<el-table-column :label="t('message.flowForm.operation')" align="center" class-name="small-padding" min-width="200px" fixed="right">
					<template #default="scope">
						<el-button type="primary" link @click="handleView(scope.row)" v-auth="'detail'"
							><el-icon><ele-View /></el-icon>{{ t('message.flowForm.detail') }}</el-button
						>
						<el-button type="primary" link @click="handleUpdate(scope.row)" v-auth="'edit'"
							><el-icon><ele-EditPen /></el-icon>{{ t('message.flowForm.edit') }}</el-button
						>
						<el-button type="primary" link @click="handleGen(scope.row)" v-auth="'gen'"
							><el-icon><ele-Position /></el-icon>{{ t('message.flowForm.deployForm') }}</el-button
						>
						<el-button type="primary" link @click="handleDelete(scope.row)" v-auth="'del'"
							><el-icon><ele-DeleteFilled /></el-icon>{{ t('message.flowForm.delete') }}</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<pagination
				v-show="tableData.total > 0"
				:total="tableData.total"
				v-model:page="tableData.param.pageNum"
				v-model:limit="tableData.param.pageSize"
				@pagination="flowFormList"
			/>
		</el-card>
		<ApiV1FlowFlowFormDetail ref="detailRef" :statusOptions="flow_form_status" @flowFormList="flowFormList"></ApiV1FlowFlowFormDetail>
	</div>
</template>
<script lang="ts">
import { computed, defineComponent, getCurrentInstance, onMounted, reactive, ref, toRaw, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { addFlowForm, delFlowForm, genFlowForm, getFlowForm, listFlowForm } from '/@/api/flow/flowForm'
import {
	FlowFormInfoData,
	FlowFormTableColumns,
	FlowFormTableDataState
} from '/@/views/flow/flowForm/list/component/model'
import ApiV1FlowFlowFormDetail from '/@/views/flow/flowForm/list/component/detail.vue'
import { useRouter } from 'vue-router'
import download from 'downloadjs'
import { useFileDialog } from '@vueuse/core'

export default defineComponent({
	name: 'ApiV1FlowFlowFormList',
	components: {
		ApiV1FlowFlowFormDetail,
	},
	setup() {
		const router = useRouter()
		const { proxy } = <any>getCurrentInstance()
		const { t } = useI18n()
		const loading = ref(false)
		const queryRef = ref()
		const editRef = ref()
		const detailRef = ref()
		// 是否显示所有搜索选项
		const showAll = ref(false)
		// 非单个禁用
		const single = ref(true)
		// 非多个禁用
		const multiple = ref(true)
		const word = computed(() => {
			if (showAll.value === false) {
				//对文字进行处理
				return t('message.flowForm.expandSearch')
			} else {
				return t('message.flowForm.collapseSearch')
			}
		})
		// 字典选项数据
		const { flow_form_status } = proxy.useDict('flow_form_status')
		const state = reactive<FlowFormTableDataState>({
			ids: [],
			tableData: {
				data: [],
				total: 0,
				loading: false,
				param: {
					pageNum: 1,
					pageSize: 10,
					name: undefined,
					status: undefined,
					createdAt: undefined,
					dateRange: [],
					isPub: undefined,
				},
			},
		})
		// 页面加载时
		onMounted(() => {
			initTableData()
		})
		// 初始化表格数据
		const initTableData = () => {
			flowFormList()
		}
		/** 重置按钮操作 */
		const resetQuery = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			flowFormList()
		}
		// 获取列表数据
		const flowFormList = () => {
			loading.value = true
			listFlowForm(state.tableData.param).then((res: any) => {
				let list = res.list ?? []
				list.map((item: any) => {
					item.createdBy = item.createdUser?.userNickname
				})
				state.tableData.data = list
				state.tableData.total = res.total
				loading.value = false
			})
		}
		const toggleSearch = () => {
			showAll.value = !showAll.value
		}
		// 状态字典翻译
		const statusFormat = (row: FlowFormTableColumns) => {
			return proxy.selectDictLabel(flow_form_status.value, row.status)
		}
		const isPubFormat = (row: FlowFormTableColumns) => {
			return row.isPub ? t('message.flowForm.deployed') : t('message.flowForm.notDeployed')
		}
		// 多选框选中数据
		const handleSelectionChange = (selection: Array<FlowFormInfoData>) => {
			state.ids = selection.map((item) => item.id)
			single.value = selection.length != 1
			multiple.value = !selection.length
		}
		const handleAdd = () => {
			router.push('/flow/flowForm/formDesign')
		}
		const handleUpdate = (row: FlowFormTableColumns) => {
			if (!row) {
				row = state.tableData.data.find((item: FlowFormTableColumns) => {
					return item.id === state.ids[0]
				}) as FlowFormTableColumns
			}
			router.push('/flow/flowForm/formDesign?id=' + row.id)
		}
		const handleGen = (row: FlowFormTableColumns) => {
			ElMessageBox.confirm(t('message.flowForm.confirmDeploy'), t('message.flowForm.tip'), {
				confirmButtonText: t('message.flowForm.confirm'),
				cancelButtonText: t('message.flowForm.cancel'),
				type: 'warning',
			})
				.then(() => {
					genFlowForm(row.id).then(() => {
						ElMessage.success(t('message.flowForm.deploySuccess'))
						flowFormList()
					})
				})
				.catch()
		}
		const handleDelete = (row: FlowFormTableColumns) => {
			let msg = t('message.flowForm.confirmDeleteSelected')
			let id: number[] = []
			if (row) {
				msg = t('message.flowForm.confirmDeleteSingle')
				id = [row.id]
			} else {
				id = state.ids
			}
			if (id.length === 0) {
				ElMessage.error(t('message.flowForm.pleaseSelectDeleteData'))
				return
			}
			ElMessageBox.confirm(msg, t('message.flowForm.tip'), {
				confirmButtonText: t('message.flowForm.confirm'),
				cancelButtonText: t('message.flowForm.cancel'),
				type: 'warning',
			})
				.then(() => {
					delFlowForm(id).then(() => {
						ElMessage.success(t('message.flowForm.deleteSuccess'))
						flowFormList()
					})
				})
				.catch(() => {})
		}
		const handleView = (row: FlowFormTableColumns) => {
			detailRef.value.openDialog(toRaw(row))
		}

		const { open, files, reset } = useFileDialog({
			multiple: false,
			accept: '.json',
		})
		const handleImport = open

		watch(files, async (newVal) => {
			if (newVal === null || newVal?.length === 0) {
				return
			}

			const file = newVal[0]
			const json = await new Promise<string>((resolve, reject) => {
				const reader = new FileReader()
				reader.readAsText(file)
				reader.onload = function (e: ProgressEvent<FileReader>) {
					if (e.target === null) {
						reject()
						return
					}
					if (typeof e.target.result == 'string') {
						resolve(e.target.result)
						return
					}
					reject()
				}
			})

			const x = JSON.parse(json)
			const result = await Promise.all<{ success: boolean; result?: FlowFormInfoData }>(
				x.map(async (it: FlowFormInfoData) => {
					return await addFlowForm(it)
						.then(() => {
							return { success: true }
						})
						.catch(() => {
							return { success: false, result: it }
						})
				})
			)

			const failed = result.filter((it) => !it)
			if (failed.length == 0) {
				ElMessage.success(t('message.flowForm.importSuccess'))
				flowFormList()
				reset()
				return
			}

			const showErrorDialog = await ElMessageBox.alert(t('message.flowForm.importFailed', { count: failed.length }), t('message.flowForm.tip'), {
				confirmButtonText: t('message.flowForm.viewFailedData'),
				cancelButtonText: t('message.flowForm.confirm'),
				type: 'warning',
			})

			if (showErrorDialog) {
				download(JSON.stringify(failed.map((it) => it.result)), t('message.flowForm.failedFileName'))
			}

			reset()
		})

		const handleExport = async () => {
			const exp: Array<any> = await Promise.all(state.ids.map(getFlowForm))
			download(
				JSON.stringify(
					exp.map((it) => {
						return {
							name: it.name,
							conf: it.conf,
							fields: it.fields,
							remark: it.remark,
							status: it.status,
						}
					})
				),
				t('message.flowForm.exportFileName')
			)
		}
		return {
			t,
			proxy,
			editRef,
			detailRef,
			showAll,
			loading,
			single,
			multiple,
			word,
			queryRef,
			resetQuery,
			flowFormList,
			toggleSearch,
			statusFormat,
			flow_form_status,
			handleSelectionChange,
			handleAdd,
			handleUpdate,
			handleDelete,
			handleView,
			handleGen,
			isPubFormat,
			handleImport,
			handleExport,
			...toRefs(state),
		}
	},
})
</script>
<style lang="scss" scoped>
.colBlock {
	display: block;
}
.colNone {
	display: none;
}
.ml-2 {
	margin: 3px;
}
</style>
