// 系统配置
<template>
	<a-card>
		<a-spin :spinning="submitButtonLoading">
			<a-form
				ref="formRef"
				:model="formState"
				:rules="formRules"
				:label-col="labelCol"
				:wrapper-col="wrapperCol"
			>
				<a-collapse
					v-model:activeKey="activeKey"
					:expand-icon-position="'right'"
					:accordion="true"
				>
					<a-collapse-panel
						v-for="item in data"
						:key="item.key"
						:header="item.header"
					>
						<a-form-item
							:label="item.header"
							:name="item.key"
							:ref="item.key"
						>
							<codemirror
								class="custom-codemirror"
								:ref="item.key"
								v-model="item.data"
								:placeholder="
									getI18n('common', 'Common_Please_Enter', [
										getI18n(
											'system',
											'SYSTEM_Process_ScriptValue'
										),
									])
								"
								:spellcheck="true"
								:autofocus="true"
								:indent-with-tab="true"
								:tab-size="4"
								:autoRefresh="true"
								:style="{ fontSize: '18px' }"
								:extensions="extensions"
								@change="e => onValueChange(item.key, e)"
							/>
						</a-form-item>
						<!-- <template #extra v-if="item.key == 'customFormFieldsOptions'">
							<a-checkbox v-model:checked="fromEngineFormFields" @click.stop=" e => onChangeFromEngineFormFields(e)">表单引擎</a-checkbox>
						</template> -->
						<!-- <setting-outlined /> -->
					</a-collapse-panel>
				</a-collapse>
			</a-form>

			<a-row>
				<a-col :span="24" style="margin-top: 1em; text-align: right">
					<a-button
						type="primary"
						:loading="submitButtonLoading"
						@click="onSubmitClick"
					>
						{{ getI18n('common', 'Common_Save') }}
					</a-button>
				</a-col>
			</a-row>
		</a-spin>
	</a-card>
</template>
<script lang="ts">
import { message } from 'ant-design-vue'
// import { SettingOutlined } from '@ant-design/icons-vue'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { getI18n } from '@/utils/i18n'

import { validatenull, deepClone } from '@/utils/tool/translateValue'
import { ConfigModel } from '@/api/system-config/model'
import {
	saveConfigApi,
	updateConfigApi,
	getConfigApi,
} from '@/api/system-config'

import { Codemirror } from 'vue-codemirror'
import { basicSetup, EditorView } from 'codemirror'
import { EditorState } from '@codemirror/state'
import { autocompletion } from '@codemirror/autocomplete'
import { javascript } from '@codemirror/lang-javascript'
// import { oneDark } from '@codemirror/theme-one-dark'

export default defineComponent({
	components: {
		// SettingOutlined,
		Codemirror,
	},
	setup() {
		const submitButtonLoading = ref<boolean>(false)
		const activeKey = ref(['processDesignConfig'])

		const formRef = ref()
		const formState = reactive<{ [propname: string]: any }>({
			processDesignConfig: `
getProcessDesignConfig = () => {
    // 获取token, design端存储在缓存中token的key为 'JCAccessToken'
    const getAuthenticationToken = () => {
        return rbacStorageToken = window.localStorage.getItem('JCAccessToken')||''
    }
	// design端存储在缓存中应用ID的key为'JCINFOBPMDESIGN_USER_APPLICATION_ID'
    const applicationId = window.localStorage.getItem('JCINFOBPMDESIGN_USER_APPLICATION_ID')||'' 
	// design端存储在缓存中应用类型的key为'JCINFOBPMDESIGN_USER_APPLICATION_TYPE'
    const applicationType = window.localStorage.getItem('JCINFOBPMDESIGN_USER_APPLICATION_TYPE')||'' 
    return {
        AuthenticationToken: getAuthenticationToken,
        ManageRequestPrefix: window['REQUEST_URL']['MANAGE-API'], // design端默认接口前缀
        ApplicationId: applicationId,
        AuthorizationAppType: applicationType,
    }
}
`,
			permissionButtonData: '',
			microflowItemList: '',
			flowConditionalList: '',
			taskTitleList: '',
			customTabOptions: ``,
			customFormTabOptions: '',
			customFormFieldsOptions: '',
			customEngineFormFieldsOptions: '',
			customConnectorsOptions: '',
		})

		const data = ref([
			{
				key: 'processDesignConfig',
				header: '配置项',
				data: formState.processDesignConfig,
				scriptAreaRef: 'editorRefDesignConfig',
			},
			{
				key: 'permissionButtonData',
				header: '操作设置数据',
				data: formState.permissionButtonData,
				scriptAreaRef: 'editorRefButtonData',
			},
			{
				key: 'microflowItemList',
				header: '服务组件',
				data: formState.microflowItemList,
				scriptAreaRef: 'editorRefMicroflow',
			},
			{
				key: 'flowConditionalList',
				header: '条件设置-表达式',
				data: formState.flowConditionalList,
				scriptAreaRef: 'editorRefFlowConditional',
			},
			{
				key: 'taskTitleList',
				header: '待办标题',
				data: formState.taskTitleList,
				scriptAreaRef: 'editorRefTaskTitle',
			},
			{
				key: 'customTabOptions',
				header: '设置经办者',
				data: formState.customTabOptions,
				scriptAreaRef: 'editorRefCustomTabOptions',
			},
			{
				key: 'customFormTabOptions',
				header: '表单配置',
				data: formState.customFormTabOptions,
				scriptAreaRef: 'editorRefCustomFormTabOptions',
			},
			{
				key: 'customFormFieldsOptions',
				header: '本地应用 - 资源配置',
				data: formState.customFormFieldsOptions,
				scriptAreaRef: 'editorRefCustomFormFieldsOptions',
			},
			{
				key: 'customEngineFormFieldsOptions',
				header: '表单引擎 - 资源配置',
				data: formState.customEngineFormFieldsOptions,
				scriptAreaRef: 'editorRefCustomEngineFormFieldsOptions',
			},
			{
				key: 'customConnectorsOptions',
				header: '连接器',
				data: formState.customConnectorsOptions,
				scriptAreaRef: 'editorRefCustomConnectorsOptions',
			},
		])

		const formRules = {
			processDesignConfig: [
				{
					required: true,
					message: getI18n('common', 'Common_Please_Enter', [
						'配置项',
					]),
					trigger: 'change',
				},
			],
		}

		const isConfigExist = ref<boolean>(false)
		const configId = ref<string>('')

		// 保存
		const onSubmitClick = () => {
			submitButtonLoading.value = true

			formRef.value.validate().then(async () => {
				let params: ConfigModel = {
					textJson: JSON.stringify(formState),
				}

				if (!isConfigExist.value) {
					await saveConfigApi(params).finally(() => {
						submitButtonLoading.value = false
						message.success(getI18n('common', 'Common_Success'))
					})
				} else {
					if (!configId.value) {
						message.warning('数据不存在')
						return
					}
					await updateConfigApi(params, configId.value).finally(() => {
						submitButtonLoading.value = false
						message.success(getI18n('common', 'Common_Success'))
					})
				}
			})
		}

		const editorRefDesignConfig = ref()
		const editorRefButtonData = ref()
		const editorRefMicroflow = ref()
		const editorRefFlowConditional = ref()
		const editorRefTaskTitle = ref()
		const editorRefCustomTabOptions = ref()
		const editorRefCustomFormTabOptions = ref()
		const editorRefCustomFormFieldsOptions = ref()
		const editorRefCustomEngineFormFieldsOptions = ref()
		const editorRefCustomConnectorsOptions = ref()

		let extensions = [basicSetup, autocompletion(), javascript({})]

		const initEditor = () => {
			// 1
			if (typeof editorRefDesignConfig.value !== 'undefined') {
				editorRefDesignConfig.value.destroy()
			}
			const startStateDesignConfig = EditorState.create({
				doc: formState.processDesignConfig,
			})
			if (editorRefDesignConfig.value) {
				editorRefDesignConfig.value = new EditorView({
					state: startStateDesignConfig,
					parent: editorRefDesignConfig.value,
				})
				editorRefDesignConfig.value.refresh()
			}

			// 2
			if (typeof editorRefButtonData.value !== 'undefined') {
				editorRefButtonData.value.destroy()
			}
			const startStateButtonData = EditorState.create({
				doc: formState.permissionButtonData,
			})
			if (editorRefButtonData.value) {
				// editorRef.value
				editorRefButtonData.value = new EditorView({
					state: startStateButtonData,
					parent: editorRefButtonData.value,
				})
				editorRefButtonData.value.refresh()
			}

			// 3
			if (typeof editorRefMicroflow.value !== 'undefined') {
				editorRefMicroflow.value.destroy()
			}
			const startStateMicroflow = EditorState.create({
				doc: formState.microflowItemList,
			})
			if (editorRefMicroflow.value) {
				editorRefMicroflow.value = new EditorView({
					state: startStateMicroflow,
					parent: editorRefMicroflow.value,
				})
				editorRefMicroflow.value.refresh()
			}

			// 4
			if (typeof editorRefFlowConditional.value !== 'undefined') {
				editorRefFlowConditional.value.destroy()
			}
			const startStateConditional = EditorState.create({
				doc: formState.flowConditionalList,
			})
			if (editorRefFlowConditional.value) {
				editorRefFlowConditional.value = new EditorView({
					state: startStateConditional,
					parent: editorRefFlowConditional.value,
				})
				editorRefFlowConditional.value.refresh()
			}

			// 5
			if (typeof editorRefTaskTitle.value !== 'undefined') {
				editorRefTaskTitle.value.destroy()
			}
			const startStateTaskTitle = EditorState.create({
				doc: formState.taskTitleList,
			})
			if (editorRefTaskTitle.value) {
				editorRefTaskTitle.value = new EditorView({
					state: startStateTaskTitle,
					parent: editorRefTaskTitle.value,
				})
				editorRefTaskTitle.value.refresh()
			}

			// 6
			if (typeof editorRefCustomTabOptions.value !== 'undefined') {
				editorRefCustomTabOptions.value.destroy()
			}
			const startStateCustomTabOptions = EditorState.create({
				doc: formState.customTabOptions,
			})
			if (editorRefCustomTabOptions.value) {
				editorRefCustomTabOptions.value = new EditorView({
					state: startStateCustomTabOptions,
					parent: editorRefCustomTabOptions.value,
				})
				editorRefCustomTabOptions.value.refresh()
			}

			// 7
			if (typeof editorRefCustomFormTabOptions.value !== 'undefined') {
				editorRefCustomFormTabOptions.value.destroy()
			}
			const startStateCustomFormTabOptions = EditorState.create({
				doc: formState.customFormTabOptions,
			})
			if (editorRefCustomFormTabOptions.value) {
				// editorRef.value
				editorRefCustomFormTabOptions.value = new EditorView({
					state: startStateCustomFormTabOptions,
					parent: editorRefCustomFormTabOptions.value,
				})
				editorRefCustomFormTabOptions.value.refresh()
			}

			// 8
			if (typeof editorRefCustomFormFieldsOptions.value !== 'undefined') {
				editorRefCustomFormFieldsOptions.value.destroy()
			}
			const startStateCustomFormFieldsOptions = EditorState.create({
				doc: formState.customFormFieldsOptions,
			})
			if (editorRefCustomFormFieldsOptions.value) {
				// editorRef.value
				editorRefCustomFormFieldsOptions.value = new EditorView({
					state: startStateCustomFormFieldsOptions,
					parent: editorRefCustomFormFieldsOptions.value,
				})
				editorRefCustomFormFieldsOptions.value.refresh()
			}

			// 9
			if (
				typeof editorRefCustomEngineFormFieldsOptions.value !==
				'undefined'
			) {
				editorRefCustomEngineFormFieldsOptions.value.destroy()
			}
			const startStateCustomEngineFormFieldsOptions = EditorState.create({
				doc: formState.customEngineFormFieldsOptions,
			})
			if (editorRefCustomEngineFormFieldsOptions.value) {
				// editorRef.value
				editorRefCustomEngineFormFieldsOptions.value = new EditorView({
					state: startStateCustomEngineFormFieldsOptions,
					parent: editorRefCustomEngineFormFieldsOptions.value,
				})
				editorRefCustomEngineFormFieldsOptions.value.refresh()
			}

			// 10
			if (typeof editorRefCustomConnectorsOptions.value !== 'undefined') {
				editorRefCustomConnectorsOptions.value.destroy()
			}
			const startStateCustomConnectorsOptions = EditorState.create({
				doc: formState.customConnectorsOptions,
				// extensions: [
				// 	basicSetup,
				// 	oneDark,
				// 	autocompletion(),
				// 	javascript({}),
				// ],
			})
			if (editorRefCustomConnectorsOptions.value) {
				// editorRef.value
				editorRefCustomConnectorsOptions.value = new EditorView({
					state: startStateCustomConnectorsOptions,
					parent: editorRefCustomConnectorsOptions.value,
				})
				editorRefCustomConnectorsOptions.value.refresh()
			}
		}

		const onValueChange = (key: string, e: any) => {
			formState[key] = e
		}

		// 查询
		const getConfig = async () => {
			await getConfigApi().then(res => {
				if (!validatenull(res.data)) {
					isConfigExist.value = true
					configId.value = res.data[0].id

					const _res = deepClone(res.data)
					const _formState = JSON.parse(_res[0].textJson)

					formState.processDesignConfig =
						_formState.processDesignConfig
					formState.permissionButtonData =
						_formState.permissionButtonData
					formState.microflowItemList = _formState.microflowItemList
					formState.flowConditionalList =
						_formState.flowConditionalList
					formState.taskTitleList = _formState.taskTitleList
					formState.customTabOptions = _formState.customTabOptions
					formState.customFormTabOptions =
						_formState.customFormTabOptions
					formState.customFormFieldsOptions =
						_formState.customFormFieldsOptions
					formState.customEngineFormFieldsOptions =
						_formState.customEngineFormFieldsOptions
					formState.customConnectorsOptions =
						_formState.customConnectorsOptions

					data.value[0].data = formState.processDesignConfig
					data.value[1].data = formState.permissionButtonData
					data.value[2].data = formState.microflowItemList
					data.value[3].data = formState.flowConditionalList
					data.value[4].data = formState.taskTitleList
					data.value[5].data = formState.customTabOptions
					data.value[6].data = formState.customFormTabOptions
					data.value[7].data = formState.customFormFieldsOptions
					data.value[8].data = formState.customEngineFormFieldsOptions
					data.value[9].data = formState.customConnectorsOptions
				}
			})
			initEditor()
		}

		onMounted(() => {
			getConfig()
		})

		return {
			activeKey,

			formRef,
			formRules,
			formState,
			labelCol: { span: 0 },
			wrapperCol: { span: 24 },
			getI18n,
			onSubmitClick,
			submitButtonLoading,
			data,
			onValueChange,
			extensions,
		}
	},
})
</script>
