<script setup name="FlowDesign">
import { onMounted, ref, watch } from 'vue'
import CodeMirrorEditor from '@/components/CodeMirrorEditor/index.vue'

import ScWorkflow from '@/components/scWorkflow'
import useFlowStore from '@/store/modules/flow'
import useClipboard from 'vue-clipboard3'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'

const flowStore = useFlowStore()
const { modelContent } = storeToRefs(flowStore)
const { toClipboard } = useClipboard()

const formRef = ref()
const drawer = ref(false)
const jsonFormat = ref({})

let form = ref({
	processConfig: {
		nodeName: '发起人',
		type: 0,
		nodeAssigneeList: []
	}
})

// 接口保存审批流程
const saveDesign = json => {
	modelContent.value = JSON.stringify(form.value.processConfig)
}

const updateCompInfo = () => {
	if (modelContent.value) {
		const _val = JSON.parse(modelContent.value)
		form.value = Object.assign({ processConfig: _val }, {})
	}
}

// const copyParseJson = async () => {
// 	await toClipboard(JSON.stringify(jsonFormat.value, null, '  '))
// }

const copyJson = async () => {
	if (!jsonFormat.value) {
		return ElMessage.warning('当前没有数据噢')
	}
	const json = JSON.parse(jsonFormat.value || {})
	try {
		await toClipboard(JSON.stringify(json))
		ElMessage.success('复制成功')
	} catch (e) {
		ElMessage.warning('复制失败')
	}
}

const validate = () => {
	// 保存表单设计
	saveDesign()
	// 根据后续的业务需求 调整 validate 的功能
	return new Promise((resolve, reject) => {
		resolve()
	})
}

const openDrawerEv = () => {
	jsonFormat.value = JSON.stringify(form.value.processConfig, null, '  ')
	drawer.value = !drawer.value
}

const sureImportJson = () => {
	form.value.processConfig = JSON.parse(jsonFormat.value || {})
	drawer.value = !drawer.value
}

onMounted(() => {
	updateCompInfo()
})

defineExpose({
	formRef,
	saveDesign,
	validate,
	updateCompInfo
})
</script>

<template>
	<div>
		<div style="z-index: 999" class="fixed top-44 right-48">
			<el-button type="primary" @click="openDrawerEv"> 查看/导入 JSON </el-button>
		</div>

		<ScWorkflow v-model="form.processConfig"></ScWorkflow>

		<el-dialog v-if="drawer" v-model="drawer" class="le-dialog" size="600px" :append-to-body="true" title="查看JSON" destroy-on-close>
			<code-mirror-editor v-model="jsonFormat"></code-mirror-editor>
			<template #footer>
				<el-button type="primary" @click="copyJson">复制 JSON</el-button>
				<el-popconfirm title="确定应用JSON模型吗？" @confirm="sureImportJson">
					<template #reference>
						<el-button>导入JSON</el-button>
					</template>
				</el-popconfirm>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss"></style>
