<template>
	<div>
		<!-- <el-affix :offset="20" style="width:100%;" v-loading="loading"> -->
			<el-card shadow="never">
				<div class="head-container">
					<el-input v-model="maintenanceName" placeholder="请输入维保目录" clearable prefix-icon="Search"
						style="margin-bottom: 20px" />
				</div>
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5" v-hasPermi="['maintenance:maintenance:add']">
						<el-button type="primary" plain icon="Plus" @click="handleAddMaintenance">新增
						</el-button>
					</el-col>
					<el-col :span="1.5" v-hasPermi="['maintenance:maintenance:import']">
						<ImportData url="maintenance/maintenance" title="维保目录" @success="getTreeselect" />
					</el-col>
					<el-col :span="1.5">
						<el-button type="warning" plain icon="Download" @click="handleExport"
							v-hasPermi="['maintenance:maintenance:export']">导出
						</el-button>
					</el-col>

				</el-row>
				<div class="head-container" style="height:calc(100vh - 50px);max-height:calc(100vh - 200px)">
					<el-scrollbar class="solid radius">
						<el-tree :data="maintenanceOptions" :props="{ label: 'maintenanceName', children: 'children' }"
							:expand-on-click-node="false" :filter-node-method="filterNode" ref="maintenanceRef"
							:default-expand-all="false" @node-click="handleMaintenanceClick">
							<template #default="{ node, data }">
								<span class="impa-tree-node"
									:class="{ active: data.maintenanceId == queryParams.maintenanceId }">
									<div class="left">
										<el-tooltip :content="`${data.label}`" placement="bottom">
											<div>{{ data.label }}</div>
										</el-tooltip>
									</div>
									<div class="action flex align-center">
										<div class="flex align-center" v-hasPermi="['maintenance:maintenance:query']">
											<el-icon @click.stop="handleViewMaintenance(data);"
												color="var(--el-color-warning)">
												<InfoFilled />
											</el-icon>
										</div>
										<div class="flex align-center" v-hasPermi="['maintenance:maintenance:add']">
											<el-icon
												@click.stop="handleAddMaintenance(); maintenanceForm.parentId = data.maintenanceId;"
												color="var(--el-color-primary)" class="margin-left-xs">
												<DocumentAdd />
											</el-icon>
										</div>
										<div class="flex align-center" v-hasPermi="['maintenance:maintenance:edit']">
											<el-icon @click.stop="handleUpdateMaintenance(data)"
												color="var(--el-color-success)" class="margin-left-xs">
												<Edit />
											</el-icon>
										</div>
										<!-- v-if="!(data.children != undefined || data.maintenanceId == 123)" -->
										<div class="flex align-center" v-hasPermi="['maintenance:maintenance:remove']">
											<el-icon @click.stop="handleRemoveMaintenance(node, data)"
												color="var(--el-color-danger)" class="margin-left-xs">
												<Delete />
											</el-icon>
										</div>
									</div>
								</span>
							</template>
						</el-tree>
					</el-scrollbar>
				</div>
			</el-card>
		<!-- </el-affix> -->

		<!-- 添加或修改维保管理-维保目录对话框 -->
		<el-dialog :title="title" v-model="openMaintenanceDialog" width="500px" append-to-body>
			<el-form ref="maintenanceRef" :model="maintenanceForm" :rules="rules" label-width="80px">
				<el-form-item label="父级维保" prop="parentId" v-if="maintenanceForm.maintenanceId == null">
					<el-tree-select filterable v-model="maintenanceForm.parentId" :data="maintenanceOptions"
						:props="{ value: 'maintenanceId', label: 'maintenanceName', children: 'children' }"
						value-key="maintenanceId" clearable placeholder="请选择父级维保" check-strictly
						:disable="maintenanceForm.maintenanceId != null" />
				</el-form-item>
				<el-form-item label="维保名称" prop="maintenanceName">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.maintenanceName" placeholder="请输入维保名称" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.maintenanceName"
						:fetch-suggestions="querySearchMaintenanceName" clearable placeholder="请输入维保名称"
						style="width:100%" @select="handleMaintenanceFormMaintenanceNameChange" />
				</el-form-item>
				<el-form-item label="生产厂商" prop="manufacturer">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.manufacturer" placeholder="请输入生产厂商" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.manufacturer"
						:fetch-suggestions="querySearchManufacturer" clearable placeholder="请输入生产厂商"
						style="width:100%" />
				</el-form-item>
				<el-form-item label="型号" prop="model">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.model" placeholder="请输入型号" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.model"
						:fetch-suggestions="querySearchModel" clearable placeholder="请输入型号" style="width:100%" />
				</el-form-item>
				<el-form-item label="序列号" prop="serialNumber">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.serialNumber" placeholder="请输入序列号" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.serialNumber"
						:fetch-suggestions="querySearchSerialNumber" clearable placeholder="请输入序列号"
						style="width:100%" />
				</el-form-item>
				<el-form-item label="供货商" prop="supplier">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.supplier" placeholder="请输入供货商" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.supplier"
						:fetch-suggestions="querySearchSupplier" clearable placeholder="请输入供货商" style="width:100%" />
				</el-form-item>
				<el-form-item label="生产日期" prop="productionTime">
					<el-date-picker v-model="maintenanceForm.productionTime" type="date" placeholder="请选择生产日期"
						value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" />
				</el-form-item>
				<el-form-item label="船检编号" prop="shipInspectionNo">
					<!-- <el-input maxlength="100" v-model="maintenanceForm.shipInspectionNo" placeholder="请输入船检编号" /> -->
					<el-autocomplete maxlength="100" v-model="maintenanceForm.shipInspectionNo"
						:fetch-suggestions="querySearchShipInspectionNo" clearable placeholder="请输入船检编号"
						style="width:100%" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitIMPAForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="MaintenanceSidebar">
	import {
		listMaintenance,
		getMaintenance,
		delMaintenance,
		addMaintenance,
		updateMaintenance,
		downloadMaintenance
	} from "@/api/maintenance/maintenance";
	import {
		overrideProperties
	} from "@/utils/ruoyi";
	import ImportData from "@/components/ImportData";

	const {
		proxy
	} = getCurrentInstance();
	const emit = defineEmits();

	const props = defineProps({
		modelValue: [String, Number],
		showView: {
			type: Boolean,
			default: false,
		},
	});
	const {
		modelValue,
		showView
	} = toRefs(props);

	const maintenanceName = ref("");
	const maintenanceList = ref([]);
	const maintenanceOptions = ref(undefined);
	const title = ref("");
	const openMaintenanceDialog = ref(false);
	const loading = ref(true);

	const data = reactive({
		maintenanceForm: {},
		queryParams: {
			pageNum: 1,
			pageSize: 10,
		},
		rules: {
			// parentId: [
			//     {
			//         required: true,
			//         message: "父级维保不能为空",
			//         trigger: "blur",
			//     },
			// ],
			maintenanceName: [{
				required: true,
				message: "维保名称不能为空",
				trigger: "blur",
			}, ],
			manufacturer: [{
				required: true,
				message: "生产厂商不能为空",
				trigger: "blur",
			}, ],
			model: [{
				required: true,
				message: "型号不能为空",
				trigger: "blur",
			}, ],
			serialNumber: [{
				required: true,
				message: "序列号不能为空",
				trigger: "blur",
			}, ],
			supplier: [{
				required: true,
				message: "供货商不能为空",
				trigger: "blur",
			}, ],
			productionTime: [{
				required: true,
				message: "生产日期不能为空",
				trigger: "blur",
			}, ],
			shipInspectionNo: [{
				required: true,
				message: "船检编号不能为空",
				trigger: "blur",
			}, ],
			maintenanceId: [{
				required: true,
				message: "维保编号不能为空",
				trigger: "blur",
			}, ],
		},
	});

	const {
		maintenanceForm,
		queryParams,
		rules
	} = toRefs(data);

	async function searchAutocompleteList(key, value) {
		let params = {
			pageNum: 1,
			pageSize: queryParams.value.pageSize,
		};
		params[key] = value;
		let result;
		await listMaintenance(params).then((response) => {
			result = response.data;
		});
		return Promise.resolve(result);
	}

	const querySearchMaintenanceName = async (queryString, cb) => {
		const responses = await searchAutocompleteList(
			`maintenanceName`,
			queryString
		);
		const results = Array.from(
			new Set(
				responses
				.filter((item) => item.parentId != 0)
				.map((item) => item[`maintenanceName`])
			)
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	const querySearchManufacturer = async (queryString, cb) => {
		const responses = await searchAutocompleteList(`manufacturer`, queryString);
		const results = Array.from(
			new Set(responses.map((item) => item[`manufacturer`]))
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	const querySearchModel = async (queryString, cb) => {
		const responses = await searchAutocompleteList(`model`, queryString);
		const results = Array.from(
			new Set(responses.map((item) => item[`model`]))
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	const querySearchSerialNumber = async (queryString, cb) => {
		const responses = await searchAutocompleteList(`serialNumber`, queryString);
		const results = Array.from(
			new Set(responses.map((item) => item[`serialNumber`]))
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	const querySearchSupplier = async (queryString, cb) => {
		const responses = await searchAutocompleteList(`supplier`, queryString);
		const results = Array.from(
			new Set(responses.map((item) => item[`supplier`]))
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	const querySearchShipInspectionNo = async (queryString, cb) => {
		const responses = await searchAutocompleteList(
			`shipInspectionNo`,
			queryString
		);
		const results = Array.from(
			new Set(responses.map((item) => item[`shipInspectionNo`]))
		).map((item) => {
			return {
				value: item
			};
		});
		cb(results);
	};

	watch(modelValue, (newValue) => {
		// let array = maintenanceList.value.filter(item => item.maintenanceId == newValue)[0];
		// let name = array ? array.maintenanceName : '';
		queryParams.value.maintenanceId = newValue;

		// maintenanceName.value = name;
	});

	/** 通过条件过滤节点  */
	const filterNode = (value, data) => {
		if (!value) return true;
		return data.label.indexOf(value) !== -1;
	};
	/** 根据名称筛选部门树 */
	watch(maintenanceName, (val) => {
		proxy.$refs["maintenanceRef"].filter(val);
	});

	/** 新增按钮操作 */
	function handleAddMaintenance() {
		reset();
		maintenanceForm.value.productionTime = proxy.parseTime(new Date());
		title.value = "新增维保管理-维保目录";
		openMaintenanceDialog.value = true;
	}

	/** 查询部门下拉树结构 */
	async function getTreeselect() {
		loading.value = true;
		await listMaintenance({
			pageNum: 1,
			pageSize: 9999
		}).then((response) => {
			response.data.map((item) => {
				item.label = `${item.maintenanceName}`;
			});
			maintenanceList.value = response.data;
			maintenanceOptions.value = proxy.handleTree(
				response.data,
				"maintenanceId",
				"parentId"
			);
			emit("update:maintenanceList", maintenanceList.value);
			emit("update:maintenanceOptions", maintenanceOptions.value);
			loading.value = false;
			//// console.log(maintenanceOptions.value)
		});
	}

	/** 节点单击事件 */
	function handleMaintenanceClick(data) {
		if (queryParams.value.maintenanceId == data.maintenanceId) {
			queryParams.value.maintenanceId = null;
			// maintenanceName.value = ""
		} else {
			queryParams.value.maintenanceId = data.maintenanceId;
			// maintenanceName.value = data.maintenanceName
		}
		emit("update:modelValue", queryParams.value.maintenanceId);
		emit("update:maintenance", data);
	}

	/** 修改按钮操作 */
	async function handleUpdateMaintenance(row) {
		reset();
		await getTreeselect();
		if (row != null) {
			maintenanceForm.value.parentId = row.maintenanceId;
		}
		getMaintenance(row.maintenanceId).then((response) => {
			maintenanceForm.value = response.data;
			openMaintenanceDialog.value = true;
			title.value = "修改维保管理-维保目录";
		});
	}

	function handleViewMaintenance(data) {
		if (showView.value) {
			openMaintenanceDialog.value = true;
		}
		//// console.log(data);
		emit("onView", data);
	}

	/** 删除按钮操作 */
	function handleRemoveMaintenance(node, data) {
		// console.log(node, data);
		proxy.$modal
			.confirm(`是否删除【${data.label}】？`)
			.then(() => {
				delMaintenance(data.maintenanceId).then(() => {
					getTreeselect();
				});
			})
			.catch(() => {});
	}

	/** 重置操作表单 */
	function reset() {
		maintenanceForm.value = {};
	}

	/** 提交按钮 */
	function submitIMPAForm() {
		proxy.$refs["maintenanceRef"].validate((valid) => {
			// console.log(valid);
			if (valid) {
				if (maintenanceForm.value.maintenanceId != undefined) {
					updateMaintenance(maintenanceForm.value).then((response) => {
						proxy.$modal.msgSuccess("修改成功");
						openMaintenanceDialog.value = false;
						emit("update:maintenance", maintenanceForm.value);
						getTreeselect();
					});
				} else {
					addMaintenance(maintenanceForm.value).then((response) => {
						proxy.$modal.msgSuccess("新增成功");
						openMaintenanceDialog.value = false;
						getTreeselect();
					});
				}
			}
		});
	}

	/** 取消按钮 */
	function cancel() {
		openMaintenanceDialog.value = false;
		reset();
	}

	const handleMaintenanceFormMaintenanceNameChange = (value) => {
		console.log(value);
		if (!value.value.trim().length) {
			return;
		}
		listMaintenance({
			pageNum: 1,
			pageSize: queryParams.value.pageSize,
			maintenanceName: value.value,
		}).then((response) => {
			if (response.data.length > 0) {
				response.data[0].maintenanceId = null;
				overrideProperties(maintenanceForm.value, response.data[0]);
				maintenanceForm.value.maintenanceId = null;
			}
		});
	};

	/** 导出按钮操作 */
	function handleExport() {
		downloadMaintenance(queryParams.value);
		// proxy.download('impa/impa/export', {
		//   ...queryParams.value
		// }, `impa_${new Date().getTime()}.xlsx`)
	}

	onActivated(() => {
		//// console.log("onActivated")
		getTreeselect();
		// getList();
	});

	onMounted(async () => {
		//// console.log("onMounted")
		// getList();
		await getTreeselect();
		//   console.log(maintenanceList.value);
		//   queryParams.value.maintenanceId = modelValue.value;
		//   let _maintenanceList = maintenanceList.value.filter(
		//     (item) => item.maintenanceId == modelValue.value
		//   );
		//   //   console.log(_maintenanceList);
		//   emit("update:maintenance", _maintenanceList[0]);
	});
</script>

<style lang="scss">
	.impa-tree-node {
		width: 90%;
		display: flex;
		align-items: center;
		justify-content: space-between;

		// padding-right: 10px;
		.action {
			display: none;
			margin-right: 10px;
		}

		>.left {
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			// margin-right:20px;
			// max-width: 50%;
		}

		&.active {
			background-color: var(--el-tree-node-hover-bg-color);
			color: var(--van-primary-color);
			font-weight: bold;
		}

		&:hover {
			.action {
				display: flex;
			}
		}
	}
</style>
