<template>
	<div class="add_box">
		<Btns
			:btns="BTNS"
			@handleBtnItemClick="handleBtnItemClick"
			type="add"
			:isOperate="datas.isOperate"
		></Btns>
		<!-- 基本信息 -->
		<div class="info_box">
			<div
				class="detailed_box"
				style="
					padding-bottom: 16px;
					border-bottom: 1px solid rgba(235, 238, 247, 1);
				"
			>
				<div class="detailed_line"></div>
				<div class="detailed_title">基本信息</div>
			</div>
			<Search
				:FormData="datas.searchData"
				:ruleForm="datas.ruleForm"
				@remoteMethod="remoteMethod"
				@valueChange="valueChange"
			/>
		</div>
		<div
			class="box"
			v-loading="datas.loading"
			element-loading-text="数据加载中..."
		>
			<!-- 明细信息 -->
			<div class="detailed_box">
				<div class="detailed_line"></div>
				<div class="detailed_title">明细信息</div>
			</div>
			<!-- 新增 -->
			<Timeline
				:timelineList="datas.timelineList"
				@handleClick="handleClick"
				@handleBtnClick="handleBtnClick"
				@handleDelete="handleDelete"
				:status="datas.status"
			/>
		</div>
		<!-- destroy-on-close -->
		<!-- 审批流适用范围弹窗 -->
		<el-dialog
			v-model="datas.isApplicableScope"
			:title="datas.title"
			:width="datas.width"
		>
			<ApplicableScope
				:deptsList="datas.methodDeptsList"
				ref="applicableScopeRef"
				:obj="datas.applicableScopeData"
				:remark="datas.applicableScopeData.remark"
				:checkIds="datas.applicableScopeData.checkIds"
			/>
			<template #footer>
				<span class="dialog-footer-btns">
					<el-button @click="handleClose('isApplicableScope')"
						>取消</el-button
					>
					<el-button
						type="primary"
						@click="handleCommit('isApplicableScope')"
					>
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 设置审批条件 -->
		<el-dialog
			v-model="datas.isSetConditions"
			:title="datas.title"
			:width="datas.width"
		>
			<SetConditions ref="setConditionsRef" />
			<template #footer>
				<span class="dialog-footer-btns">
					<el-button @click="handleClose('isSetConditions')"
						>取消</el-button
					>
					<el-button
						type="primary"
						@click="handleCommit('isSetConditions')"
					>
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog
			v-model="datas.isMethod"
			:title="datas.title"
			:width="datas.width"
		>
			<!-- 审批流方式 -->
			<Method
				:cities="datas.cities"
				:deptsList="datas.waySearchList"
				:memberList="datas.memberSearchList"
				:radios="datas.radios"
				:method="datas.method"
				@handleSearchClick="handleSearchClick"
				:radioValue="datas.setConditionsData.radioValue"
				:methodValue="datas.setConditionsData.methodValue"
				:checkIds="datas.setConditionsData.checkIds"
				:deptValue="datas.setConditionsData.deptValue"
				@handleLeftRadio="handleLeftRadio"
				@handleRadioChange="handleRadioChange"
				@handleDeptChange="handleDeptChange"
				ref="setMethodRef"
			/>
			<template #footer>
				<span class="dialog-footer-btns">
					<el-button @click="handleClose('isMethod')">取消</el-button>
					<el-button type="primary" @click="handleCommit('isMethod')">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import Btns from '@/components/Btns';
import { useStore } from 'vuex';
import {
	SHOWS,
	TITLES,
	WIDTHS,
	BTNS,
	SEARCHDATA,
	RULEFORM,
	ADDTIMELINE,
	EDITTIMELNE,
	EDITTIMELINEITEM,
	RULEFORMINIT,
	ADDTIMELINEITEM,
	WAYSITEM,
} from '../constant/index.js';
import { detailsDataInit } from '../utils/index.js';
import Search from '../components/Search/index.vue';
import { reactive, getCurrentInstance, ref, watch } from 'vue';
import Method from './Method/index.vue';
import ApplicableScope from './ApplicableScope/index.vue';
import SetConditions from './SetConditions/index.vue';
import Timeline from '../components/Timeline/index.vue';
import { formatDate } from '@/utils/lodash/formatDate.js';
import { ElMessageBox } from 'element-plus';
import {
	approvalFlowSave,
	approvalFlowSubmit,
	approvalFlowget,
	approvalFlowCheck,
	approvalFlowRecheck,
} from '@/utils/api.js';
import { msg } from '@/utils/lodash/msg.js';
import { useRoute, useRouter } from 'vue-router';
const datas = reactive({
	ruleForm: RULEFORM,
	searchData: SEARCHDATA,
	selectedKeys: [],
	isMethod: false, //控制审批方式
	isSetConditions: false, //审批条件
	isApplicableScope: false, //审批适用范围
	loading: false,
	remack: '', //备注说明
	title: '', //用于控制弹窗的标题
	width: '', //用于控制弹窗的宽度

	showDialogContent: SHOWS,
	sort: 0, //审批方式的添加顺序
	status: 'a', //审批流状态
	timelineItemIndex: null, //记录当前审批方式的
	method: [],
	cities: [],
	arr: [], //用于存储其他部门
	deptsList: [], //部门集合 depts 用于审批范围
	methodDeptsList: [
		{
			label: '全选',
			id: 0,
			children: [],
		},
	],
	memberList: [], //组织成员集合
	memberSearchList: [], //组织成员search集合
	radios: [], //审批方式
	wayList: [], //部门集合 用于审批方式
	waySearchList: [], //部门集合 用于搜索
	isOperate: false,
	dids: [], //审批方式禁止
	//新增
	timelineList: ADDTIMELINE,
	detailsIndex: 0,
	applicableScopeData: {
		remark: '',
		checkIds: [],
	},
	setConditionsData: {
		radioValue: '1',
		methodValue: '1',
		checkIds: [],
		deptValue: 0,
	},
});
//选择审批方式禁止条件
const DISNUM = [2, 3, 4];
//审批方式
const METHODS = ['', '会签', '或签'];
//获取组织ID
const store = useStore();
const { state } = store;
const orgId = state.user.orgId;
//获取search状态
const { proxy } = getCurrentInstance();
const { $http, $topNavTagRename } = proxy;

const $route = useRoute();
const $router = useRouter();
const applicableScopeRef = ref(null);
const setMethodRef = ref(null);
const setConditionsRef = ref(null);
//设置表单禁用
watch(
	() => datas.ruleForm.documentStatus,
	(newVal) => {
		const NODISABLED = [
			'单据状态',
			'维护日期',
			'审批流版本号',
			'审批流编号',
			'审批流名称',
			'应用单据',
		];
		datas.status = newVal;
		//等于a要禁止的
		const DISABLED = ['单据状态', '维护日期', '审批流版本号', '审批流编号'];
		let arrs = newVal === 'a' || newVal === 'd' ? DISABLED : NODISABLED;
		let length = datas.searchData.length;
		for (let i = 0; i < length; i++) {
			datas.searchData[i].disabled = arrs.includes(
				datas.searchData[i].label
			);
		}
		//禁止
		datas.timelineList.forEach((item) => {
			item.isDis = newVal == 'a' || newVal == 'd' ? false : true;
		});
		//改变标题
		newVal === 'a' || newVal === 'd'
			? $topNavTagRename('新增审批流')
			: $topNavTagRename('编辑审批流');
	},
	{ immediate: true }
);

//维护日期初始化
// datas.ruleForm.date = formatDate(new Date());
//对象转数组
const initSelectArray = (data) => {
	let arr = [];
	if (!data || JSON.stringify(data) === '{}') {
		console.error('initSelectArray方法接受一个对象并转为数组');
		return [];
	}
	for (let key in data) {
		let obj = {};
		obj.value = key;
		obj.label = data[key];
		arr.push(obj);
	}
	return arr;
};
//获取枚举类型
const getStatus = () => {
	$http.get('ApprovalFlow/status').then((res) => {
		if (res.status === 200) {
			datas.searchData[2].options = initSelectArray(
				res.data.useOrderType
			);
			datas.radios = initSelectArray(res.data.approvalWayType);
			//添加禁止条件
			datas.radios.forEach((item) => {
				item.disabled = false;
			});
			datas.method = initSelectArray(res.data.method);
		}
	});
};
getStatus();

//详情
const getDetails = () => {
	if ($route.query.id) {
		datas.loading = true;
		$http
			.get(`${approvalFlowget + $route.query.id}`)
			.then((res) => {
				if (res.status === 200) {
					//重置timelineList数据
					datas.timelineList = JSON.parse(
						JSON.stringify(EDITTIMELNE)
					);
					datas.timelineList[1].statuss = [
						{ name: '单据状态 : ', status: '审核中' },
					];
					//应用单据需要转换成字符串才能正确显示
					res.data.useOrderType = res.data.useOrderType + '';
					datas.ruleForm = res.data;
					detailsDataInit(datas);
				}
			})
			.finally(() => {
				datas.loading = false;
			});
	}
};

//根据组织ID获取部门(当前组织下的部门)
const getDept = () => {
	$http.post(`SysConfig/GetDeptAll/${orgId}`).then(async (res) => {
		if (res.status == 200) {
			datas.methodDeptsList[0].children = datas.deptsList =
				await recursion(res.data, 'range');

			datas.waySearchList = datas.wayList = await recursion(
				res.data,
				'way'
			);
			getDetails();
		}
	});
};
//递归函数
const recursion = (data, type) => {
	if (!data) {
		return;
	}
	for (let i = 0; i < data.length; i++) {
		data[i].label = data[i].name;
		if (type === 'way') {
			datas.arr.push(data[i]);
		}
		if (Array.isArray(data[i].children) && data[i].children.length) {
			recursion(data[i].children, type);
		}
	}
	let lists = type === 'way' ? datas.arr : data;
	return lists;
};
getDept();
//根据组织获取组织成员
const getMeStaffList = () => {
	$http.get(`SysConfig/GetStaffList/${orgId}`).then((res) => {
		if (res.status === 200) {
			datas.memberSearchList = datas.memberList = res.data.filter(
				(item) => {
					return !item.disable;
				}
			);
		}
	});
};
getMeStaffList();

//审批流名称只允许输入汉字,数字,字母!
const valueChange = (item) => {
	let reg = new RegExp('^[A-Za-z0-9\u4e00-\u9fa5]+$');
	if (!reg.test(datas.ruleForm.name)) {
		datas.ruleForm.name = '';
		return msg('warning', '审批流名称只允许输入汉字|数字|字母!');
	}
};
//取消=
const handleClose = (type) => {
	datas[type] = false;
};
//审批方式搜索条件,后端不好写前端做
const handleSearchClick = (val, type) => {
	if (type == 2 && val) {
		datas.memberSearchList = datas.memberList.filter((item) => {
			return item.name.indexOf(val) > -1;
		});
	} else {
		datas.memberSearchList = datas.memberList;
	}
	if (type == 3 && val) {
		datas.waySearchList = datas.wayList.filter((item) => {
			return item.label.indexOf(val) > -1;
		});
	} else {
		datas.waySearchList = datas.wayList;
	}
};

//弹窗确定
const handleCommit = (type) => {
	//适用范围
	if (datas.isApplicableScope) {
		//获取适用范围数据
		let data = applicableScopeRef.value.getData();

		datas.radios.forEach((item) => {});
		let names = [];
		data.selectedKeys.forEach((item) => {
			names.push(item.name);
		});

		datas.timelineList[0].content = names;
		datas.ruleForm.details[datas.detailsIndex].remark = data.remark;
		//重组数据
		let rangesInitArray = [];
		let length = data.ids.length || 0;
		for (let i = 0; i < length; i++) {
			let rangesItem = { id: 0, detailsId: 0, deptId: data.ids[i] };
			rangesInitArray.push(rangesItem);
		}
		datas.ruleForm.details[datas.detailsIndex].ranges = rangesInitArray;
		//回填
	}
	if (datas.isSetConditions) {
		datas.timelineList[1].statuss = [
			{ name: '单据状态 : ', status: '审核中' },
		];
		datas.timelineList[1].text = '';
	}
	//审批方式
	if (datas.isMethod) {
		let data = setMethodRef.value.getData();
		let timeIndex = datas.timelineItemIndex;
		let waysIndex = timeIndex - 2;
		//选中的审批方式type
		// datas.dids.push(data.radioValue);
		//设置Title和禁止其他的审批方式
		datas.radios.forEach((item) => {
			if (item.value == data.radioValue) {
				datas.timelineList[timeIndex].title = item.label;
			}
		});
		//审批类型;
		datas.ruleForm.details[datas.detailsIndex].ways[waysIndex].type =
			Number(data.radioValue);
		//审批方式;
		datas.ruleForm.details[datas.detailsIndex].ways[waysIndex].method =
			Number(data.methodValue);

		// //指定成员审批
		if (data.radioValue == '2') {
			let length = data.memberData.length || 0;
			datas.ruleForm.details[datas.detailsIndex].ways[
				waysIndex
			].wayApprovers = [];
			if (!length) {
				msg('warning', '请选择成员!');
				return;
			}
			for (let i = 0; i < length; i++) {
				let obj = {
					id: 0,
					wayId: 0,
					deptId: data.memberData[i].deptId,
					approverId: data.memberData[i].id,
				};

				datas.ruleForm.details[datas.detailsIndex].ways[
					waysIndex
				].wayApprovers.push(obj);
			}
			let names = [];
			data.memberData.forEach((item) => {
				names.push(item.name);
			});
			datas.timelineList[timeIndex].method.name = names.join(',');
		}
		// //指定其他部门负责人审批
		if (data.radioValue == '3') {
			let radioData;
			datas.wayList.forEach((item) => {
				if (item.id === datas.setConditionsData.deptValue) {
					radioData = item;
				}
			});
			//!data.radioData.managerId
			if (!radioData.managerId) {
				msg('warning', '请重新选择部门负责人!');
				return false;
			}
			datas.timelineList[timeIndex].method.name = radioData.label;
			let obj = {
				id: 0,
				wayId: 0,
				deptId: radioData.id || 0,
				approverId: radioData.managerId || 0,
			};
			datas.ruleForm.details[datas.detailsIndex].ways[
				waysIndex
			].wayApprovers.push(obj);
		}
		//禁止非选择的审批方式，只能修改选择了的
		if (DISNUM.includes(timeIndex)) {
			//改变审批方式左边的文字
			let index = Number(data.radioValue) - 1;
			let label = datas.radios[index].label;
			//设置审批人
			if (label === '部门负责人审批') {
				datas.timelineList[timeIndex].method.name = label;
			}
			// if (label == '指定成员审批') {
			// 	let names = [];
			// 	data.memberData.forEach((item) => {
			// 		names.push(item.name);
			// 	});
			// 	datas.timelineList[timeIndex].method.name = names.join(',');
			// }
			// if (label === '其它部门负责人审批') {
			// 	datas.timelineList[timeIndex].method.name =
			// 		data.radioData.label;
			// }
			//设置审批方式
			datas.timelineList[timeIndex].method.status =
				METHODS[data.methodValue];
		}
	}
	//关闭窗口
	datas[type] = false;
};
//添加审批方式
const handleBtnClick = (t) => {
	let item =
		datas.ruleForm.documentStatus === 'a'
			? JSON.parse(JSON.stringify(ADDTIMELINEITEM))
			: JSON.parse(JSON.stringify(EDITTIMELINEITEM));
	let waysItem = JSON.parse(JSON.stringify(WAYSITEM));
	//隐藏上一个添加审批方式按钮
	datas.timelineList.forEach((item) => {
		item.isNewAdd = false;
	});
	let length = datas.timelineList.length;
	item.id = length - 1;
	//显示下一个添加审批方式按钮
	datas.timelineList.splice(item.id, 0, item);

	//审批方式最多为3个,到达3个则不再显示添加审批方式按钮
	if (datas.timelineList.length > 5) {
		datas.timelineList.forEach((item) => {
			item.isNewAdd = false;
			item.isAdd = false;
		});
	}
	datas.ruleForm.details[datas.detailsIndex].ways.push(waysItem);
};
//明细信息右侧btn点击事件
const handleClick = (item) => {
	if (
		datas.ruleForm.documentStatus !== 'a' &&
		datas.ruleForm.documentStatus !== 'd'
	) {
		return;
	}
	datas.timelineItemIndex = item.id;
	datas.title = TITLES[item.tag];
	datas.width = WIDTHS[item.tag];
	for (let key in datas.showDialogContent) {
		datas[key] = false;
		datas[item.tag] = true;
	}
	//禁止
	if (item.id > 1) {
		let wayItem =
			datas.ruleForm.details[datas.detailsIndex].ways[item.id - 2];
		let type = wayItem.type || 0;
		//审批方式
		let methodValue = wayItem.method || '1';
		let wayItemLength = wayItem.wayApprovers.length;
		if (wayItemLength) {
			datas.setConditionsData.deptValue = wayItem.wayApprovers[0].deptId;
			datas.setConditionsData.checkIds = wayItem.wayApprovers;
		}

		if (type) {
			datas.setConditionsData.methodValue = methodValue + '';
			datas.setConditionsData.radioValue = type + '';
			datas.radios.forEach((item) => {
				item.disabled = true;
				if (item.value == type) {
					item.disabled = false;
				}
			});
		} else {
			let types = [];
			datas.setConditionsData.methodValue = '1';
			datas.ruleForm.details[datas.detailsIndex].ways.forEach((item) => {
				if (item.type) {
					types.push(item.type + '');
				}
			});
			datas.radios.forEach((item) => {
				item.disabled = false;
				if (types.includes(item.value)) {
					item.disabled = types.includes(item.value);
				}
			});
			const radioValueArr = ['1', '2', '3'];
			for (let i = 0; i < radioValueArr.length; i++) {
				if (!types.includes(radioValueArr[i] + '')) {
					datas.setConditionsData.radioValue = radioValueArr[i] + '';
					return;
				}
			}
		}
	}

	if (item.title === '审批适用范围') {
		//回填
		datas.applicableScopeData.remark =
			datas.ruleForm.details[datas.detailsIndex].remark;
		datas.ruleForm.details[datas.detailsIndex].ranges.forEach((item) => {
			datas.applicableScopeData.checkIds.push(item.deptId);
		});
	}
};
const handleLeftRadio = (val) => {
	datas.setConditionsData.radioValue = val;
	datas.setConditionsData.methodValue = '1';
};
const handleRadioChange = (val) => {
	datas.setConditionsData.methodValue = val;
};
const handleDeptChange = (val) => {
	datas.setConditionsData.deptValue = val.id;
};
//删除审批方式
const handleDelete = (item) => {
	if (
		datas.ruleForm.documentStatus === 'c' ||
		datas.ruleForm.documentStatus == 'b'
	) {
		msg('warning', '只能删除创建中的审批流!');
		return;
	}
	ElMessageBox.confirm('确定要删除该审批方式吗？', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		let length = datas.timelineList.length;
		if (length === 4) {
			msg('warning', '请至少保留一个审批方式!');
			return;
		}
		datas.timelineList.splice(item.id, 1);
		let waysIndex = item.id - 2;
		datas.ruleForm.details[datas.detailsIndex].ways.splice(waysIndex, 1);
		let targetLength = datas.timelineList.length;
		targetLength < length
			? msg('success', '删除成功')
			: msg('success', '删除失败');
		//重置id
		for (let i = 0; i < targetLength; i++) {
			if (datas.timelineList[i].title !== '结束') {
				datas.timelineList[i].id = i;
			} else {
				datas.timelineList[i].isAdd = true;
			}
		}
	});
};

const handleBtnItemClick = (val) => {
	datas.isOperate = true;
	setTimeout(() => {
		datas.isOperate = false;
	}, 1000);
	let type = val.type;
	let ids = [];
	if ($route.query.id) {
		ids.push(Number($route.query.id));
	} else {
		ids.push(datas.ruleForm.id);
	}
	if (type === 'add') {
		$router.push({
			path: '/examine/mange/examineAdd',
			query: { type: 'add', id: '', sjtag: Math.random() * 36 },
		});
	}
	if (type === 'submit' || type === 'save') {
		if (
			datas.ruleForm.documentStatus === 'c' ||
			datas.ruleForm.documentStatus === 'b'
		) {
			msg('error', '只能保存|提交创建中的审批流！');
			return false;
		}

		//过滤没有选择的审批方式,因为审批方式里的数据是写死的,所以过滤一下不想去动态添加了
		datas.ruleForm.details[datas.detailsIndex].ways =
			datas.ruleForm.details[datas.detailsIndex].ways.filter((item) => {
				return item.type && item.method;
			});
		datas.ruleForm.details[datas.detailsIndex].ways.forEach(
			(item, index) => {
				item.sort = index + 1;
				item.id = 0;
				item.detailsId = 0;
			}
		);
		datas.ruleForm.details[datas.detailsIndex].ranges.forEach((item) => {
			item.id = 0;
			item.detailsId = 0;
		});
		const URLS = {
			submit: approvalFlowSubmit,
			save: approvalFlowSave,
		};
		let MSGS = {
			submit: '提交成功!',
			save: '保存成功!',
		};
		if (!datas.ruleForm.useOrderType) {
			msg('error', '请填写审批流名称');
			return;
		}
		if (!datas.ruleForm.useOrderType) {
			msg('error', '请填写应用单据');
			return;
		}

		if (!datas.ruleForm.details[datas.detailsIndex].ranges[0].deptId) {
			msg('error', '请选择审批适用范围');
			return;
		}
		datas.loading = true;
		$http
			.post(URLS[type], datas.ruleForm)
			.then((res) => {
				if (res.status === 200) {
					msg('success', MSGS[type]);
					res.data.useOrderType = res.data.useOrderType + '';
					let Dlength = res.data.details.length - 1;
					datas.detailsIndex = Dlength;
					datas.ruleForm = res.data;

					datas.ruleForm.versionStr =
						datas.ruleForm.details[Dlength].versionStr;
					datas.ruleForm.CurrentVersionDetailsId =
						datas.ruleForm.details[Dlength].id;
				}
			})
			.finally(() => {
				datas.loading = false;
			});
	}
	if (type === 'audit') {
		if (datas.ruleForm.documentStatus !== 'b') {
			msg('error', '只能审核状态为“审核中”的订单！');
			return false;
		}
		datas.loading = true;
		$http
			.post(approvalFlowCheck, { ids })
			.then((res) => {
				if (res.status === 200) {
					if (res.data[0].isSuccess) {
						datas.ruleForm.documentStatus = 'c';
						msg('success', '审核成功');
					} else {
						msg('success', '审核失败');
					}
				}
			})
			.finally(() => {
				datas.loading = false;
			});
	}
	if (type === 'noAudit') {
		if (datas.ruleForm.documentStatus !== 'c') {
			msg('error', '只能反审核状态为“已审核”的订单！');
			return false;
		}
		datas.loading = true;
		$http
			.post(approvalFlowRecheck, { ids })
			.then((res) => {
				if (res.status === 200) {
					if (res.data[0].isSuccess) {
						datas.ruleForm.documentStatus = 'd';
						msg('success', '反审核成功');
					} else {
						msg('success', '反审核失败');
					}
				}
			})
			.finally(() => {
				datas.loading = false;
			});
	}
};
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>
