<!--
@ 作者: 秦东
@ 时间: 2024-03-11 14:46:00
@ 备注: 工作流
-->
<script lang='ts' setup>
import '@/styles/workflowcss/workflow.scss'

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({
	formKey:{
		type:String,
		default:""
	},
	state:{
		type:Object,
		default(){
			return {}
		}
	}
});

const emits = defineEmits<{
    (e: 'update:state', val: formStruct): void
	(e: 'judgeFormIsEdit', 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 formKeyVal =  computed({
	get() {
		return props.formKey
	},
	set(val: formStruct) {
		emits('update:formKey', val)
	}
});
let { setTableId, setIsTried } = useStore()
const flowIsTrue = ref(false)
const isRead = ref(false)      //判断操作功能按钮
const openOfClise = ref(false)  //当前版本状态
const versionList = reactive<flowversion[]>([]); //工作流版本列表
const enableVersion = ref<string>("1");    //流程版本
const enableFlow = ref<any>();
const activeTabs = ref<string>("");			//当前工作流版本
const isFormFlow = ref(true);		//兼容
const closeOrOpenVersion = ref(false);  //判断是否显示版本启用与关闭

let nowVal = ref(100);	//缩放比例
let nodeConfig = ref<any>({}); 	//节点配置
let flowPermission = ref([]); //工作流权限
let processConfig = ref<any>({});	//工作流信息
let directorMaxLeveling = ref<number>(0);	//主管深度（层级）
let workFlowDef = ref({});			//流程名称
let tipList = ref<any>([]);		//信息提示

/**
@ 作者: 秦东
@ 时间: 2024-03-11 16:33:49
@ 功能: 开启流程
*/
const createFormFlow = () =>{
	if(formKeyVal.value == ""){
		flowIsTrue.value = false;
		ElMessageBox.alert('您还未设置表单！请先设置完表单后，在创建流程！','温馨提示！',{
			confirmButtonText: '确定',
			callback: (action: Action) => {
				emits("runNextWindows",1);
			},
		})
	}else{
		openOrCloseFormFlow(1)
		getFlowVerList()
		flowIsTrue.value = true
	}
	// flowIsTrue.value = true
}
const openOrCloseFormFlow = (val:number) => {
	openFormFlow({id:formKeyVal.value.toString(),status:val})
}
//初始化工作流数据
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 = formKeyVal.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)
}
//缩放画布
const zoomSize = (type:number) => {
	if (type == 1) {
		if (nowVal.value == 50) {
		return;
		}
		nowVal.value -= 10;
	} else {
		if (nowVal.value == 300) {
		return;
		}
		nowVal.value += 10;
	}
};

//获取工作流版本列表
const getFlowVerList = ()=>{
	gainFlowVersionList({id:formKeyVal.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();
			
		})
}
//判断当前工作流版本是否启用
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)
}
//获取流程内容
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 = formKeyVal.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();
		})
}
//清空画布
const clearCanvas = (isOk?:any) =>{
	if(isOk==1){
		initWorkFlowData()
		setIsTried(false);
		tipList.value = []
	}else{
		ElMessageBox.confirm('确定要清空画布?')
		.then(() => {
			initWorkFlowData()
			setIsTried(false);
			tipList.value = []
		})
	}
	
	enableFlow.value = ""
}
//错误提示
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;
	}
};
//选择工作流版本
const clickFormTable = (val:any) =>{
	console.log("切换表单",val,activeTabs.value)
	enableVersion.value = val
	gainFlowCont();
	clickOpenOrClose();
	// getTableFieldList(versionIndex.value,val)
}
//流程版本启用禁用
const setupState = (val:number) =>{
	let sendCont = {
		id:enableVersion.value.toString(),
		status:val
	}
	if(val == 1){
		activeTabs.value = enableVersion.value
	}
	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();
		})
	// console.log("enableFlow.version==activeTabs",enableFlow.version,activeTabs)
}
//发布新流程
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("runNextWindows",3);
				// clearCanvas(1);
			}
		})
		.finally(()=>{
			// emits("chanerequest");
			getFlowVerList()
		})
	// let res = await setWorkFlowData(processConfig.value);
	// if (res.code == 200) {
	// 	ElMessage.success("设置成功")
	// 	setTimeout(function () {
	// 		window.location.href = "";
	// 	}, 200);
	// }
	
};
//编辑当前版本流程
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("runNextWindows",3);
			}
		})
		.finally(()=>{
			// emits("chanerequest");
			getFlowVerList()
		})
}
//另存为新版
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("runNextWindows",3);
			}
		})
		.finally(()=>{
			getFlowVerList()
		})
}
/**
@ 作者: 秦东
@ 时间: 2024-03-12 15:49:35
@ 功能: 关闭表单流程
*/
const closwFormFlow = () => {
	flowIsTrue.value = false;
	openOrCloseFormFlow(2)
}
onMounted(()=>{
	if(formKeyVal.value == ""){
		flowIsTrue.value = false;
	}else{
		judgeFormFlowIsOpen({id:formKeyVal.value.toString()})
			.then((data)=>{
				console.log("判断是否已经存在工作流以及是否开启",data)
				if(data.data.isOpen == 1){
					flowIsTrue.value = true;
					getFlowVerList()
				}else{
					flowIsTrue.value = false;
				}
			})
	}
})
</script>
<template>
	<div class="design_flow_work">
		<el-row v-if="flowIsTrue" style="height: 100%;">
			<el-col :span="24">
				<table class="table_box">
					<tr>
						<td class="table_td_title"><el-text v-if="isRead">版本：</el-text></td>
						<td class="table_td_info">
							<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="but_box">
								<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>
						</td>
					</tr>
				</table>
			</el-col>
			<el-col :span="24">
			
				
				<section class="dingflow-design" style="top:40px">		
					<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" />
				<approverDrawer :directormaxlevel="directorMaxLeveling" :node-config="nodeConfig"  :is-form-flow="isFormFlow"  :customer-form-key="formKeyVal" />
				<copyerDrawer />
				<conditionDrawer  :is-form-flow="isFormFlow"  :customer-form-key="formKeyVal" />
			</el-col>
		</el-row>
		<div v-else class="flow_work_begin">
			<el-result title="" sub-title="">
				<template #icon>{{formKeyVal}}<br>{{state}} <br>
					流程可实现需要多人流转的业务场景。<br>绘制流程图，设定数据流转方式，即可搭建线上工作流。<br><br>
					<el-image
						:src="FlowImgSrc"
					/>
				</template>
				<template #extra>
					<el-button type="primary" @click="createFormFlow">开启流程</el-button>
				</template>
			</el-result>
		</div>
		
	</div>
</template>
<style  lang='scss' scoped>
.design_flow_work{
	height: calc(100vh - 40px);
    width: inherit;
	overflow: hidden;
	overflow-y: auto;
}
.flow_work_begin{
	height: calc(100vh - 40px);
	display: flex;
	align-items: center;
  	justify-content: center;
}
/* 去掉tabs标签栏下的下划线 */
::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
  /* background-color: #fff; */
}
::v-deep .el-tabs__item{
	padding:0 10px;
}
.version_but{
	display: flex;
	align-items: center;
  	justify-content: space-between;
}
.tabs_box{
	max-width: 60%;
	min-width:30%
}
.but_box{
	max-width: 50%;
	min-width: 40%;
	overflow: hidden;
	overflow-x: auto;
	padding:5px 10px 5px 0;
	text-align: right;
}

.table_box{
	width: 100%;
}
.table_td_title{
	width: 60px;
	text-align: right;
	align-items: center;
	vertical-align: middle;
}
.table_td_info{
	display: flex;
	// width: calc(100% - 100px);
	align-items: center;
  	justify-content: space-between;
}
</style>
<style>
.canvas_body{
	height: 100%;
    width: inherit;
}
.flow_version{
	
}
.flow_version > .el-tabs__content{
    padding: 0px;
	height:0px;
}
.flow_version > .el-tabs__header{
	margin:0px;
}
.flow_version .custom-tabs-label span {
  padding:0 10px;
}

.right_kongx{
	margin-right:50px
	
}
</style>
