<!-- 
    filename: Record-detail.vue
    author: liubin
    date: 2024-2-24 11:38:56
    description: 
-->

<template>
	<el-drawer
		:visible="visible"
		:show-close="false"
		:wrapper-closable="false"
		class="drawer"
		custom-class="mes-drawer"
		size="60%"
		@closed="$emit('destroy')">
		<SmallTitle slot="title">查看详情</SmallTitle>

		<div class="drawer-body flex">
			<div class="drawer-body__content">
				<div class="form-part" style="margin-bottom: 32px">
					<!-- <el-skeleton v-if="!showForm" animated /> -->
					<el-form
						class="equipment-info-form"
						ref="form"
						:model="form"
						label-width="200px"
						label-position="top"
						v-loading="formLoading">
						<el-row :gutter="20">
							<el-col :span="8">
								<el-form-item label="巡检单名称" prop="name">
									<div style="">{{ form.name }}</div>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="部门" prop="department">
									<div style="">{{ form.department }}</div>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="班次" prop="groupClass">
									<div style="">{{ form.groupClass || '---' }}</div>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="巡检人" prop="checkPerson">
									<div style="">{{ form.checkPerson || '---' }}</div>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="巡检时间" prop="planCheckTime">
									<div style="">{{ form.planCheckTime | parseTime }}</div>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="确认人" prop="confirmPerson">
									<div style="">{{ form.confirmPerson || '---' }}</div>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>

				<SmallTitle>巡检内容</SmallTitle>

				<div style="margin-top: 12px; position: relative">
					<!-- <SearchBar
						:formConfigs="searchBarFormConfig"
						ref="attr-search-bar"
						@headBtnClick="handleSearchBarBtnClick" /> -->
				</div>

				<div style="margin-top: 12px; position: relative">
					<div
						v-if="!disableEdit"
						style="position: absolute; top: -40px; right: 0">
						<el-button @click="handleAddAttr" type="text">
							<i class="el-icon-plus"></i>
							添加内容
						</el-button>
					</div>
					<base-table
						v-loading="attrListLoading"
						:table-props="attrTableProps"
						:page="attrQuery?.params.pageNo || 1"
						:limit="attrQuery?.params.pageSize || 10"
						:table-data="attrList"
						@emitFun="handleEmitFun">
						<method-btn
							slot="handleBtn"
							label="操作"
							v-if="!disableEdit"
							:method-list="tableBtn"
							@clickBtn="handleTableBtnClick" />
					</base-table>

					<!-- 分页组件 -->
					<pagination
						v-show="attrTotal > 0"
						:total="attrTotal"
						:page.sync="attrQuery.params.pageNo"
						:limit.sync="attrQuery.params.pageSize"
						@pagination="getAttrList" />
				</div>
			</div>

			<div class="drawer-body__footer">
				<el-button style="" @click="handleCancel">
					{{ disableEdit ? '返回' : '取消' }}
				</el-button>
				<el-button
					v-if="!disableEdit"
					type="primary"
					:loading="btnLoading"
					@click="handleConfirm">
					保存
				</el-button>
			</div>
		</div>

		<!-- 属性对话框 -->
		<base-dialog
			:dialogTitle="attrTitle"
			:dialogVisible="attrFormVisible"
			width="35%"
			:append-to-body="true"
			custom-class="baseDialog"
			@close="closeAttrForm"
			@cancel="closeAttrForm"
			@confirm="submitAttrForm">
			<DialogForm
				v-if="attrFormVisible"
				ref="attrForm"
				v-model="attrForm"
				:rows="attrRows" />
		</base-dialog>
	</el-drawer>
</template>

<script>
import { parseTime } from '../../core/mixins/code-filter';
import DialogForm from '../../../components/DialogForm/index.vue';

const SmallTitle = {
	name: 'SmallTitle',
	props: ['size'],
	components: {},
	data() {
		return {};
	},
	methods: {},
	render: function (h) {
		return h(
			'span',
			{
				class: 'small-title',
				style: {
					fontSize: '18px',
					lineHeight:
						this.size == 'lg' ? '24px' : this.size == 'sm' ? '18px' : '20px',
					fontWeight: 500,
					fontFamily: '微软雅黑, Microsoft YaHei, Arial, Helvetica, sans-serif',
				},
			},
			this.$slots.default
		);
	},
};

export default {
	components: { SmallTitle, DialogForm },
	props: ['dataId'], // dataId 作为一个通用的存放id的字段
	filters: { parseTime },
	data() {
		return {
			visible: false,
			btnLoading: false,
			form: {},
			formLoading: false,
			departmentList: [],
			inspectorOptions: [],
			attrTableProps: [
				{
					prop: 'equipmentName',
					label: '设备名称',
				},
				{
					prop: 'program',
					label: '巡检项目',
				},
				{
					prop: 'checkResult',
					label: '巡检结果',
				},
			],
			attrList: [],
			attrTotal: 0,
			attrTitle: '',
			attrForm: {
				id: null,
				orderId: null,
				program: null,
				checkResult: null,
				equipmentId: null,
			},
			attrFormVisible: false,
			attrRows: [
				[
					{
						select: true,
						label: '设备名称',
						prop: 'equipmentId',
						url: '/base/core-equipment/page?pageNo=1&pageSize=100&special=true',
						rules: [
							{ required: true, message: '设备不能为空', trigger: 'blur' },
						],
					},
				],
				[
					{
						input: true,
						label: '巡检项目',
						prop: 'program',
						rules: [
							{ required: true, message: '巡检项目不能为空', trigger: 'blur' },
						],
					},
				],
				[
					{
						input: true,
						label: '巡检结果',
						prop: 'checkResult',
						rules: [
							{ required: true, message: '巡检结果不能为空', trigger: 'blur' },
						],
					},
				],
			],
			attrQuery: {
				params: {
					pageNo: 1,
					pageSize: 10,
					equipmentName: null,
				},
			}, // 属性列表的请求
			searchBarFormConfig: [
				{
					type: 'input',
					label: '设备',
					placeholder: '请输入设备名称',
					param: 'equipmentName',
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
			],
			attrFormSubmitting: false,
			attrListLoading: false,
			// syncFileListFlag: null,
			tableBtn: [
				{
					type: 'edit',
					btnName: '编辑',
				},
				{
					type: 'delete',
					btnName: '删除',
				},
			],
			row: null,
			groupOptions: [],
			disableEdit: false,
		};
	},
	computed: {
		departmentOptions() {
			return (this.departmentList || []).map((item) => ({
				id: item.id,
				label: item.name,
				value: item.id,
			}));
		},
	},
	mounted() {
		// this.formLoading = true;
		// this.getList('department');
		// this.getList('groupClass');
		// this.getList('inspector');
	},
	methods: {
		handleSearchBarBtnClick(btn) {
			switch (btn.btnName) {
				case 'search':
					this.attrQuery.params.equipmentName = btn.equipmentName;
					this.getAttrList();
					break;
			}
		},
		handleTableBtnClick({ type, data }) {
			switch (type) {
				case 'edit':
					this.handleEditAttr(data.id);
					break;
				case 'delete':
					this.handleDeleteAttr(data.id);
					break;
			}
		},
		async handleConfirm() {
			this.btnLoading = true;
			this.$nextTick(async () => {
				const { code, data } = await this.$axios({
					url: '/base/equipment-check-order/update',
					method: 'put',
					data: {
						...this.form,
						groupClass: this.form.groupClass?.join(','),
						checkPerson: this.form.checkPerson?.join(','),
					},
				});
				if (code == 0) {
					this.$modal.msgSuccess('更新成功');
				}
				this.btnLoading = false;
				this.$emit('refreshDataList');
				this.handleCancel();
			});
		},

		handleEmitFun(val) {
			console.log('handleEmitFun', val);
		},

		init(row, detail) {
			if (detail) this.disableEdit = true;
			this.visible = true;
			this.row = row;
			this.getInfo(row);
			this.getAttrList(row);
		},

		async getInfo(row) {
			const res = await this.$axios(
				'/base/equipment-check-order/get?id=' + row.id
			);
			if (res.code == 0) {
				this.form = res.data;
				// this.form.groupClass = res.data.groupClass.split(',');
				// this.form.checkPerson = res.data.checkPerson?.split(',');
				this.formLoading = false;
			}
			this.formLoading = false;
		},

		async getAttrList(row, condition = {}) {
			if (!row) row = this.row;
			this.attrListLoading = true;
			const res = await this.$axios({
				url: '/base/equipment-check-order-det/page',
				method: 'get',
				params: {
					...this.attrQuery.params,
					orderId: row.id,
					...condition,
				},
			});
			if (res.code == 0) {
				this.attrList = res.data.list;
				this.attrTotal = res.data.total;
			}
			this.attrListLoading = false;
		},

		async getList(source = 'department') {
			const urls = [
				'/base/core-department/listAll',
				'/base/group-classes/listAll',
			];
			let res;
			switch (source) {
				case 'department':
					res = await this.$axios(urls[0]);
					this.departmentList = res.data || [];
					break;
				case 'inspector':
					let inspectorList = [];
					const userlist = await this.$axios({
						url: '/system/user/page',
						params: { pageNo: 1, pageSize: 100 },
					});
					if (userlist.code == 0) {
						inspectorList = inspectorList.concat(
							(userlist.data?.list || []).map((item) => ({
								label: item.nickname,
								value: item.nickname,
							}))
						);
					}
					const workerlist = await this.$axios('/base/core-worker/listAll');
					if (workerlist.code == 0) {
						inspectorList = inspectorList.concat(
							workerlist.data.map((item) => ({
								label: item.name,
								value: item.id,
							}))
						);
					}
					this.inspectorOptions = inspectorList;
					break;
				case 'groupClass':
					res = await this.$axios(urls[1]);
					this.groupOptions = (res.data || []).map((item) => ({
						label: item.name,
						value: item.id,
					}));
					break;
			}
			this.formLoading = false;
		},

		// 保存表单
		handleSave() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					await this.$axios({
						url: '/urlupdate', //  this.sections[0][isEdit ? 'urlUpdate' : 'urlCreate'],
						method: 'post', // isEdit ? 'put' : 'post',
						data: this.form,
					});
					this.$modal.msgSuccess(`${isEdit ? '更新' : '创建'}成功`);
					this.visible = false;
					this.$emit('refreshDataList');
				}
			});
		},

		handleCancel() {
			this.visible = false;
		},

		resetAttrform() {
			this.attrForm = {
				id: null,
				orderId: null,
				equipmentId: null,
				program: null,
				checkResult: null,
			};
		},

		// 新增属性
		handleAddAttr() {
			if (!this.row.id) return this.$message.error('请先选中保养记录');
			this.resetAttrform();
			this.attrTitle = '添加设备属性';
			this.attrFormVisible = true;
		},

		// 编辑属性
		async handleEditAttr(attrId) {
			const res = await this.$axios({
				url: '/base/equipment-check-order-det/get',
				method: 'get',
				params: { id: attrId },
			});
			if (res.code == 0) {
				this.attrForm = res.data;
				this.attrTitle = '编辑巡检单详情';
				this.attrFormVisible = true;
			}
		},

		// 删除属性
		handleDeleteAttr(attrId) {
			this.$confirm('确定删除该巡检内容?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					const res = await this.$axios({
						url: '/base/equipment-check-order-det/delete?id=' + attrId,
						method: 'delete',
					});
					if (res.code == 0) {
						this.$message({
							message: '删除成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getAttrList();
							},
						});
					}
				})
				.catch(() => {});
		},

		// 提交属性表
		submitAttrForm() {
			this.$refs['attrForm'].validate(async (valid) => {
				if (!valid) {
					return;
				}

				try {
					const isEdit = this.attrForm.id != null;
					this.attrFormSubmitting = true;
					const res = await this.$axios({
						url: isEdit
							? '/base/equipment-check-order-det/update'
							: '/base/equipment-check-order-det/create',
						method: isEdit ? 'put' : 'post',
						data: { ...this.attrForm, orderId: this.row.id },
					});

					if (res.code == 0) {
						this.closeAttrForm();
						this.$message({
							message: `${isEdit ? '更新' : '创建'}成功`,
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getAttrList();
							},
						});
					}
					this.attrFormSubmitting = false;
				} catch (err) {
					this.$message({
						message: err,
						type: 'error',
						duration: 1500,
					});
					this.attrFormSubmitting = false;
				}
			});
		},

		closeAttrForm() {
			this.attrFormVisible = false;
		},

		handleClick(raw) {
			if (raw.type === 'delete') {
				this.$confirm(
					`确定对${
						raw.data.name
							? '[名称=' + raw.data.name + ']'
							: '[序号=' + raw.data._pageIndex + ']'
					}进行删除操作?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				)
					.then(() => {
						deleteProductAttr(raw.data.id).then(({ data }) => {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getList();
								},
							});
						});
					})
					.catch(() => {});
			} else {
				this.addNew(raw.data.id);
			}
		},
	},
};
</script>

<style scoped>
.drawer >>> .el-drawer {
	border-radius: 8px 0 0 8px;
}

.drawer >>> .el-date-editor,
.drawer >>> .el-select {
	width: 100%;
}

.drawer >>> .el-drawer__header {
	margin: 0;
	padding: 32px 32px 24px;
	border-bottom: 1px solid #dcdfe6;
	margin-bottom: 0px;
}

.small-title::before {
	content: '';
	display: inline-block;
	vertical-align: top;
	width: 4px;
	height: 22px;
	border-radius: 1px;
	margin-right: 8px;
	background-color: #0b58ff;
}

.drawer-body {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.drawer-body__content {
	flex: 1;
	/* background: #eee; */
	padding: 20px 30px;
	overflow-y: auto;
}

.drawer-body__footer {
	display: flex;
	justify-content: flex-end;
	padding: 18px;
}
</style>
