<!--
@ 作者: 秦东
@ 时间: 2023-09-22 15:26:36
@ 备注: 回显表单
-->
<script lang='ts' setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import {  useRouter } from 'vue-router'

import { notAsA_BasisForJudgment,asAnApprovalActionControl,fixedValueControl,timeControl,timeEquation } from '@/utils/workflow/const'

import {
    string2json,
    stringToObj
} from '@/utils/DesignForm/form'
import { nodeFlow,conditionInfo,nodelPeoples } from '@/api/taskapi/types'
import { haveCustomerFormVersion,generateFlow } from '@/api/taskapi/management'
import { judgeSubmitCancel } from '@/api/DesignForm/requestapi'

import '@/assets/scss/element-var.scss'
import '@/assets/scss/index.scss'
import '@/assets/iconfont/iconfont.css'
import 'element-plus/dist/index.css'

import FlowStep from '@/views/taskplatform/taskmanagement/flowStep.vue'

const props = defineProps({
	isopen:{
		type:Boolean,
		default:true
	},
	versionid:{
		type:String,
		default:""
	},
	versiontitle:{
		type:String,
		default:""
	},
	infoid:{
		type:String,
		default:""
	},
	drawerwith:{
		type:Number,
		default:0
	}
})
const submitButton = {
    type: "div",
    control:
    {},
    config:
    {
      textAlign: "center",
      span: ""
    },
    list: [
    {
      type: "button",
      control:
      {
        label: "保存",
        type: "primary",
        key: "submit"
      },
      config:
      {
        textAlign: "center"
      }
    }]
}
const flowOpinion = ref(false);   //审批窗口
const isFlowForm = ref(false)
const loadingData = ref(false)
const formEl = ref()
const router = useRouter()
const state = reactive<any>({
	type: 1, // 1新增；2修改；3查看（表单模式） ；4查看； 5设计
    formData: {
      list: [],
      form: {},
      config: {}
    },
    dict: {},
    formId: props.versionid,
    id: 0,
    loading: true
})

//获取工作流条件
const gainFlowChart = reactive<nodeFlow>({
	id:0
})
const flowFactor = reactive<conditionInfo[]>([])	//表单组件
const nodelUserList = reactive<nodelPeoples[]>([])
//工作流数据
const flowMap = ref<any[]>();
const nextStep = ref<number>(0);
const currentProgress  = ref<number>(1);
const nodeKey = ref<string>('');
const formType = computed(() => {
    // 带有参数id为编辑状态
    if (props.infoid) {
      return 2
    } else {
      return 1
    }
})

const emits = defineEmits(["update:isopen","searchquery"]);
const drawerOpenOrClose =   computed({
	get: () => props.isopen,
	set: (val) => {
		emits("update:isopen", val);
	},
});

//获取表单数据
const getTaskFormData = () =>{
	loadingData.value = true;
	haveCustomerFormVersion({id:props.versionid})
		.then(({ data }) =>{
			console.log("表单数据",data)
			if(data.classify == 2){
				isFlowForm.value = true;
			}else{
				isFlowForm.value = false;
			}
			state.id=props.versionid
			state.formData = stringToObj(data.mastesform)
      		state.dict = string2json(data.dict)
				judgeSubmitCancel({"name":data.mastesformjson})
					.then((data:any) =>{
						if(data.code == 0){
							if (data.data == 3 || data.data == 4){
								state.formData.list.push(submitButton)
							}
						}
					})
			//获取工作流不进图
			gainFlowChart.id=data.flowkeystr
			// generateFlow(gainFlowChart)
			// 	.then((data:any) =>{
			// 		console.log("获取工作流不进图",data.data)
			// 		flowMap.value = data.data.flowList
			// 		console.log("获取工作流不进图--->",flowMap.value)
			// 	})
		})
		.finally(()=>{
			loadingData.value = false;
		})
}

const drawerWith = ref<number>(0);
onMounted(()=>{
	drawerWith.value = window.innerWidth - 220
	
});
window.addEventListener("resize", function(){
	drawerWith.value = window.innerWidth -220
})
const beforeSubmit = (params: any) => {
    params.formId =  props.versionid
    params.id = ""
	// emits("update:isopen", false);
    return params
}
const afterSubmit = (type: string) => {
	if (type === 'success') {
		// router.go(-1)
		console.log("表单提交成功")
		emits("searchquery");
		closeAppSubmit();
	}
}
const closeAppSubmit = () => {
	emits("update:isopen", false);
	initData();
}
const initData = () => {
	state.formData = {
      list: [],
      form: {},
      config: {}
    };
	state.dict = {};
	state.formId = 0;
	state.id = 0;
	state.loading = true;
	let aryLen = flowFactor.length
	if(aryLen > 0) flowFactor.splice(0,aryLen);
}
watch(()=>props.isopen,()=>{
	if(props.isopen){
		getTaskFormData();
	}else{
		initData()
	}
})

const changeKeyVal = (key:any,val:any,type:any,attribute:any) => {
	// console.log("改变表单值--key--->",key)
	// console.log("改变表单值--val--->",val,Array.isArray(val))
	// console.log("改变表单值--type--->",type)
	// console.log("改变表单值--attribute--->",attribute)

	// console.log("改变表单值--type-1-true->",notAsA_BasisForJudgment.indexOf(type))
	// if(notAsA_BasisForJudgment.indexOf(type) != -1){
	// 	console.log("改变表单值--type--true->",notAsA_BasisForJudgment.indexOf(type))
	// }
	let unitsVal = val
	let isUpdateFlowChart = false
	//单选，多选，下拉菜单
	if(notAsA_BasisForJudgment.indexOf(type) === -1){
		let isWrite = true
		flowFactor.forEach((item:any)=>{
			if(item.factorid == key){
				isWrite = false
				isUpdateFlowChart = true
				item.type=3
				if(type == "checkbox"){
					item.isCheckbox = true
					item.answers = val.map(String)
				}else{
					item.isCheckbox = false
					item.oneanswer = val.toString()
				}
			}
		})
		if(isWrite){
			if(type == "checkbox"){
				flowFactor.push({
					factorid:key,
					type:3,
					isCheckbox:true,
					answers:val.map(String)
				})
			}else{
				flowFactor.push({
					factorid:key,
					type:3,
					isCheckbox:false,
					oneanswer:val.toString()
				})
			}
			isUpdateFlowChart = true
		}
		// console.log("改变表单值--flowFactor--->",flowFactor)
		
	}
	// console.log("改变表单值--flowFactor--1->",unitsVal,timeControl,type)
	//时间类空间附加判断条件
	if(timeControl.indexOf(type) > -1 || fixedValueControl.indexOf(type) > -1 || type == "input"){
		// console.log("改变表单值--flowFactor--3->",unitsVal)
		let addNewTime = true		//判断是否新增
		flowFactor.forEach((item:any)=>{
			// console.log("改变表单值--flowFactor--5->",item.type)
			if(item.type == 2){
				addNewTime = false
				// console.log("改变表单值--flowFactor--5====1->",item.type)
				// console.log("改变表单值--flowFactor--5====3->",item.customFields,item.customFields.length)
				if(item.customFields && item.customFields.length > 0){
					// console.log("改变表单值--flowFactor--5====2->",item.customFields)
					let sunNewAdd = true
					item.customFields.forEach((sunItem:any)=>{
						// console.log("改变表单值--flowFactor-4->",sunItem.wordfield , key,sunItem.wordfield == key)
						if(sunItem.wordfield == key){
							sunNewAdd = false
							isUpdateFlowChart = true
							if(timeEquation.indexOf(attribute) === -1){			//非区间性时间
								sunItem.leftval = val.toString()
							}else{ //区间性时间
								if(Array.isArray(val)){
									if(val.length >= 2){
										sunItem.leftval =  val[0].toString()
										sunItem.rightval = val[val.length - 1].toString()
									}
								}
							}
						}
					})
					if(sunNewAdd){
						isUpdateFlowChart = true
						if(timeEquation.indexOf(attribute) === -1){//非区间性时间
							let customFieldInfo = {
								wordfield: key,
								optType: "1",
								leftval: val.toString()
							}
							item.customFields.push(customFieldInfo)
						}else{ //区间性时间
							if(Array.isArray(val)){
								if(val.length >= 2){
									let customFieldInfo = {
										wordfield: key,
										optType: "6",
										leftval: val[0].toString(),
										leftoptType:"3",
										rightoptType:"3",
										rightval:val[val.length - 1].toString()
									}
									item.customFields.push(customFieldInfo)
								}
							}
						}
					}
				}
			}
		})
		
		if(addNewTime){	//新增自定义类数据判断
			isUpdateFlowChart = true
			if(timeEquation.indexOf(attribute) === -1){			//非区间性时间
				let customFieldInfo = {
					wordfield: key,
					optType: "1",
					leftval: val.toString()
				}
				let condInfo = {
					factorid:"customFields",
					type:2,
					isCheckbox:false,
					customFields:[customFieldInfo]
				}
				flowFactor.push(condInfo)
			}else{		//区间性时间
				if(Array.isArray(val)){
					
					if(val.length >= 2){
						let customFieldInfo = {
							wordfield: key,
							optType: "6",
							leftval: val[0].toString(),
							leftoptType:"3",
							rightoptType:"3",
							rightval:val[val.length - 1].toString()
						}
						let condInfo = {
							factorid:"customFields",
							type:2,
							isCheckbox:false,
							customFields:[customFieldInfo]
						}
						flowFactor.push(condInfo)
					}
				}
			}
			
		}
	}
	//操作人
	if(asAnApprovalActionControl.indexOf(type) > -1){
		isUpdateFlowChart = true
		let isWriteUs = true
		nodelUserList.forEach((item:any)=>{
			if(item.factorid == key){
				isWriteUs = false
				item.userList = val
			}
		})
		if(isWriteUs){
			nodelUserList.push({
				factorid:key,
				userList:val
			})
		}
	}

	console.log("改变表单值--flowFactor--->",flowFactor)
	//更新工作流图
	if(isUpdateFlowChart){
		//获取工作流不进图
		gainFlowChart.conditionList=flowFactor
		gainFlowChart.nodelPeople=nodelUserList
		console.log("获取工作流不进图--gainFlowChart--->",gainFlowChart)
		generateFlow(gainFlowChart)
			.then((data:any) =>{
				console.log("获取工作流不进图-new-->",data)
				flowMap.value = data.data.flowList
				nextStep.value = data.data.nextStep;
				currentProgress.value  = data.data.Step;
				nodeKey.value = data.data.nodeKey;
				console.log("获取工作流不进图-1-->",flowMap.value)
			})
	}
}
watch(()=>flowMap,(val:any)=>{
	console.log("工作流在变化-->",flowMap.value)
})
const sendFlowInfo = ref<any>()
</script>
<template>
	<el-drawer  v-model="drawerOpenOrClose" v-loading="loadingData" :title="versiontitle"  :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :size="props.drawerwith" class="drawerClass" >
		<table border="0" v-if="isFlowForm" class="tableFlowBox">
			<tr>
				<td valign="top">
					<div class="drawerFormBox boxLeft">
						<ak-form
							ref="formEl"
							:form-data="state.formData"
							:type="formType"
							:dict="state.dict"
							request-url="getFormContent"
							add-url="saveFormContent"
							edit-url="editFormContent"
							:before-submit="beforeSubmit"
							:after-submit="afterSubmit"
							:close-app-submit="closeAppSubmit"
							:change-key-val="changeKeyVal"
						/>
					</div>
				</td>
				<td valign="top" width="350">
					<div class="drawerFormBox boxRight">
						<div class="flowBox">
							<el-affix  :offset="20">
								<el-text size="large">审批流程</el-text>
							</el-affix>
							<FlowStep v-model:flow-map="flowMap" :next-step="nextStep" :current-progress="currentProgress" :node-key="nodeKey" />
						</div>
						
						<el-affix v-if="flowOpinion" position="bottom" :offset="0">
							<div class="approvalBoard">
								<el-text size="large" class="appBoardTitle">审批意见</el-text>
								<el-row :gutter="20">
									<el-col :span="24">
										<el-input
											v-model="sendFlowInfo"
											:autosize="{ minRows: 2, maxRows: 6 }"
											type="textarea"
											placeholder="请输入审批意见"
										/>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="4"></el-col>
									<el-col :span="8" class="juzhong"><el-button type="primary" style="width:100%">同意</el-button></el-col>
									<el-col :span="8" class="juzhong"><el-button type="danger" style="width:100%">驳回</el-button></el-col>
									<el-col :span="4"></el-col>
								</el-row>
							</div>
						</el-affix>
					</div>
					
				</td>
			</tr>
		</table>
		<!--无流程表单-->
		<div v-else class="drawerBody">
				<ak-form
					ref="formEl"
					:form-data="state.formData"
					:type="formType"
					:dict="state.dict"
					request-url="getFormContent"
					add-url="saveFormContent"
					edit-url="editFormContent"
					:before-submit="beforeSubmit"
					:after-submit="afterSubmit"
					:close-app-submit="closeAppSubmit"
					:change-key-val="changeKeyVal"
				/>
			</div>
  	</el-drawer>

</template>
<style  lang='scss' scoped>
.tableFlowBox{
	width: 100%;
	height: 100%;
	// background-color: #000000;
	.drawerFormBox{
		width: 100%;
		height: 100%;
		// background-color: #ff0000;
	}
}
.boxLeft{
	padding: 0 10px 0 15px;
	overflow: hidden;
	overflow-y: auto;
}
.flowBox{
	padding: 0 5px 0 10px;
}
.boxRight{
	overflow: hidden;
	overflow-y: auto;
	border-left: 1px solid #EEEEEE;
}
.approvalBoard{
	padding: 5px 10px;
	background-color: #FFFFFF;
	border-top: 1px solid #EEEEEE;
	.juzhong{
		padding: 10px 0;
		text-align: center;
	}
	.appBoardTitle{
		padding: 5px 0 10px 0;
		display: block;
	}
}
</style>
<style  lang='scss'>

.drawerClass ::v-deep.el-drawer__header {
        font-size: 22px;
        text-align: center;
        margin-bottom: 0px;
        padding: 0;
        .el-drawer__close-btn{
            background-color: rgb(255, 77, 79);
            color: white;
        }
    }
    ::v-deep .el-drawer__body {
        padding: 0px;
    }
    .details {
        width: 80%;
        margin-right: 0px;
        margin-left: 20%;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    }
.drawerBody{
	padding: 20px;
	
}

</style>
<style>
.demo-tabs > .el-tabs__content {
	padding: 0px 20px 20px 20px;
	overflow: hidden;
	overflow-y: auto;
}
.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
	height: 100%;
	
}
</style>
<style scoped>
.affix-container {
  text-align: center;
  height: 400px;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
}
</style>
