<!--
@ 作者: 秦东
@ 时间: 2024-05-07 15:07:51
@ 备注: 表单流程
-->
<script lang='ts' setup>
import { useStore } from '@/store/workflow/index' 
import { flowversion } from '@/api/workflowapi/types'
import { initializeWorkFlow,setWorkFlowData,gainFlowVersionList,saveFlowCont,gainFlowInfo,editFlowCont,saveNewFlow,switchFlowVersion,judgeFormFlowIsOpen,openFormFlow } from '@/api/workflowapi/index'
import FlowImgSrc from '@/assets/images/3.png'
const props = defineProps({
	appCont:{
		type:Object,
		default(){
			return {}
		}
	},
	formKey:{
		type:String,
		default:""
	},
	groupKey:{
		type:String,
		default:""
	},
	menuId:{
		type:String,
		default:""
	},
	appPageKey:{
		type:String,
		default:""
	},
	formVersion:{
		type:String,
		default:""
	},
	state:{
		type:Object,
		default(){
			return {}
		}
	}
});
const emits = defineEmits<{
    (e: 'update:state', val: formStruct): void
	(e: 'update:formKey', val: string): void
	(e: 'update:appPageKey', val: string): void
	// (e: 'judgeFlowIsEdit', val: boolean): void
	// (e: 'runNextWindows', val: number): void
	// (e: 'closeFormPage'): void
}>()
const state =  computed({
	get() {
		return props.state
	},
	set(val: formStruct) {
		emits('update:state', val)
	}
});
const appPageKey =  computed({
	get() {
		return props.appPageKey
	},
	set(val: formStruct) {
		emits('update:appPageKey', val)
	}
});
let { setTableId, setIsTried } = useStore()
const openOfClise = ref(false)  //当前版本状态
const flowIsTrue = ref(false) 			//判断流程是否使用
const isRead = ref(false)      //判断操作功能按钮
const activeTabs = ref<string>("");			//当前工作流版本
const versionList = reactive<flowversion[]>([]); //工作流版本列表
const nowVal = ref(100);	//缩放比例
let nodeConfig = ref<any>({}); 	//节点配置
let flowPermission = ref([]); //工作流权限
const enableVersion = ref<string>("1");    //流程版本
const enableFlow = ref<any>();
let tipList = ref<any>([]);		//信息提示
let processConfig = ref<any>({});	//工作流信息
let directorMaxLeveling = ref<number>(0);	//主管深度（层级）
let workFlowDef = ref({});			//流程名称
let tipVisible = ref(false);
const closeOrOpenVersion = ref(false);  //判断是否显示版本启用与关闭
let oneIsTrue = true;
//缩放画布
const zoomSize = (type:number) => {
	if (type == 1) {
		if (nowVal.value == 50) {
		return;
		}
		nowVal.value -= 10;
	} else {
		if (nowVal.value == 300) {
		return;
		}
		nowVal.value += 10;
	}
};
/**
@ 作者: 秦东
@ 时间: 2024-03-11 16:33:49
@ 功能: 开启流程
*/
const createFormFlow = () =>{
	if(appPageKey.value == ""){
		flowIsTrue.value = false;
		ElMessageBox.alert('您还未设置表单！请先设置完表单后，在创建流程！','温馨提示！',{
			confirmButtonText: '确定',
			callback: (action: Action) => {
				// emits("runNextWindows",1);
			},
		})
	}else{
		openOrCloseFormFlow(1)
		flowIsTrue.value = true
		getFlowVerList()
	}

	// flowIsTrue.value = true
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 11:29:46
@ 功能: 获取工作流版本列表
*/
const getFlowVerList = ()=>{
	gainFlowVersionList({id:appPageKey.value.toString()})
		.then(({data})=>{
			console.log("获取工作流版本列表-->",data)
			// versionList = data;
			versionList.splice(0,versionList.length)
			if(data){
				if(data.length>0){

					data.forEach((item:any)=>{

						if(item.state == 1){
							activeTabs.value = item.id
							enableFlow.value = item
							enableVersion.value = item.id
						}
						versionList.push({
							id:item.id,
							key:item.key,
							state:item.state,
							version:item.version
						})
					})
					if(versionList.length > 1){
						closeOrOpenVersion.value = true
					}else{
						closeOrOpenVersion.value = false
					}
					
					// console.log("获取工作流版本列表--1-1-->",enableFlow.value);
					if(enableFlow.value == "" || enableFlow.value == undefined){
						enableFlow.value = versionList[0]
						// activeTabs.value = versionList[0].id
						enableVersion.value = versionList[0].id
					}
					isRead.value = true
				}else{
					isRead.value = false

				}
			}
			// console.log("获取工作流版本列表---1-->",activeTabs.value);
			// console.log("获取工作流版本列表---2-->",enableFlow.value);
			// console.log("获取工作流版本列表---3-->",enableVersion.value);
			// console.log("获取工作流版本列表---3-1->",versionList[0],versionList);
		})
		.finally(()=>{
			
			if(isRead.value == true){
				gainFlowCont();
			}else{
				clearCanvas(1);
			}
			clickOpenOrClose();
			
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 11:40:34
@ 功能: 判断当前工作流版本是否启用
*/
const clickOpenOrClose = () => {
	// console.log("判断当前工作流版本是否启用",enableFlow,activeTabs.value)
	if(enableFlow.value.id==activeTabs.value){
		openOfClise.value = true
	}else{
		openOfClise.value = false
	}
	// console.log("openOfClise",openOfClise.value)
	// console.log("enableFlow.version=1=activeTabs",enableFlow.value,activeTabs.value)
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 11:37:19
@ 功能: 清空画布
*/
const clearCanvas = (isOk?:any) =>{
	if(isOk==1){
		initWorkFlowData()
		setIsTried(false);
		tipList.value = []
	}else{
		ElMessageBox.confirm('确定要清空画布?')
		.then(() => {
			initWorkFlowData()
			setIsTried(false);
			tipList.value = []
		})
	}
	
	enableFlow.value = ""
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 11:37:46
@ 功能: 初始化工作流数据
*/
const initWorkFlowData = async() => {
	let { data } = await initializeWorkFlow({name:state.value.formData.form.formName})
	// console.log("data-=------>",data)
	processConfig.value = data;
	let {
		nodeConfig:nodes,
		flowPermission:flowPermissiones,
		directorMaxLevel:levels,
		workFlowDef:workName,
		tableId,
	} = data;
	processConfig.value.workFlowDef.formKey = appPageKey.value
	nodeConfig.value = nodes;
	flowPermission.value = flowPermissiones;
	directorMaxLeveling = levels;
	workFlowDef.value = workName;

	setTableId(tableId);
	// console.log("max--1->",data)
	// console.log("max--6->",tableId)
	// console.log("max--2->",flowPermission)
	// console.log("max--3->",nodeConfig)
	// console.log("max--4->",directorMaxLevel)
	// console.log("max--5->",processConfig)
}
//缩放画布
/**
@ 作者: 秦东
@ 时间: 2024-05-21 11:26:41
@ 功能: 编辑表单流程状态
*/
const openOrCloseFormFlow = (val:number) => {
	openFormFlow({id:appPageKey.value.toString(),status:val})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 10:10:46
@ 功能: 组件加载完毕执行数据初始化
*/
onMounted(()=>{
	console.log("判断是否已经存在工作流以及是否开启",appPageKey.value)
	if(appPageKey.value == ""){
		flowIsTrue.value = false;
	}else{
		judgeFormFlowIsOpen({id:appPageKey.value.toString()})
			.then((data)=>{
				// console.log("判断是否已经存在工作流以及是否开启",data)
				if(data.data.isOpen == 1){
					flowIsTrue.value = true;
					// emits('judgeFlowIsEdit', false)
					getFlowVerList()
				}else{
					flowIsTrue.value = false;
					// emits('judgeFlowIsEdit', false)
				}
			})
	}
})
/**
@ 作者: 秦东
@ 时间: 2024-05-21 13:57:13
@ 功能: 流程版本启用禁用
*/
const setupState = (val:number) =>{
	let sendCont = {
		id:enableVersion.value.toString(),
		status:val
	}
	if(val == 1){
		activeTabs.value = enableVersion.value
	}
	console.log("流程版本启用禁用",sendCont)
	switchFlowVersion(sendCont)
		.then((data:any)=>{
			ElMessage.success(data.msg);
			// activeTabs.value = enableVersion.value
			// enableFlow.value.id = enableVersion.value
			if(versionList.length > 0){
				versionList.forEach(item=>{
					if(item.id == enableVersion.value){
						enableFlow.value = item
					}
				})
			}
			
		})
		.finally(()=>{
			clickOpenOrClose();
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 13:59:44
@ 功能: 发布新流程
*/
const saveSet = async () => {
	setIsTried(true);
	tipList.value = [];
	reErr(nodeConfig.value);
	if (tipList.value.length != 0) {
		tipVisible.value = true;
		return;
	}
	processConfig.value.flowPermission = flowPermission.value;
	// eslint-disable-next-line no-console
	// console.log("processConfig",processConfig.value);
	// console.log("flowPermission",flowPermission.value);
	// console.log("nodeConfig",nodeConfig.value);
	saveFlowCont(processConfig.value)
		.then((data:any) => {
			if(data.code == 0){
				ElMessage.success("设置成功");
				// emits('judgeFlowIsEdit', false)
				// emits("runNextWindows",3);
				// clearCanvas(1);
			}
		})
		.finally(()=>{
			// emits("chanerequest");
			getFlowVerList()
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:01:22
@ 功能: 错误提示
*/
const reErr = ({ childNode }:any) => {
	if (childNode) {
		let { type, error, nodeName, conditionNodes } = childNode;
		if (type == 1 || type == 2 || type == 3) {
			if (error) {
				tipList.value.push({
					name: nodeName,
					type: ["", "审核人", "抄送人", "执行人"][type],
				});
			}
			reErr(childNode);
		} else if (type == 4) {
			reErr(childNode);
		} else if (type == 5) {
			reErr(childNode);
			for (var i = 0; i < conditionNodes.length; i++) {
				if (conditionNodes[i].error) {
					tipList.value.push({ name: conditionNodes[i].nodeName, type: "条件" });
				}
				reErr(conditionNodes[i]);
			}
		}
	} else {
		childNode = null;
	}
};
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:11:28
@ 功能: 获取流程内容
*/
const gainFlowCont = () =>{
	gainFlowInfo({id:enableVersion.value.toString()})
		.then((data:any)=>{
						// console.log("获取工作流版本列表-1->",data,enableFlow.value)
			if(data.code == 0){
				processConfig.value = data.data;
				processConfig.value.workFlowDef.formKey = appPageKey.value
				nodeConfig.value = data.data.nodeConfig;
				flowPermission.value = data.data.flowPermission;
				directorMaxLeveling = data.data.directorMaxLevel;
				workFlowDef.value = data.data.workFlowDef;
				setTableId(data.data.tableId);
				flowIsTrue.value = true;
				// console.log("max--1->",data)
				// console.log("max--6->",data.data.tableId)
				// console.log("max--2->",data.data.flowPermission)
				// console.log("max--3->",nodeConfig)
				// console.log("max--4->",data.data.directorMaxLevel)
				// console.log("max--5->",processConfig.value)
			}else{
				clearCanvas(1);
			}
			// initWorkFlowData();
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:12:43
@ 功能: 选择工作流版本
*/
const clickFormTable = (val:any) =>{
	console.log("切换表单",val,activeTabs.value)
	enableVersion.value = val
	gainFlowCont();
	clickOpenOrClose();
	// getTableFieldList(versionIndex.value,val)
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:21:06
@ 功能: 编辑当前版本流程
*/
const saveEdit =()=>{
	setIsTried(true);
	tipList.value = [];
	
	reErr(nodeConfig.value);
	if (tipList.value.length != 0) {
		tipVisible.value = true;
		return;
	}
	processConfig.value.flowPermission = flowPermission.value;
	// eslint-disable-next-line no-console
	// console.log("processConfig",flowPermission);
	// console.log("flowPermission",flowPermission.value);
	// console.log("activeTabs",enableFlow.value);
	let sendCont = {
		id:enableVersion.value.toString(),
		flowinfo:processConfig.value
	}
	editFlowCont(sendCont)
		.then((data:any) => {
			if(data.code == 0){
				ElMessage.success("设置成功");
				// emits("update:openDrawer", false);
				// clearCanvas(1);
				// emits('judgeFlowIsEdit', false)
				// emits("runNextWindows",3);
			}
		})
		.finally(()=>{
			// emits("chanerequest");
			getFlowVerList()
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:34:45
@ 功能: 另存为新版
*/
const saveNew = () => {
	setIsTried(true);
	tipList.value = [];
	
	reErr(nodeConfig.value);
	if (tipList.value.length != 0) {
		tipVisible.value = true;
		return;
	}
	processConfig.value.flowPermission = flowPermission.value;
	// eslint-disable-next-line no-console
	// console.log("processConfig",flowPermission);
	// console.log("flowPermission",flowPermission.value);
	// console.log("activeTabs",enableFlow.value);
	let sendCont = {
		id:enableVersion.value.toString(),
		flowinfo:processConfig.value
	}
	saveNewFlow(sendCont)
		.then((data:any) => {
			if(data.code == 0){
				ElMessage.success("设置成功");
				// emits('judgeFlowIsEdit', false)
				// emits("runNextWindows",3);
			}
		})
		.finally(()=>{
			getFlowVerList()
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:35:06
@ 功能: 监听流程节点变动
*/
watch(()=>nodeConfig,()=>{
	// console.log("变动流程")
	if(oneIsTrue){
		oneIsTrue = false;
		// emits('judgeFlowIsEdit', false)
	}else{
		// emits('judgeFlowIsEdit', true)
	}
	
},
{
    deep: true
})
/**
@ 作者: 秦东
@ 时间: 2024-05-21 14:37:22
@ 功能: 关闭表单流程
*/
const closwFormFlow = () => {
	flowIsTrue.value = false;
	// emits('judgeFlowIsEdit', false)
	openOrCloseFormFlow(2)
}
</script>
<template>
	<el-main class="mainBox">
		<div v-if="flowIsTrue" style="height: 100%;">
		
			<div  class="flowVersionBox">
				<div class="tabs_box">
					<el-tabs v-if="isRead" v-model="activeTabs"  @tab-change="clickFormTable">
						<el-tab-pane  v-for="item in versionList" :key="item.id" :name="item.id">
							<template #label>
								<el-icon><Share /></el-icon>
								<span class="my-label">V{{item.version}}</span>
							</template>
						</el-tab-pane>
					</el-tabs>
				</div>
				<div class="flowButBox">
					<el-button v-if="isRead && !openOfClise && closeOrOpenVersion" type="success"  size="small" plain  @click="setupState(1)">
						<el-icon class="el-icon--left"><Delete /></el-icon>
						启用
					</el-button>
					<el-button v-if="isRead && openOfClise && closeOrOpenVersion"  type="warning"  size="small" plain @click="setupState(2)">
						<el-icon class="el-icon--left"><Delete /></el-icon>
						禁用
					</el-button>
					<el-button   size="small" plain  @click="clearCanvas">
						<el-icon class="el-icon--left"><Delete /></el-icon>
						清空
					</el-button>
					<el-button v-if="!isRead"   size="small" plain  @click="saveSet">
						<el-icon class="el-icon--left"><Promotion /></el-icon>
						发布
					</el-button>
					<el-button v-if="isRead"  size="small" plain @click="saveEdit">
						<el-icon class="fa fa-save" style="margin-right:5px"></el-icon>
						保存
					</el-button>
					<el-button v-if="isRead" type="warning"  size="small"  @click="saveNew">
						<el-icon class="el-icon--left"><Share /></el-icon>
						另存为新版
					</el-button>
					<el-button type="danger"  size="small" @click="closwFormFlow">
						<el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
						关闭流程
					</el-button>
				</div>
			</div>
			<div >
				
				<section class="dingflow-design" style="top:80px">		
					<div class="zoom">
						<div class="zoom-out" :class="nowVal == 50 && 'disabled'" @click="zoomSize(1)"></div>
								<span>{{ nowVal }}%</span>
						<div class="zoom-in" :class="nowVal == 300 && 'disabled'" @click="zoomSize(2)"></div>
					</div>
					<div class="box-scale" :style="`transform: scale(${ nowVal / 100});`">
						<nodeWrap v-model:nodeConfig="nodeConfig" v-model:flowPermission="flowPermission" />
						<div class="end-node">
							<div class="end-node-circle"></div>
							<div class="end-node-text">流程结束</div>
						</div>
					</div>
				</section>

				<errorDialog v-model:visible="tipVisible" :list="tipList" />
				<promoterDrawer v-model:form-data="state.formData" :form-key="appPageKey" :form-version="formVersion" />
				<approverDrawer :directormaxlevel="directorMaxLeveling" :node-config="nodeConfig"  :is-form-flow="isFormFlow"  :customer-form-key="appPageKey"  v-model:form-data="state.formData"  :form-version="formVersion" />
				<copyerDrawer />
				<conditionDrawer  :is-form-flow="isFormFlow"  :customer-form-key="appPageKey" />
			</div>
		</div>
		<div v-else class="flow_work_begin">
			<el-result title="" sub-title="">
				<template #icon>
					流程可实现需要多人流转的业务场景。<br>绘制流程图，设定数据流转方式，即可搭建线上工作流。<br><br>
					<el-image
						class="imgBox"
						:src="FlowImgSrc"
					/>
				</template>
				<template #extra>
					<el-button type="primary" @click="createFormFlow">开启流程</el-button>
				</template>
			</el-result>
		</div>
	
	</el-main>
</template>
<style  lang='scss' scoped>
.mainBox{
	padding: 0;
	overflow-y : auto;
	height: calc(100vh - 40px);
	background-color: #f5f5f7;
}
.flow_work_begin{
	height: calc(100vh - 40px);
	display: flex;
	align-items: center;
  	justify-content: center;
	background-color: #FFFFFF;
	.imgBox{
		height: calc(100vh - 400px);
		// height: 10%;
	}
}
.flowVersionBox{
	width: 100%;
	display: flex;
	align-items: center;
  	justify-content: space-between;
	background-color: #FFFFFF;
	.flowVerLeft{
		max-width: 50%;
		padding-left: 10px;
		display: flex;
		align-items: center;
	}
}
.tabs_box{
	max-width: 50%;
	min-width:30%;
	::v-deep .el-tabs__nav-wrap::after {
		position: static !important;
		/* background-color: #fff; */
	}
	::v-deep .el-tabs__item{
		padding:0 10px;
	}
	::v-deep .el-tabs__header{
		margin:0;
	}
}
.flowButBox{
	padding: 7px 0;
}
</style>
