<template>
	<div class="modal">
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			:width="modalConfig.dialogWidth || '80%'"
			center
			@close="handleExcel(ruleFormRef)"
			:close-on-click-modal="false"
		>
			<template #header>
				<pageTitle :title="dialogTitle"></pageTitle>
			</template>
			<div class="form">
				<el-form
					ref="ruleFormRef"
					:rules="modalConfig.formRules"
					label-suffix=":"
					:model="formData"
					:label-width="modalConfig.labelWidth || '100px'"
					size="large"
				>
					<el-row :gutter="12">
						<template v-for="item in modalConfig.formItems" :key="item.prop">
							<el-col :span="item.span || 8">
								<el-form-item :label="item.label" :prop="item.prop">
									<template v-if="item.type === 'input'">
										<el-input
											:disabled="item.disabled"
											v-model="formData[item.prop]"
											:placeholder="item.placeholder"
										/>
									</template>
									<template v-if="item.type === 'number'">
										<el-input
											v-model="formData[item.prop]"
											type="number"
											:min="0"
											:max="999999999999"
											:disabled="item.disabled"
											:placeholder="item.placeholder"
										/>
									</template>
									<template v-if="item.type === 'select'">
										<el-select
											v-model="formData[item.prop]"
											:placeholder="item.placeholder"
											style="width: 100%"
											:disabled="item.disabled"
										>
											<template v-for="(val, index) in item.options" :key="index">
												<el-option :value="val.value" :label="val.label" />
											</template>
										</el-select>
									</template>
									<template v-if="item.type === 'date-picker'">
										<el-date-picker
											:type="item.dateType || 'daterange'"
											range-separator="-"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
											v-model="formData[item.prop]"
											:disabled="item.disabled"
										/>
									</template>
									<template v-if="item.type === 'date'">
										<el-date-picker
											type="date"
											:placeholder="item.placeholder"
											style="width: 100%"
											v-model="formData[item.prop]"
											:disabled="item.disabled"
										/>
									</template>
									<template v-if="item.type === 'msgRecipient'">
										<el-radio-group v-model="formData[item.prop]">
											<el-radio v-for="vax in bj_msg_recipient" border :label="vax.value">{{
												vax.label
											}}</el-radio>
										</el-radio-group>
									</template>
									<template v-if="item.type === 'contactName'">
										<el-select
											:disabled="item.disabled"
											v-model="formData[item.prop]"
											filterable
											remote
											reserve-keyword
											:placeholder="item.placeholder"
											:remote-method="remoteuserNameMethod"
											:loading="userLoading"
											remote-show-suffix
											style="width: 100%"
										>
											<el-option
												v-for="item in userNameOptions"
												:key="item.value"
												:label="item.label"
												:value="item.value"
											/>
										</el-select>
									</template>
									<template v-if="item.type === 'unitName'">
										<el-tree-select
											v-model="formData[item.prop]"
											:data="unitOptions"
											node-key="id"
											filterable
											check-strictly="true"
											:placeholder="item.placeholder"
											style="width: 100%"
										/>
									</template>
									<template v-if="item.type === 'belongsDept'">
										<el-tree-select
											v-model="formData[item.prop]"
											:data="belongsDeptOptions"
											:render-after-expand="false"
											node-key="id"
											filterable
											:placeholder="item.placeholder"
											style="width: 100%"
										/>
									</template>

									<template v-if="item.type === 'abStatus'">
										<el-radio-group v-model="formData[item.prop]">
											<el-radio v-for="vax in bj_ab_status" border :label="vax.value">{{
												vax.label
											}}</el-radio>
										</el-radio-group>
									</template>
								</el-form-item>
							</el-col>
						</template>
					</el-row>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleExcel(ruleFormRef)">返回</el-button>
					<el-button type="primary" v-show="dialogLook == false" @click="handleConfirmClick(ruleFormRef)"
						>确定</el-button
					>
					<slot name="button"></slot>
				</span>
				<el-col span="24">
					<img class="imgClass" src="@/assets/person-add.png" />
				</el-col>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="modal">
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import useSystemStore from '@/store/main';
import { getDeptTree } from '@/api/address/index';
import { outTypeList } from '@/libs/commonMeth';
const bj_msg_recipient = outTypeList('bj_msg_recipient'); //短信接收人
const bj_ab_status = outTypeList('bj_ab_status'); //短信接收人
import dayjs from 'dayjs';
// 定义props
interface IProps {
	modalConfig: {
		pageName: string;
		addTitle: string;
		editTitle: string;
		detailTitle: string;
		dialogWidth: string;
		labelWidth: string;
		formItems: any[];
		formRules: object;
		pageListParams?: object; //新增一个对象，用来传给特殊的列表接口刷新页面（非必传）
	};
	otherInfo?: any;
}

const props = defineProps<IProps>();

const dialogVisible = ref(false);
const isEdit = ref(false);

const ruleFormRef = ref<FormInstance>();

const systemStore = useSystemStore();

const { pageDetailInfo, pageOperateType } = storeToRefs(systemStore);

interface userNameListItem {
	value: string;
	label: string;
}
const allOptions = ref<userNameListItem[]>([]);
allOptions.value = [
	{ label: '综合办公室-张三', value: 'Alabama' },
	{ label: '科技信息处-李四', value: 'Alaska' },
	{ label: '综合办公室-王五', value: 'Arizona' },
	{ label: '科技信息处-赵六', value: 'California' },
];

const userLoading = ref(false);

const userNameOptions = ref<userNameListItem[]>([]);
const remoteuserNameMethod = (query: string) => {
	if (query) {
		userLoading.value = true;
		setTimeout(() => {
			userLoading.value = false;
			userNameOptions.value = allOptions.value.filter(item => {
				return item.label.toLowerCase().includes(query.toLowerCase());
			});
		}, 200);
	} else {
		userNameOptions.value = allOptions.value;
	}
};

// const hideitem = (str: string) => {
// 	if (isEdit.value == true) {
// 		return true;
// 	}
// 	if (['addName', 'addDept', 'addDate'].includes(str)) {
// 		return false;
// 	} else {
// 		return true;
// 	}
// };
onMounted(async () => {
	getTree();
});
interface Tree {
	id: number;
	label: string;
	children?: Tree[];
}
const unitOptions: any = ref<Tree[]>();
const belongsDeptOptions: any = ref<Tree[]>();
// 过滤节点（搜索功能）
const getTree = () => {
	getDeptTree().then((res: any) => {
		if (res.code == 200) {
			unitOptions.value = res.data;
		} else {
			unitOptions.value = [];
		}
	});
};

// 定义数据绑定
const initialForm: any = {};
for (const item of props.modalConfig.formItems) {
	initialForm[item.prop] = item.initialValue ?? '';
}

let formData = ref(JSON.parse(JSON.stringify(initialForm)));

const dialogTitle = ref();
const dialogLook = ref(false);
const nowStr = dayjs().format('YYYY-MM-DD HH:mm:ss');
// 新建或者编辑
async function setDialogVisible(isNew: boolean = true, check: boolean = false) {
	dialogVisible.value = true;
	ruleFormRef.value?.resetFields();
	await nextTick();
	dialogLook.value = false;
	if (!isNew) {
		watch(pageDetailInfo, newVal => {
			formData.value = pageDetailInfo.value;
		});

		if (check) {
			dialogTitle.value = props.modalConfig.detailTitle;
			dialogLook.value = true;
			systemStore.getDetailType('detail');
		} else {
			dialogTitle.value = props.modalConfig.editTitle;
			systemStore.getDetailType('edit');
		}
	} else {
		props.modalConfig.formItems.map((m: any) => {
			if (m.prop === 'msgRecipient') {
				initialForm[m.prop] = '1';
			}
			if (m.prop === 'abStatus') {
				initialForm[m.prop] = '1';
			}
			if (m.prop === 'addName') {
				initialForm[m.prop] = '张浩楠';
			}
			if (m.prop === 'addDept') {
				initialForm[m.prop] = '交通运输部海事局';
			}
			if (m.prop === 'addDate') {
				initialForm[m.prop] = nowStr;
			}
		});

		formData.value = JSON.parse(JSON.stringify(initialForm));
		await nextTick();
		dialogTitle.value = props.modalConfig.addTitle;
		systemStore.detailPageEval(initialForm);
		systemStore.getDetailType('add');
	}
	isEdit.value = !isNew;
}

watch(
	() => formData.value.unitName,
	(newVal, oldVal) => {
		belongsDeptOptions.value = getChildrenById(unitOptions.value, newVal);
	}
);

/** 深度优先搜索，找到第一个 id 匹配的节点并返回它的 children */
function getChildrenById(treeData: any[], targetId: string): any {
	for (const node of treeData) {
		if (node.id === targetId) {
			return node.children;
		}
		if (node.children) {
			const found = getChildrenById(node.children, targetId);
			if (found) return found;
		}
	}
	return [];
}

// 点击确定
function handleConfirmClick(formEl: FormInstance | undefined) {
	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {
			dialogVisible.value = false;
			let data = { ...formData.value };
			if (props.otherInfo) {
				data = { ...data, ...props.otherInfo };
			}
			if (!isEdit.value) {
				systemStore.newPageDataAction(props.modalConfig.pageName, data, props.modalConfig.pageListParams);
			} else {
				if (pageOperateType.value === 'edit') {
					systemStore.editPageDataAction(props.modalConfig.pageName, data, props.modalConfig.pageListParams);
				}
			}
		} else {
			console.log('error submit!', fields);
		}
	});
}
// 取消
function handleExcel(formEl: FormInstance | undefined) {
	dialogVisible.value = false;
	if (!formEl) return;
	formEl.resetFields();
}

// 获取详情
function onPageDetail(urlId: number | [] | string) {
	systemStore.detailPageDataAction(props.modalConfig.pageName, urlId);
}

defineExpose({
	setDialogVisible,
	onPageDetail,
});
</script>

<style scoped lang="scss">
.form {
	padding: 10px 30px;
}
.imgClass {
	margin-top: 5%;
	width: 100%;
}
</style>
