<!-- 
    filename: WaitingListUnplanned--edit.vue
    author: liubin
    date: 2023-08-22 14: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="maintainOrderNumber"
									:rules="[
										{
											required: true,
											message: '请输入保养计划单号',
											trigger: 'blur',
										},
									]">
									<el-input
										v-model="form.maintainOrderNumber"
										:placeholder="`请输入保养计划单号`" />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="保养计划名称" prop="name">
									<el-input value="---" disabled />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item
									label="部门"
									prop="departmentId"
									:rules="[
										{ required: true, message: '请选择部门', trigger: 'blur' },
									]">
									<el-select
										v-model="form.departmentId"
										:placeholder="`请选择部门`"
										clearable
										filterable>
										<el-option
											v-for="opt in departmentOptions"
											:key="opt.value"
											:label="opt.label"
											:value="opt.value" />
									</el-select>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item
									label="产线"
									prop="lineId"
									:rules="[
										{ required: true, message: '请选择产线', trigger: 'blur' },
									]">
									<el-select
										v-model="form.lineId"
										:placeholder="`请选择产线`"
										clearable
										filterable>
										<el-option
											v-for="opt in lineOptions"
											:key="opt.value"
											:label="opt.label"
											:value="opt.value" />
									</el-select>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="计划保养人员" prop="maintainer">
									<el-input value="---" disabled />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="计划开始时间" prop="planStartTime">
									<el-input value="---" disabled />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item label="计划结束时间" prop="planEndTime">
									<el-input value="---" disabled />
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item
									label="实际开始时间"
									prop="startTime"
									:rules="[
										{
											required: true,
											message: '请选择实际开始时间',
											trigger: 'blur',
										},
									]">
									<el-date-picker
										v-model="form.startTime"
										type="datetime"
										placeholder="请选择实际开始时间"
										value-format="timestamp"></el-date-picker>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item
									label="实际结束时间"
									prop="endTime"
									:rules="[
										{
											required: true,
											message: '请选择实际结束时间',
											trigger: 'blur',
										},
									]">
									<el-date-picker
										v-model="form.endTime"
										type="datetime"
										placeholder="请选择实际结束时间"
										value-format="timestamp"></el-date-picker>
								</el-form-item>
							</el-col>

							<el-col :span="8">
								<el-form-item
									label="实际保养人员"
									prop="maintainWorker"
									:rules="[
										{
											required: true,
											message: '请选择实际保养人员',
											trigger: 'blur',
										},
									]">
									<el-select
										v-model="form.maintainWorker"
										:placeholder="`请选择实际保养人员`"
										multiple
										clearable
										filterable>
										<el-option
											v-for="opt in maintainerOptions"
											:key="opt.value"
											:label="opt.label"
											:value="opt.value" />
									</el-select>
								</el-form-item>
							</el-col>

							<el-col :span="24">
								<el-form-item label="备注" prop="remark">
									<el-input v-model="form.remark" :placeholder="`请输入备注`" />
								</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 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="操作"
							: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">取消</el-button>
				<el-button type="primary" @click="handleConfirm">保存</el-button>
				<!-- sections的第二项必须是 属性列表  -->
				<!-- <el-button
						v-if="sections[1].allowAdd"
						type="primary"
						@click="handleAddAttr">
						添加属性
					</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"
				:dataForm="attrForm"
				:rows="attrRows" /> -->
		</base-dialog>
	</el-drawer>
</template>

<script>
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 },
	props: ['dataId'], // dataId 作为一个通用的存放id的字段
	data() {
		return {
			visible: false,
			btnLoading: false,
			form: {},
			lineList: [],
			maintainerList: [],
			departmentList: [],
			attrTableProps: [
				{
					prop: 'equipmentName',
					label: '设备名称',
				},
				{
					prop: 'program',
					label: '保养项目',
				},
				{
					prop: 'maintenanceDes',
					label: '保养描述',
				},
			],
			attrList: [],
			attrTotal: 0,
			attrTitle: '',
			attrForm: {
				id: null,
				equipmentId: null,
				name: '',
				value: '',
			},
			attrFormVisible: false,
			attrRows: [
				[
					{
						input: true,
						label: '属性名称',
						prop: 'name',
						rules: [
							{ required: true, message: '属性名称不能为空', trigger: 'blur' },
						],
					},
				],
				[
					{
						input: true,
						label: '属性值',
						prop: 'value',
					},
				],
			],
			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: [],
			row: null,
		};
	},
	computed: {
		departmentOptions() {
			return (this.departmentList || []).map((item) => ({
				id: item.id,
				label: item.name,
				value: item.id,
			}));
		},
		lineOptions() {
			return (this.lineList || []).map((item) => ({
				id: item.id,
				label: item.name,
				value: item.id,
			}));
		},
		maintainerOptions() {
			return (this.maintainerList || []).map((item) => ({
				id: item.id,
				label: item.name,
				value: item.name,
			}));
		},
	},
	mounted() {
		this.getList('maintainer');
		this.getList('department');
		this.getList('line');
	},
	methods: {
		handleSearchBarBtnClick(btn) {
			console.log('btn', btn);
			switch (btn.btnName) {
				case 'search':
					this.attrQuery.params.equipmentName = btn['key'];
					this.handleQuery();
					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.syncFileListFlag = Math.random();

			this.$nextTick(async () => {
				const { code, data } = await this.$axios({
					url: '/update', // this.sections[0].urlUpdate,
					method: 'put',
					data: this.form,
				});
				if (code == 0) {
					this.$modal.msgSuccess('更新成功');
				}

				this.btnLoading = false;
				this.$emit('refreshDataList');
				this.handleCancel();
			});
		},

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

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

		async getInfo(row) {
			this.formLoading = true;
			const res = await this.$axios(
				'/base/equipment-maintain-log/get?id=' + row.id
			);
			if (res.code == 0) {
				this.form = res.data;
				this.form.maintainWorker = res.data.maintainWorker.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-maintain-log-det/page',
				method: 'get',
				params: {
					...this.attrQuery.params,
					logId: 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-production-line/listAll',
				'/base/core-department/listAll',
				'/base/core-worker/listAll',
			];
			let res;
			switch (source) {
				case 'department':
					res = await this.$axios(urls[1]);
					this.departmentList = res.data || [];
					break;
				case 'maintainer':
					res = await this.$axios(urls[2]);
					this.maintainerList = res.data || [];
					break;
				case 'line':
					res = await this.$axios(urls[0]);
					this.lineList = res.data || [];
					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;
		},

		// 新增属性
		handleAddAttr() {
			if (!this.dataId) return this.$message.error('请先创建设备信息');
			this.attrForm = {
				id: null,
				equipmentId: this.dataId,
				name: '',
				value: '',
			};
			this.attrTitle = '添加设备属性';
			this.attrFormVisible = true;
		},

		// 编辑属性
		async handleEditAttr(attrId) {
			const res = await this.$axios({
				url: 'urlpudate', // this.sections[1].urlDetail,
				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: 'url delete', // this.sections[1].urlDelete,
						method: 'delete',
						params: { id: attrId },
					});
					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: 'url edit',
						// isEdit
						// 	? this.sections[1].urlUpdate
						// 	: this.sections[1].urlCreate,
						method: isEdit ? 'put' : 'post',
						data: this.attrForm,
					});

					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>
