<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: DY
 * @LastEditTime: 2024-02-27 09:41:00
 * @Description:
-->
<template>
	<el-drawer
		:visible.sync="visible"
		:show-close="false"
		:wrapper-closable="isdetail"
		class="drawer"
		size="60%">
		<small-title slot="title" :no-padding="true">
			{{ isdetail ? '详情' : !dataForm.id ? '新增' : '编辑' }}
		</small-title>
		<div class="content">
			<div class="visual-part">
				<el-form
					:model="dataForm"
					:rules="dataRule"
					ref="dataForm"
					@keyup.enter.native="dataFormSubmit()"
					label-width="100px"
					label-position="top">
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="巡检单名称" prop="name">
								<el-input v-model="dataForm.name" placeholder="请输入巡检单名称" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="部门" prop="departmentId">
								<el-select
									v-model="dataForm.departmentId"
									:placeholder="`请选择部门`">
									<el-option
										v-for="opt in departmentOptions"
										:key="opt.id"
										:label="opt.name"
										:value="opt.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="班次" prop="groupClass">
								<el-select
									v-model="dataForm.groupClass"
									filterable
									clearable
									multiple
									:disabled="isedit"
									style="width: 100%"
									placeholder="请选择班次">
									<el-option
										v-for="d in groupOptions"
										:key="d.id"
										:label="d.name"
										:value="d.id" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="巡检人" prop="checkPerson">
								<el-select
									v-model="dataForm.checkPerson"
									:placeholder="`请选择巡检人`"
									multiple
									clearable
									:disabled="isedit"
									filterable>
									<el-option
										v-for="opt in inspectorOptions"
										: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="planCheckTime">
								<el-date-picker
									v-model="dataForm.planCheckTime"
									type="datetime"
									:disabled="isedit"
									placeholder="请选择巡检时间"
									value-format="timestamp"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>

			<div class="attr-list" v-if="idAttrShow">
				<small-title
					style="margin: 16px 0; padding-left: 8px"
					:no-padding="true">
					巡检内容
				</small-title>

				<div v-if="!isdetail">
					<div>
						<SearchBar
							:formConfigs="searchBarFormConfig"
							ref="attr-search-bar"
							@headBtnClick="handleSearchBarBtnClick" />
					</div>
					<!-- <template>
						<span style="display: inline-block;" @click="addNew()">
							<svg-icon style="width: 14px; height: 14px" class="item-icon" icon-class="table_add" />
							<span class="add">添加</span>
						</span>
					</template> -->
				</div>
				<base-table
					:table-props="tableProps"
					:page="listQuery.pageNo"
					:limit="listQuery.pageSize"
					:table-data="detList">
					<method-btn
						v-if="!isdetail"
						slot="handleBtn"
						:width="120"
						label="操作"
						:method-list="tableBtn"
						@clickBtn="handleClick" />
				</base-table>
				<pagination
					v-show="listQuery.total > 0"
					:total="listQuery.total"
					:page.sync="listQuery.pageNo"
					:limit.sync="listQuery.pageSize"
					:page-sizes="[5, 10, 15]"
					@pagination="getList" />
			</div>

		</div>

		<div v-if="!isdetail" class="drawer-body__footer">
			<el-button @click="goback()">取消</el-button>
			<!-- <el-button :disabled="isdetail" @click="init(dataForm.id)">重置</el-button> -->
			<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
		</div>

		<attr-add
			v-if="addOrUpdateVisible"
			ref="addOrUpdate"
			:order-id="dataForm.id"
			@refreshDataList="getList" />
	</el-drawer>
</template>

<script>
import basicAdd from './../../../../core/mixins/basic-add';
import { createCheckOrder, updateCheckOrder, getCheckOrder } from "@/api/equipment/base/inspection/settings";
import { getCheckOrderDetPage, deleteCheckOrderDet } from "@/api/equipment/base/inspection/record";
import SmallTitle from './SmallTitle';
import { parseTime } from '@/utils/ruoyi';
import attrAdd from './attr-add';
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import { getCoreDepartmentList } from "@/api/base/coreDepartment";
import { groupClassesListAll } from '@/api/monitoring/teamProduction'

const tableBtn = [
	{
		type: 'edit',
		btnName: '编辑',
	},
	{
		type: 'delete',
		btnName: '删除',
	},
];
const tableProps = [
	{
		prop: 'equipmentName',
		label: '设备名称'
	},
	{
		prop: 'program',
		label: '巡检项目',
	},
	{
		prop: 'checkResult',
		label: '巡检结果',
	},
];

const topBtnConfig = [
  {
    type: 'add',
    btnName: 'btn.add'
  }
]

export default {
	mixins: [basicAdd],
	components: { SmallTitle, attrAdd },
	data() {
		return {
			tableBtn,
			tableProps,
			topBtnConfig,
			addOrUpdateVisible: false,
			urlOptions: {
			  isGetCode: false,
				createURL: createCheckOrder,
				updateURL: updateCheckOrder,
				infoURL: getCheckOrder,
			},
			searchBarFormConfig: [
				{
					type: 'input',
					label: '设备',
					placeholder: '请输入设备名称',
					param: 'equipmentName',
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'button',
					btnName: '新增',
					name: 'add',
					color: 'success',
					plain: true
				}
			],
			listQuery: {
				pageSize: 10,
				pageNo: 1,
				total: 0,
				equipmentName: undefined
			},
			dataForm: {
        id: undefined,
        name: '',
				departmentId: undefined,
				groupClass: undefined,
        checkPerson: undefined,
				planCheckTime: undefined
			},
			detList: [],
			groupOptions: [],
			// departmentList: [],
			departmentOptions: [],
			inspectorOptions: [],
			visible: false,
			isdetail: false,
			isedit: false,
			idAttrShow: false,
			dataRule: {
        name: [{ required: true, message: "巡检单名称不能为空", trigger: "blur" }]
      }
		};
	},
	mounted() {
		this.getDict()
	},
	methods: {
		async getDict() {
			// 班次列表
			const res = await groupClassesListAll();
			this.groupOptions = res.data || [];
			// 部门列表
			const res1 = await getCoreDepartmentList();
			this.departmentOptions = res1.data || []
			// 巡检人
			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.username,
						value: item.id,
					}))
				);
			}
			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;
			// const res1 = await groupClassesListAll();
			// this.groupOptions = res1.data || [];
			// const res = await getEquipmentAll()
			// this.eqList = res.data
		},
		handleSearchBarBtnClick(btn) {
			switch (btn.btnName) {
				case 'search':
					this.listQuery.equipmentName = btn.equipmentName;
					this.getList();
					break;
				case 'add':
					this.addNew()
					break;
			}
		},
		initData() {
			this.detList.splice(0);
			this.listQuery.total = 0;
		},
		handleClick(raw) {
			if (raw.type === 'delete') {
				this.$confirm(
					`是否确认删除巡检项目名为"${raw.data.program}"的数据项?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				)
					.then(() => {
						deleteCheckOrderDet(raw.data.id).then(({ data }) => {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getList();
								},
							});
						});
					})
					.catch(() => {});
			} else {
				this.addNew(raw.data.id);
			} 
		},
		getList() {
			// 获取设备巡检单详细
			getCheckOrderDetPage({
				...this.listQuery,
				orderId: this.dataForm.id,
			}).then((response) => {
				this.detList = response.data.list;
				this.listQuery.total = response.data.total;
			});
		},
		init(id, isdetail) {
			this.initData();
			this.isdetail = isdetail || false;
			this.dataForm.id = id || undefined;
			this.isedit = id ? true : false;
			console.log('你好', this.isedit)
			this.visible = true;
			if (id) {
				this.idAttrShow = true
			} else {
				this.idAttrShow = false
			}

			this.$nextTick(() => {
				this.$refs['dataForm'].resetFields();

				if (this.dataForm.id) {
					// 获取巡检单详情
					this.urlOptions.infoURL(id).then(response => {
            this.dataForm = response.data
          });
					// 获取巡检内容列表
					this.getList();
				} else {
					if (this.urlOptions.isGetCode) {
            this.getCode()
          }
				}
			});
		},
		goback() {
			this.$emit('refreshDataList');
			this.visible = false;
			this.initData();
		},
		goEdit() {
			this.isdetail = false;
		},
		// 新增 / 修改
		addNew(id) {
			this.addOrUpdateVisible = true;
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(id);
			});
		},
		// 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (!valid) {
          return false;
        }
        // 修改的提交
        if (this.dataForm.id) {
          this.urlOptions.updateURL({
						...this.dataForm,
						groupClass: this.dataForm.groupClass.join(','),
						checkPerson: this.dataForm.checkPerson.join(','),
						special: false,
						status: 1
					}).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.visible = false; 
            this.$emit("refreshDataList");
          });
          return;
        }
        // 添加的提交
        this.urlOptions.createURL({
					...this.dataForm,
					groupClass: this.dataForm.groupClass.join(','),
					checkPerson: this.dataForm.checkPerson.join(','),
					special: false,
					status: 1
				}).then(response => {
          this.$modal.msgSuccess("新增成功");
					this.idAttrShow = true
					this.dataForm.id = response.data
          // this.visible = false;
          this.$emit("refreshDataList");
        });
      });
    }
	}
};
</script>
<style scoped>
.drawer >>> .el-drawer {
	border-radius: 8px 0 0 8px;
	display: flex;
	flex-direction: column;
}

.drawer >>> .el-form-item__label {
	padding: 0;
}

.drawer >>> .el-drawer__header {
	margin: 0;
	padding: 32px 32px 24px;
	border-bottom: 1px solid #dcdfe6;
}
.drawer >>> .el-drawer__body {
	flex: 1;
	height: 1px;
	display: flex;
	flex-direction: column;
}

.drawer >>> .content {
	padding: 30px 24px;
	/* flex: 1; */
	display: flex;
	flex-direction: column;
	/* height: 100%; */
}

.drawer >>> .visual-part {
	flex: 1 auto;
	max-height: 76vh;
	overflow: hidden;
	overflow-y: scroll;
	padding-right: 10px; /* 调整滚动条样式 */
}

.drawer >>> .el-form,
.drawer >>> .attr-list {
	padding: 0 16px;
}

.drawer-body__footer {
	display: flex;
	justify-content: flex-end;
	padding: 18px;
}
.action_btn {
  float: right;
  margin: -32px 15px 0;
  font-size: 14px;
}
.add {
	color: #0b58ff;
}
</style>
