<!--
    filename: MaintainRecord.vue
    author: DY
    date: 2023-12-12 13:54:53
    description:
-->

<template>
	<div class="app-container">
		<!-- 搜索工作栏 -->
		<SearchBar
			:formConfigs="searchBarFormConfig"
			ref="search-bar"
			@select-changed="handleSearchBarChange"
			@headBtnClick="handleSearchBarBtnClick" />
		<WaitingListTable
			ref="waiting-list-table"
			:table-data="list"
			:page="queryParams.pageNo"
			:limit="queryParams.pageSize"
			@edit="handleEdit"
			@detail="handleDetail"
			@delete="handleDelete"
			@confirm="handleConfirm" />

		<!-- 分页组件 -->
		<pagination
			v-show="total > 0"
			:total="total"
			:page.sync="queryParams.pageNo"
			:limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<add-or-update
			v-if="addOrUpdateVisible"
			ref="addOrUpdate"
			@refreshDataList="getList" />
	</div>
</template>

<script>
import AddOrUpdate from './add-or-updata';
import moment from 'moment';
import basicPageMixin from '@/mixins/lb/basicPageMixin';
import { exportCheckOrderExcel } from '@/api/equipment/base/maintain/record';
import WaitingListTable from './WaitingListTable.vue';

// const timeFilter = (val) => moment(val).format('yyyy-MM-DD HH:mm:ss');

const btn = {
	name: 'tableBtn',
	props: ['injectData'],
	data() {
		return {};
	},
	methods: {
		handleClick() {
			this.$emit('emitData', {
				action: this.injectData.label,
				value: this.injectData,
			});
		},
	},
	render: function (h) {
		return (
			<el-button type="text" onClick={this.handleClick}>
				{this.injectData.name}
			</el-button>
		);
	},
};

export default {
	name: 'Confirm',
	components: {
		WaitingListTable,
		AddOrUpdate,
	},
	mixins: [basicPageMixin],
	data() {
		return {
			addOrUpdateVisible: false,
			recordDetailVisible: false,
			searchBarKeys: ['name'],
			tobeConfirmedIdList: [],
			searchBarFormConfig: [
				{
					type: 'input',
					label: '巡检单名称',
					placeholder: '请输入巡检单名称',
					param: 'name',
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type:
						this.$auth.hasPermiAnd([
							'equipment:check-record:create',
							'base:core-worker:query',
							'base:core-production-line:query',
							'base:core-department:query',
						]) ||
						this.$auth.hasPermi('equipment:check-record:update') ||
						this.$auth.hasPermi('equipment:check-record:export')
							? 'separate'
							: '',
				},
				{
					type: this.$auth.hasPermiAnd([
						'equipment:check-record:create',
						'base:core-worker:query',
						'base:core-production-line:query',
						'base:core-department:query',
					])
						? 'button'
						: '',
					btnName: '新增',
					name: 'add',
					plain: true,
					color: 'success',
				},
				{
					type: this.$auth.hasPermi('equipment:check-record:update')
						? 'button'
						: '',
					btnName: '巡检人批量确认',
					name: 'batchConfirm',
					color: 'primary',
					plain: true,
				},
				{
					type: this.$auth.hasPermi('equipment:check-record:update')
						? 'button'
						: '',
					btnName: '确认人批量确认',
					name: 'batchConfirm2',
					color: 'primary',
					plain: true,
				},
				// {
				// 	type: this.$auth.hasPermi('equipment:check-record:export')
				// 		? 'button'
				// 		: '',
				// 	btnName: '导出',
				// 	name: 'export',
				// 	plain: true,
				// 	color: 'primary',
				// },
				// {
				// 	type: this.$auth.hasPermi('equipment:maintain-record:create')
				// 		? 'button'
				// 		: '',
				// 	btnName: '新增',
				// 	name: 'add',
				// 	plain: true,
				// 	color: 'success',
				// },
			],
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNo: 1,
				pageSize: 20,
				maintainPlanId: null,
				startTime: null,
				special: false,
				status: 1,
			},
			// 表单参数
			form: {},
			basePath: '/base/equipment-check-order',
			mode: null,
			allSpecialEquipments: [],
			openPlannedDrawer: false,
			openUnplannedDrawer: false,
			openPlannedDrawer: false,
		};
	},
	watch: {
		tobeConfirmedIdList: {
			handler(val) {
				if (val.length == this.list.length) {
					this.$refs['table'].toggleAllSelection();
				}
			},
		},
	},
	created() {
		this.getList();
	},
	methods: {
		/** 批量确认 */
    async handleSearchBarBtnClick(btn) {
      console.log(11111);

			switch (btn.btnName) {
				case 'batchConfirm':
					if (this.$refs['waiting-list-table'].selectedPlan.length == 0) {
						this.$message.warning('请选择待确认的设备巡检单');
						return;
					}
					this.$modal
						.confirm('是否确认所有选中巡检单"?')
						.then(() => {
							// let checkPersonParam = '';
							// if (!row.checkPerson || row.checkPerson.trim() == '') {
							// 	/** 如有必要，更新巡检人 */
							// 	checkPersonParam = `&checkPerson=${this.$store.getters.nickname}`;
							// }
							return this.$axios({
								// url: `/base/equipment-check-order/confirm?confirmPerson=${this.$store.getters.nickname}` + checkPersonParam,
								url: `/base/equipment-check-order/confirm`,
								method: 'put',
								data: {
									ids: this.$refs['waiting-list-table'].selectedPlan.map(
										(item) => item.id
									),
									confirmBy: this.$store.getters.nickname,
								},
							});
						})
						.then((res) => {
							this.getList();
							res.code == 0 && this.$modal.msgSuccess('确认成功');
							res.code != 0 && this.$modal.msgError('确认失败');
						})
						.catch(() => {});
				case 'batchConfirm2':
					if (this.$refs['waiting-list-table'].selectedPlan.length == 0) {
						this.$message.warning('请选择待确认的设备巡检单');
						return;
					}
					this.$modal
						.confirm('是否确认所有选中巡检单"?')
						.then(() => {
							// let checkPersonParam = '';
							// if (!row.checkPerson || row.checkPerson.trim() == '') {
							// 	/** 如有必要，更新巡检人 */
							// 	checkPersonParam = `&checkPerson=${this.$store.getters.nickname}`;
							// }
							return this.$axios({
								// url: `/base/equipment-check-order/confirm?confirmPerson=${this.$store.getters.nickname}` + checkPersonParam,
								url: `/base/equipment-check-order/confirm2`,
								method: 'put',
								data: {
									ids: this.$refs['waiting-list-table'].selectedPlan.map(
										(item) => item.id
									),
									confirmBy: this.$store.getters.nickname,
								},
							});
						})
						.then((res) => {
							this.getList();
							res.code == 0 && this.$modal.msgSuccess('确认成功');
							res.code != 0 && this.$modal.msgError('确认失败');
						})
            .catch(() => { });
          break;
        case 'search':
          this.getList()
          break;
        case 'add':
          this.addOrUpdateVisible = true;
          this.$nextTick(() => {
            this.$refs.addOrUpdate.init();
          });
					break;
			}
		},
		handleSelectionChange(list) {
			if (this.tobeConfirmedIdList.length) {
				this.tobeConfirmedIdList = [];
				this.list.forEach((item) => {
					this.handleEmitFun({
						action: 'row-selected',
						value: { row: item, selected: false },
					});
				});
				console.log(
					'清空选择列表',
					this.list.map((item) => item._selection)
				);
			} else {
				this.tobeConfirmedIdList = list.map((item) => item.id);
				this.list.forEach((item) => {
					this.handleEmitFun({
						action: 'row-selected',
						value: { row: item, selected: true },
					});
				});
				console.log(
					'全选',
					this.list.map((item) => item._selection)
				);
			}
		},

		handleEmitFun({ action, value }) {
			switch (action) {
				case '详情':
					this.recordDetailVisible = true;
					this.$nextTick(() => {
						this.$refs.recordDetailDrawer.show({
							id: value.id,
							planMaintainWorker: value.planMaintainWorker,
							maintainWorker: value.maintainWorker,
						});
					});
					break;
				case 'row-selected':
					if (value.selected) {
						this.tobeConfirmedIdList.push(value.row.id);
						value.row._selection = 0b11;
					} else {
						const index = this.tobeConfirmedIdList.indexOf(value.row.id);
						if (index != -1) {
							this.tobeConfirmedIdList.splice(index, 1);
						}
					}
					console.log('tobeConfirmedIdList', this.tobeConfirmedIdList);
					break;
			}
		},

		handleSearchBarChange({ param, value }) {
			console.log('122', param);
			// if ('specialType' === param) {
			// 	if (!value) {
			// 		this.setSearchBarEquipmentList(this.allSpecialEquipments);
			// 		return;
			// 	}
			// 	this.setSearchBarEquipmentList(
			// 		this.allSpecialEquipments.filter((item) => item.specialType == value)
			// 	);
			// }
		},
		/** 查询列表 */
		getList() {
			this.loading = true;
			// 执行查询
			this.recv({
				...this.queryParams,
			}).then((response) => {
				this.list = response.data.list;
				this.total = response.data.total;
				this.loading = false;
			});
		},
		/** 取消按钮 */
		cancel() {
			this.open = false;
			this.mode = null;
			this.reset();
		},
		/** 表单重置 */
		reset() {
			this.form = {
				id: null,
				relatePlan: null,
				maintainWorker: [],
				maintainOrderNumber: null,
				departmentId: null,
				lineId: null,
				startTime: null,
				endTime: null,
				planStartTime: null,
				planEndTime: null,
				confirmed: false,
				remark: null,
				special: false,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNo = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm');
			this.handleQuery();
		},
		/** 新增按钮操作 */
		handleAdd() {
			// this.reset();
			// this.open = true;
			// this.title = '添加待确认保养记录';
			// this.addOrEditTitle = '新增';
			this.addOrUpdateVisible = true;
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init();
			});
		},

		// 新增 / 修改
		// addOrUpdateHandle(id) {
		//   this.addOrUpdateVisible = true;
		//   this.$nextTick(() => {
		//     this.$refs.addOrUpdate.init(id);
		//   });
		// },

		getConfirmed() {
			return this.$confirm('是否直接确认巡检记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			});
		},

		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) {
					return;
				}
				// 修改的提交
				if (this.form.id != null) {
					this.put({
						...this.form,
						maintainWorker: this.form.maintainWorker.join(','),
						special: false,
						relatePlan: 2,
					}).then((response) => {
						this.$modal.msgSuccess('修改成功');
						this.open = false;
						this.getList();
					});
					return;
				}

				// 添加的提交
				this.getConfirmed()
					.then((confirmed) => {
						this.post({
							...this.form,
							maintainWorker: this.form.maintainWorker.join(','),
							special: false,
							relatePlan: 2,
							confirmed: true,
						}).then((response) => {
							this.$modal.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					})
					.catch((err) => {
						this.post({
							...this.form,
							maintainWorker: this.form.maintainWorker.join(','),
							special: false,
							relatePlan: 2,
							confirmed: false,
						}).then((response) => {
							this.$modal.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					});
			});
		},
		/** 确认 */
		async handleConfirm(row) {
			this.$modal
				.confirm('是否确认巡检单"' + row.name + '"?')
				.then(() => {
					// let checkPersonParam = '';
					// const nickname = this.$store.getters.nickname;
					// if (!row.checkPerson || row.checkPerson.trim() == '') {
					// 	/** 如有必要，更新巡检人 */
					// 	checkPersonParam = `&checkPerson=${nickname}`;
					// } else {
					// 	checkPersonParam = `&checkPerson=${row.checkPerson}`
					// }
					return this.$axios({
						url: `/base/equipment-check-order/confirm`,
						method: 'put',
						data: {
									ids: [row.id],
									confirmBy: this.$store.getters.nickname,
								},
					});
				})
				.then((res) => {
					this.getList();
					res.code == 0 && this.$modal.msgSuccess('确认成功');
					res.code != 0 && this.$modal.msgError('确认失败');
				})
				.catch(() => {});
		},
		/** 编辑 */
		async handleEdit(row) {
			this.addOrUpdateVisible = true;
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(row.id);
			});
			// this.reset();
			// if (row.relatePlan == 1) {
			// 	// 计划型
			// 	// const res = await this.info({ id: row.id });
			// 	// this.form = res.data;
			// 	// this.form.maintainWorker = res.data.maintainWorker.split(',');
			// 	this.openPlannedDrawer = true;
			// 	this.$nextTick(() => {
			// 		this.$refs.planned.init(row);
			// 	});
			// } else {
			// 	this.openUnplannedDrawer = true;
			// 	this.$nextTick(() => {
			// 		this.$refs.unplanned.init(row);
			// 	});
			// }
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			this.$modal
				.confirm('是否确认删除巡检单名称为"' + row.name + '"的数据项?')
				.then(() => {
					return this.$axios({
						url: '/base/equipment-check-order/delete?id=' + row.id,
						method: 'delete',
					});
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess('删除成功');
				})
				.catch(console.error);
		},
		handleDetail(row) {
			this.addOrUpdateVisible = true;
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(row.id, true);
			});
			// this.recordDetailVisible = true;
			// this.$nextTick(() => {
			// 	this.$refs.recordDetailDrawer.show({
			// 		id: row.id,
			// 		planMaintainWorker: row.planMaintainWorker,
			// 		maintainWorker: row.maintainWorker,
			// 	});
			// });
		},
		/** 导出按钮操作 */
		handleExport() {
			// 处理查询参数
			let params = { ...this.queryParams };
			params.pageNo = undefined;
			params.pageSize = undefined;
			this.$modal
				.confirm('是否确认导出所有巡检单?')
				.then(() => {
					this.exportLoading = true;
					return exportCheckOrderExcel(params);
				})
				.then((response) => {
					this.$download.excel(response, '设备巡检单.xls');
					this.exportLoading = false;
				})
				.catch(() => {});
		},
	},
};
</script>
