<template>
	<view class="nav_main">
		<view class="fixedheader">
			<headers :showBack="true">
				<view class="headerName">
					提交审批
				</view>
			</headers>
		</view>
		<view class="nav-type">
			<uni-segmented-control :current="current" :values="['流程表单', '流程步骤']" @clickItem="switchItem"
				styleType="text" activeColor="#4C87F3"></uni-segmented-control>
		</view>
		<view class="w-submit-form" scroll-y show-scrollbar :style="{height: contentHeight + 'px'}"
			@scroll="scroll">
			<view v-show="current === 0">
				<view class="w-start-dept" v-if="userDepts.length > 1">
					<view>发起人部门</view>
					<uni-data-checkbox v-model="startDept" :localdata="userDepts"></uni-data-checkbox>
				</view>
				<form-render ref="wform" :config="model.formConfig" :jsonConf="model.formItems"
					v-model="formData"></form-render>
			</view>
			<!-- {{ model.formItems }} -->
			<view class="w-process-render" v-show="current === 1">
				<process-render :key="updateKey" @render-ok="onRenderOk" ref="process" v-if="!loading && startDept"
					:process-def-id="model.processDefId" :dept-id="startDept" v-model="processUsers"
					:formData="formData" :process="model.process" />
			</view>
		</view>
		<view class="w-submit-opration">
			<button class="w-button" type="primary" @click="submitProcess">提交流程</button>
		</view>

	</view>

</template>

<script setup>
	import FormRender from "@/components/FormRender.vue";
	import ProcessRender from './ProcessRender.vue'
	import {
		ref,
		computed
	} from "vue";
	import {
		debounce
	} from '@/utils/tool.js'
	import {
		onLoad,
		onBackPress
	} from "@dcloudio/uni-app";
	import {
		getUserDepts
	} from '@/api/org.js'
	import {
		getInstanceFormData
	} from '@/api/task.js'
	import {
		getModelById
	} from '@/api/model.js'
	import {
		startProcess
	} from '@/api/process.js'

	const wform = ref()
	const process = ref()
	//表单数据
	const formData = ref({})
	//流程表单设计数据
	const model = ref({})
	const userDepts = ref([])
	//发起流程的部门
	const startDept = ref(null)
	//流程节点自选审批人/抄送人
	const processUsers = ref({})
	const submitLoading = ref(false)
	const loading = ref(false)
	//tab选项卡
	const current = ref(0)
	const updateKey = ref(0)

	const contentHeight = computed(() => {
		const h = uni.getSystemInfoSync().windowHeight
		if (window.plus) {
			return h - uni.upx2px(88) - uni.upx2px(44) - uni.upx2px(130)  - uni.upx2px(60);
		}
		return h - uni.upx2px(88) - uni.upx2px(60) - uni.upx2px(130);
	})

	onLoad((v) => {
		getModelInfo(v.code || '')
		getUserDept()
	})

	const onRenderOk = () => {
		console.log('onRenderOk');
		submitLoading.value = false;
		// updateKey.value += 1;
	}

	//当前登录的用户
	const loginUser = JSON.parse(uni.getStorageSync('loginUser'))

	//滚动延时去抖动
	const scDebounce = debounce(() => uni.$emit('showFp'), 500)

	function getModelInfo(code) {
		loading.value = true
		getModelById(code).then(rsp => {
			console.log(JSON.stringify(rsp), 777888999)
			model.value = rsp.data;
			loading.value = false
			//构建表单及校验规则
			//this.loadFormData()
		})
	}

	function getUserDept() {
		getUserDepts(loginUser.userId).then(rsp => {
			// if (userDepts.value.length > 0) {
			// 	startDept.value = userDepts.value[0].id
			// }
			userDepts.value = (rsp.data || []).map(v => {
				return {
					text: v.name,
					value: v.id
				}
			});

			if (userDepts.value.length > 0) {
				startDept.value = userDepts.value[0].value
			}
		})
	}

	function switchItem(v) {
		current.value = v.currentIndex;
		uni.$emit(current.value === 0 ? 'showFp' : 'hideFp')
	}

	function scroll(v) {
		// #ifdef APP-VUE
		uni.$emit('wv:scorll')
		//刷新文件选择器定位
		//#endif
		scDebounce()
	}

	function submitProcess() {
		wform.value.validate(formValid => {
			if (formValid) {
				process.value.validate(processValid => {
					if (processValid) {
						// return
						doSubmit()
					} else {
						current.value = 1
						uni.showToast({
							icon: 'none',
							title: '请按提示完成流程选项'
						})
					}
				})
			} else {
				current.value = 0
				uni.showToast({
					icon: 'none',
					title: '请按提示完成表单'
				})
			}
		})
	}

	function doSubmit() {
		let startParams = {
			deptId: startDept.value,
			formData: formData.value,
			processUsers: processUsers.value
		}
		startProcess(model.value.processDefId, startParams).then(rsp => {
			uni.showToast({
				icon: 'success',
				title: '发起成功'
			})
			uni.navigateBack({
				delta: 1
			});
			// uni.switchTab({
			// 	url: '/pages/submit/submit'
			// })
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: '发起失败: ' + err.msg
			})
		})
	}
</script>

<style lang="less" scoped>
	:deep(.w-submit-form) {
		// padding-bottom: 70px;
		overflow-y: auto;
		z-index: 100;
	}
	:deep(.headerBox) {
	  background: #2b8df3;
	  color: #fff;
	  .uni-icons {
		  color: #fff !important;
	  }
	}
	.nav_main {
		// height: calc(100% - 88rpx - 44rpx - env(safe-area-inset-top));
	}

	.w-start-dept {
		background: white;
		padding: 20rpx;
		margin-bottom: 20rpx;

		&>view {
			margin-bottom: 5rpx;
		}
	}

	.w-submit-opration {
		height: 70px;
		display: flex;
		align-items: center;

		//background-color: white;
		&>button {
			width: 100%;
			margin: 0 32rpx;
			padding: 20rpx 0;
		}
	}

	.w-process-render {
		background-color: white;
		padding: 16rpx;
	}

	.nav-type {
		background-color: white;
		border-bottom: 1px solid #F4F5F7;
	}
</style>