<template>
	<a-modal
		:title='$t("fmeamanager.maturity.dfmea-maturity-assessment-submit-for-approval")'
		:visible='visible'
		:mask-closable='false'
		:confirmLoading='okLoading'
		destroyOnClose
		@cancel='handleCancel'
		@ok='handleOk'
		width='80%'
	>
		<a-tabs default-active-key='1' tab-position='left'>
			<a-tab-pane key='1' :tab="$t('fmeamanager.process-instance')">
				<a-form layout='vertical' :form='form'>
					<!-- 流程信息 -->
					<a-card :title="$t('fmeamanager.process-information')">
						<a-row :gutter='24'>
							<a-col :xl='8' :lg='12' :md='12' :sm='24' :xs='24'>
								<a-form-item :label="$t('fmeamanager.approval-process')">
									<a-select
										:placeholder="$t('fmeamanager.please-select-the-approval-process')"
										@change='handleProcessChange'
										v-decorator="[
											'process',
											{
												rules: [
													{
														required: true,
														message: $t('fmeamanager.please-select-the-approval-process')
													}
												]
											},
										]"
									>
										<a-select-option
											v-for='(process, index) in processList'
											:key='index'
											:value='process.id'
										>
											{{ process.displayName }}
										</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
						</a-row>
					</a-card>
					<br />
					<!-- 审批人 -->
					<a-card v-if='userTaskFlag' :title="$t('fmeamanager.approver')" class='mt10'>
						<a-row
							:gutter='24'
							v-for='userTask in userTaskList'
							:key='userTask.key'
						>
							<a-col :xl='8' :lg='12' :md='12' :sm='24' :xs='24'>
								<a-form-item
									:label='userTask.name'
									:required='userTask.required'
								>
									<a-select
										:placeholder="$t('fmeamanager.please-select-approver')"
										:filter-option='handleFilterOption'
										@change='handleUserChange($event, userTask)'
										@search='handleUserSearch'
										allowClear
										showSearch
										v-decorator="[
											'userName'+ userTask.key,
											{
												rules: [
													{
														required: userTask.required,
														message: $t('fmeamanager.please-select-approver')
													}
												]
											},
										]"
									>
										<a-icon slot='suffixIcon' type='search' />
										<a-select-option
											v-for='(user, uIndex) in userList'
											:key='uIndex'
											:value='user.value'
										>
											{{ user.name }}
										</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<a-col :xl='8' :lg='12' :md='12' :sm='24' :xs='24'>
								<a-form-item :label="'\xa0'">
									<a-button
										v-if='userTask.required'
										type='primary'
										shape='circle'
										icon='plus'
										@click='add(userTask.key)'
									/>
									<a-button
										v-else
										type='dashed'
										shape='circle'
										icon='minus'
										@click='remove(userTask.key)'
									/>
								</a-form-item>
							</a-col>
						</a-row>
					</a-card>
				</a-form>
			</a-tab-pane>
			<a-tab-pane key='2' :tab="$t('fmeamanager.flow-chart')" force-render>
				<SnakerFlowDesigner
					style='height: 65vh'
					ref='designer'
					:viewer='true'
					:value='process'
				/>
			</a-tab-pane>
		</a-tabs>
	</a-modal>
</template>

<script>

import { delCookie, setCookie } from '@/utils/util';
import { snakerXml2LogicFlowJson } from '@/components/SnakerFlowDesigner/src/snakerflow/tool';
import { v4 as uuidv4 } from 'uuid';
import moment from 'moment';

export default {
	name: 'SubmitApprovalModal',
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		title: {
			type: String,
			default: ''
		},
		rfmeaType: {
			type: String,
			default: ''
		}
	},
	components: {},
	data() {
		return {
			/** 输入参数 */
			inputArgs: {},
			/** 流程定义 */
			process: {
				/** XML数据 */
				xml: '',
				/** 流程ID */
				processId: ''
			},
			/** 用户集合 */
			userList: [],
			/** 表单创建 */
			form: this.$form.createForm(this, { name: 'dynamic_rule' }),
			/** 用户任务集合 */
			userTaskList: [],
			/** 按钮【确定】loading */
			okLoading: false,
			/** 流程集合 */
			processList: [],
			/** 用户节点标识，用于创建销毁 */
			userTaskFlag: false,
			/** 延期信息 */
			delay: {
				/** 延期tg名称 */
				tgLabel: '',
				/** 延期tg时间 */
				tgTime: undefined,
				/** 延期至时间 */
				toTgTime: undefined,
				/** 延期原因 */
				reason: undefined
			}
		};
	},
	watch: {
		visible(val) {
			if (val) {
				this.userTaskList = [];
				this.getWfProcessList();
				this.handleUserSearch();
			} else {
				this.handleCancel();
			}
		}
	},
	methods: {
		/**
		 * 处理关闭模态框
		 */
		handleCancel() {
			this.$emit('close');
		},
		/**
		 * 处理确定
		 */
		handleOk() {
			let _that = this;
			// 校验
			let flag = false;
			_that.form.validateFields(err => {
				if (!err) {
					flag = true;
				}
			});
			if (!flag) {
				return;
			}

			/****************************** 参数处理 ******************************************/

				// 处理数组分组，按照groupKey
			let arrayGroup = _that.handleArrayGroup('groupKey', this.userTaskList);
			// 处理提交审批参数，逗号拼接
			let args = _that.handleSaveArgs(arrayGroup);

			/****************************** 参数处理 ******************************************/
			console.log('审批类型:' + _that.inputArgs.approveType);
			_that.okLoading = true;
			// 启动流程定义
			let url = '/DFMEA/approve/start.do';
			_that.$api.post(url, {
				businessId: _that.inputArgs.businessId, /** fmea标识或者失效报告标识 */
				/** 审批类型---
				 * 11=TG1审批,
				 * 12=TG2审批，
				 * 13=tg1延期审批,
				 * 14=tg2延期审批,
				 * 15=FMEA失效报告核实审批,
				 * 20=家族FMEA审批,
				 * 40=主动更新审批,
         * 71=DFMEA成熟度评估审批*/
				approveType: _that.inputArgs.approveType,
				yqDate: _that.delay.toTgTime, /** 延期时间 */
				reason: _that.delay.reason, /** 延期原因 */
				fmeaType: '1', /** fmea类型1=主fmea  2=派生fmea */
				processId: _that.process.processId, /** 流程ID */
				projectSn: _that.inputArgs.projectSn, /** 项目流水号 */
				projectNo: _that.inputArgs.projectNo, /** 项目代号 */
				projectId: _that.inputArgs.projectId, /** 项目信息ID */
				myProjectId: _that.inputArgs.myProjectId, /** 我的项目ID */
        libraryId: _that.inputArgs.libraryId,
				args: JSON.stringify(args), /** 参数 */
			}).then((res) => {
				if (res.flag) {
					_that.$notification.success({ message: res.message });
					// 提交审批后更改按钮权限
					// _that.$api.btnPms = false;
					// 关闭弹出框
					_that.handleCancel();
					// 刷新列表
					_that.$emit('list');
				} else {
					_that.$notification.error({ message: res.message });
				}
			}).finally(() => {
				_that.okLoading = false;
			});
		},
		/**
		 * 获取流程定义列表
		 */
		getWfProcessList() {
			let _that = this;
			_that.$api.getProcessList({
				approveType: _that.inputArgs.approveType /** 流程定义状态 */
			}).then(res => {
				if (res.flag) {
					_that.processList = res.data.data;
				} else {
					_that.$notification.error({ message: res.message });
				}
			});
		},
		/**
		 * 处理审批流程选择
		 */
		handleProcessChange(val) {
			let _that = this;
			_that.process.processId = val;
			_that.$api.getWfXml({
				id: val
			}).then(res => {
				if (res.flag) {
					_that.userTaskList = [];
					_that.userTaskFlag = false;
					_that.process.xml = res.data;
					let tranData = snakerXml2LogicFlowJson(_that.process.xml);
					if (tranData.nodes) {
						let nodes = tranData.nodes;
						for (let i = 0; i < nodes.length; i++) {
							let node = nodes[i];
							// 取到任务节点
							if (node.type === 'snaker:task') {
								let userTask = {
									key: uuidv4(),
									groupKey: uuidv4(),
									name: node.text,
									required: true
								};
								userTask[node.properties.assignee] = node.properties.assignee;
								_that.userTaskList.push(userTask);
							}
						}
					}
				} else {
					_that.$notification.error({ message: res.message });
				}
			}).finally(() => {
				_that.userTaskFlag = true;
			});
		},
		/**
		 * 处理过滤配置
		 * @param input
		 * @param option
		 */
		handleFilterOption(input, option) {
			return (
				option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
			);
		},
		/**
		 * 处理用户选择
		 * @param val 选择用户ID
		 * @param userTask 用户任务节点
		 */
		handleUserChange(val, userTask) {
			let keys = Object.keys(userTask);
			let k = '', v = '';
			keys = keys.filter(key => {
				return key.indexOf('userTask') !== -1;
			});
			k = keys[0];
			if (keys && keys.length > 1) {
				v = keys[1];
			}
			userTask[k] = val;
			if (!v) {
				v = k.replaceAll('userTask', 'userTaskName');
			}
			this.userList.forEach(item => {
				if (item.value === val) {
					userTask[v] = item.name;
				}
			});
			if (!val) {
				this.handleUserSearch(val);
			}
		},
		/**
		 * 处理用户检索
		 * @param val 输入值
		 */
		handleUserSearch(val) {
			let _that = this;
			_that.$api.getUserPageList({
				pageNo: 1,
				pageSize: 10,
				userName: val
			}).then(res => {
				if (res.flag) {
					let resData = res.data.data;
					_that.userList = [];
					_that.userList = resData.map(item => {
						return {
							name: item.userName + '/' + item.account + '/' + item.departmentName,
							value: item.userId
						};
					});
				} else {
					_that.$notification.error({ message: res.message });
				}
			});
		},
		/**
		 * 处理延期至 -- 时间选择变化
		 * @param date
		 * @param dateString
		 */
		handleToTgTime(date, dateString) {
			this.delay.toTgTime = dateString;
		},
		/**
		 * 处理延期原因 -- 输入变化
		 * @param e
		 */
		handleReason(e) {
			this.delay.reason = e.target.value;
		},
		/**
		 * 处理延期至 -- 禁用时间
		 * @param current
		 */
		handleDisabledToTgTime(current) {
			// Can not select days before today and today
			return current && current < moment(this.delay.tgTime).endOf('day');
		},
		/**
		 * 添加
		 * @param key 标识
		 */
		add(key) {
			for (let i = 0; i < this.userTaskList.length; i++) {
				let userTask = this.userTaskList[i];
				if (userTask.key === key) {
					let target = {};
					Object.assign(target, this.userTaskList[i]);
					target['required'] = false;
					target['key'] = uuidv4();
					let keys = Object.keys(target);
					let k = '', v = '';
					keys = keys.filter(key => {
						return key.indexOf('userTask') !== -1;
					});
					if (keys && keys.length === 2) {
						if (keys[1].indexOf('userTaskName') !== -1) {
							v = keys[1];
							k = keys[0];
						} else {
							v = keys[0];
							k = keys[1];
						}
					} else if (keys && keys.length === 1) {
						k = keys[0];
					}
					if (k) {
						target[k] = '';
					}
					if (v) {
						target[v] = '';
					}
					this.userTaskList.splice(i + 1, 0, target);
				}
			}
		},
		/**
		 * 删除
		 * @param key 标识
		 */
		remove(key) {
			this.userTaskList = this.userTaskList.filter(v => {
				return key !== v.key;
			});
		},
		/**
		 * 处理提交审批参数
		 * @param arrayGroup 数组分组
		 */
		handleSaveArgs(arrayGroup) {
			let newArr = [];
			for (let i = 0; i < arrayGroup.length; i++) {
				let arr = arrayGroup[i];
				let newObj = {};
				if (arr && arr.length > 0) {
					Object.assign(newObj, arr[0]);
					let keys = Object.keys(newObj);
					let k = '', v = '';
					keys = keys.filter(key => {
						return key.indexOf('userTask') !== -1;
					});
					if (keys && keys.length === 2) {
						if (keys[1].indexOf('userTaskName') !== -1) {
							v = keys[1];
							k = keys[0];
						} else {
							v = keys[0];
							k = keys[1];
						}
					}
					let kVal = [], vVal = [];
					for (let j = 0; j < arr.length; j++) {
						// 保证值不为空
						if (arr[j][k]) {
							kVal.push(arr[j][k]);
							vVal.push(arr[j][v]);
						}
					}
					if (k) {
						newObj[k] = kVal.toString();
					}
					if (v) {
						newObj[v] = vVal.toString();
					}
				}
				newArr.push(newObj);
			}
			return newArr;
		},
		/**
		 * 处理数组分组
		 * @param key 属性key
		 * @param source 源数组
		 * @return {*[][]}
		 */
		handleArrayGroup(key, source) {
			const map = new Map();
			source.forEach((item, index, arr) => {
				if (!map.has(item[key])) {
					map.set(
						item[key],
						arr.filter(a => a[key] === item[key])
					);
				}
			});
			return Array.from(map).map(item => [...item[1]]);
		}
	}
};

</script>

<style lang='less' scoped>

</style>
