<script setup name="FlowDesign">
import { onMounted, ref, watch } from 'vue'
import JsonEditorVue from 'json-editor-vue3'
import ScWorkflow from '@/components/scWorkflow'
import useFlowStore from '@/store/modules/flow'
import useClipboard from 'vue-clipboard3'
import { storeToRefs } from 'pinia'

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 () => {
	await toClipboard(JSON.stringify(jsonFormat.value))
}

watch(
	() => form.value.processConfig,
	value => {
		jsonFormat.value = form.value.processConfig
	},
	{
		// 初始化立即执行
		immediate: true
	}
)

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

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="() => (drawer = true)"> 查看 JSON </el-button>
		</div>

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

		<el-drawer v-model="drawer" size="500px" class="drawer" :append-to-body="true" :modal="false" :with-header="false">
			<div style="height: 100vh">
				<div style="padding: 1px; background-color: #3883fa">
					<el-button type="primary" plain @click="copyParseJson"> 复制 JSON </el-button>
					<el-button type="primary" plain @click="drawer = false"> 关闭弹窗 </el-button>
				</div>
				<json-editor-vue v-model="form.processConfig" class="editor" language="zh-CN" current-mode="view" />
			</div>
		</el-drawer>
	</div>
</template>

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