<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>
			<img
				class="reviewIconImg1"
				src="../../../assets/reviewed_ico.png"
				v-if="datas.ruleForm.documentStatus === 'c'"
			/>
			<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"
			:destroy-on-close="datas.isClose"
		>
			<ApplicableScope
				:deptsList="datas.methodDeptsList"
				ref="applicableScopeRef"
				:obj="datas.applicableScopeData"
				:remark="datas.applicableScopeData.remark"
				:checkIds="datas.applicableScopeData.checkIds"
				@handleInput="handleInput"
			/>
			<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,
	BTNS,
	SEARCHDATA,
	RULEFORM,
	ADDTIMELINE,
	EDITTIMELNE,
} from '../constant/index.js';
import {
	detailsDataInit, //详情数据初始化
	dialogCommitData, //弹窗确定操作数据设置
	rigthBtnDataInit, //右侧按钮操作
	commitHttpData, //提交数据
	deleteData, //删除审批方式
	addData, //添加审批方式
} 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 { approvalFlowget } from '@/utils/api.js';
import { msg } from '@/utils/lodash/msg.js';
import { useRoute, useRouter } from 'vue-router';
const datas = reactive({
	ruleForm: JSON.parse(JSON.stringify(RULEFORM)),
	searchData: SEARCHDATA,
	selectedKeys: [],
	isMethod: false, //控制审批方式
	isSetConditions: false, //审批条件
	isApplicableScope: false, //审批适用范围
	loading: false,
	isClose: 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: JSON.parse(JSON.stringify(ADDTIMELINE)),
	detailsIndex: 0,
	applicableScopeData: {
		remark: '',
		checkIds: [],
	},
	setConditionsData: {
		radioValue: '1',
		methodValue: '1',
		checkIds: [],
		deptValue: 0,
	},
});
//获取组织ID
const store = useStore();
const { state, dispatch } = store;
// const orgId = state.user.orgId;
//获取search状态
const { proxy } = getCurrentInstance();
const { $http, $topNavTagRename } = proxy;
import { formatDate } from '@/utils/lodash/formatDate.js';
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 = [
			'单据状态',
			'维护日期',
			'审批流版本号',
			'审批流编号',
			'审批流名称',
			'应用单据',
		];
		const NODISABLEDA = [
			'单据状态',
			'维护日期',
			'审批流版本号',
			'审批流编号',
		];
		datas.status = newVal;
		//等于a要禁止的
		const DISABLED = [
			'单据状态',
			'维护日期',
			'审批流版本号',
			'审批流编号',
			'应用单据',
		];
		let obj = {
			a: NODISABLEDA,
			d: DISABLED,
			c: NODISABLED,
			b: NODISABLED,
		};
		let arrs = obj[newVal];
		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;
		});
		let tLength = datas.timelineList.length;
		if (newVal == 'a' || newVal == 'd') {
			datas.timelineList[tLength - 1].isAdd = true;
		} else {
			datas.timelineList[tLength - 1].isAdd = false;
		}
		//添加按钮隐藏
		//改变标题
		newVal === 'a' || newVal === 'd'
			? $topNavTagRename('新增审批流')
			: $topNavTagRename('编辑审批流');
	},
	{ immediate: true }
);
watch(
	() => state.user.orgId,
	(newVal) => {
		if (newVal) {
			dispatch('examine/deleteAll');
			dispatch('examine/deleteStaffAllList');
			datas.ruleForm = JSON.parse(JSON.stringify(RULEFORM));
			datas.ruleForm.orgId = newVal;
			datas.timelineList = JSON.parse(JSON.stringify(ADDTIMELINE));
			datas.applicableScopeData.remark = '';
			datas.applicableScopeData.checkIds = [];
			datas.isClose = true;
			getDeptCache();
			getMeStaffListCache();
		}
	}
);

watch(
	() => datas.timelineList,
	(newVal) => {
		if (newVal) {
			let length = newVal.length;
			if (
				length === 6 ||
				datas.ruleForm.documentStatus === 'c' ||
				datas.ruleForm.documentStatus === 'b'
			) {
				datas.timelineList.forEach((item) => {
					item.isAdd = false;
				});
			}
			if (
				length < 6 &&
				(datas.ruleForm.documentStatus === 'a' ||
					datas.ruleForm.documentStatus === 'd')
			) {
				datas.timelineList[length - 1].isAdd = true;
			}
			// if(length!==6 || datas.ruleForm.documentStatus)
			// console.log(
			// 	datas.ruleForm.documentStatus,
			// 	'=datas.ruleForm.documentStatus='
			// );
		}
	},
	{
		deep: true,
		immediate: true,
	}
);
const initOrgId = () => {
	datas.ruleForm.orgId = state.user.orgId;
};
initOrgId();
//获取审批流的select
const getStatus = () => {
	const { examineStatus } = state.examine;
	if (examineStatus && JSON.stringify(examineStatus) !== '{}') {
		datas.searchData[2].options = examineStatus.useOrderType;
		datas.radios = examineStatus.approvalWayType;
		//添加禁止条件
		datas.radios.forEach((item) => {
			item.disabled = false;
		});
		datas.method = examineStatus.method;
	}
};
getStatus();
//详情
const getDetails = () => {
	if ($route.query.id && $route.query.detailsId) {
		datas.loading = true;
		$http
			.get(`${approvalFlowget + $route.query.id}`)
			.then(async (res) => {
				if (res.status === 200) {
					if (res.data.orgId != state.user.orgId) {
						return;
					}
					//重置timelineList数据
					datas.timelineList = JSON.parse(
						JSON.stringify(EDITTIMELNE)
					);
					datas.timelineList[1].statuss = [
						{ name: '单据状态 : ', status: '审核中' },
					];
					//应用单据需要转换成字符串才能正确显示
					res.data.date = formatDate(new Date(res.data.date)) || '';
					res.data.useOrderType = res.data.useOrderType + '';

					//==================
					if (localStorage.getItem('deptAll')) {
						let deptAll = JSON.parse(
							localStorage.getItem('deptAll')
						);

						let deptAllObj = {};
						deptAll.forEach((item) => {
							deptAllObj[item.id] = item;
						});

						let detailsItem = res.data.details.filter((item) => {
							return item.id == $route.query.detailsId;
						});
						detailsItem[0].ways.forEach((item) => {
							if (item.type == 3) {
								console.log();
								item.wayApprovers[0].approverId =
									deptAllObj[
										item.wayApprovers[0].deptId
									].managerId;
							}
						});

						res.data.details.forEach((item) => {
							if (
								item.id == $route.query.detailsId &&
								item.type == 3
							) {
								item = detailsItem[0];
							}
						});
					}

					//==================

					datas.ruleForm = await res.data;
					await detailsDataInit(datas, $route.query.detailsId);
					// if (res.data.documentStatus === 'c') {
					// 	let length = datas.timelineList.length - 1;
					// 	datas.timelineList[length].isAdd = false;
					// }
				}
			})
			.finally(() => {
				datas.loading = false;
			});
	}
};
const getDeptCache = () => {
	//setDeptAll

	dispatch('examine/deleteAll');
	$http.post(`SysConfig/GetDeptAll/${state.user.orgId}`).then(async (res) => {
		if (res.status == 200) {
			dispatch('examine/setDeptAll', res.data);

			datas.methodDeptsList[0].children = datas.deptsList = recursion(
				res.data,
				'range'
			);
			datas.waySearchList = datas.wayList = recursion(res.data, 'way');
			//默认选择第一个
			datas.setConditionsData.deptValue = datas.waySearchList[0].id;
		}
	});
};
//根据组织ID获取部门(当前组织下的部门)
const getDept = () => {
	const { deptAll } = state.examine;
	if (Array.isArray(deptAll) && deptAll.length) {
		datas.methodDeptsList[0].children = datas.deptsList = recursion(
			deptAll,
			'range'
		);
		datas.waySearchList = datas.wayList = recursion(deptAll, 'way');
		//默认选择第一个
		datas.setConditionsData.deptValue = datas.waySearchList[0].id;
	} else {
		getDeptCache();
	}
	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();
///SysConfig/GetStaffAllList/53
//根据组织获取组织成员
const getMeStaffListCache = () => {
	dispatch('examine/deleteStaffAllList');
	$http.get(`SysConfig/GetStaffAllList/${state.user.orgId}`).then((res) => {
		if (res.status === 200) {
			dispatch('examine/setStaffAllList', res.data);
			datas.memberSearchList = datas.memberList = res.data.filter(
				(item) => {
					return !item.disable;
				}
			);
		}
	});
};

//根据组织获取组织成员
const getMeStaffList = () => {
	const { staffAllList } = state.examine;
	if (Array.isArray(staffAllList) && staffAllList.length) {
		datas.memberSearchList = datas.memberList = staffAllList.filter(
			(item) => {
				return !item.disable;
			}
		);
	} else {
		getMeStaffListCache();
	}
};
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 handleInput = (val) => {
	if (val.length > 100) {
		return;
	}
	//	applicableScopeData: {remark: '',
	datas.applicableScopeData.remark = val;
};
//弹窗确定
const handleCommit = async (type) => {
	//适用范围
	await dialogCommitData(datas, type, applicableScopeRef, setMethodRef);
};
//添加审批方式
const handleBtnClick = (t) => {
	addData(datas, t);
};
//明细信息右侧btn点击事件
const handleClick = (item) => {
	rigthBtnDataInit(datas, item);
};
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) => {
	deleteData(datas, item, $route.query.id);
};

const handleBtnItemClick = (val) => {
	commitHttpData(datas, val, $http, $router, $route);
};
</script>

<style lang="scss" scoped>
@import '../index.scss';
.reviewIconImg1 {
	width: 52px;
	height: 52px;
	position: absolute;
	z-index: 10;
	top: 54px;
	left: 42.5px;

	transform: rotate(-20deg);
}
</style>
