<template>
	<div class="app-container">
		<!-- 搜索工作栏 -->
		<SearchBar
			:formConfigs="searchBarFormConfig"
			ref="search-bar"
			@headBtnClick="handleSearchBarBtnClick" />

		<!-- 列表 -->
		<base-table
			:table-props="tableProps"
			:page="queryParams.pageNo"
			:limit="queryParams.pageSize"
			:table-data="list"
			@emitFun="handleEmitFun">
			<method-btn
				v-if="tableBtn.length"
				slot="handleBtn"
				label="操作"
				:width="120"
				:method-list="tableBtn"
				@clickBtn="handleTableBtnClick" />
		</base-table>

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

		<!-- 对话框(添加 / 修改) -->
		<base-dialog
			:dialogTitle="title"
			:dialogVisible="open"
			width="700px"
			@close="cancel"
			@cancel="cancel"
			@confirm="submitForm">
			<DialogForm v-if="open" ref="form" v-model="form" :rows="rows" />
		</base-dialog>

		<!-- 抽屉 详情 -->
		<BasicDrawer
			v-if="editVisible"
			ref="drawer"
			:default-mode="editMode"
			:info-data="alarmForm"
			:sections="[
				{
					name: '基本信息',
					key: 'base',
					rows: drawerBaseInfoRows,
				},
				{
					name: '属性列表',
					key: 'attrs',
					props: drawerListProps,
					url: '/base/equipment-plc-param/page',
					urlCreate: '/base/equipment-plc-param/create',
					urlUpdate: '/base/equipment-plc-param/update',
					urlDelete: '/base/equipment-plc-param/delete',
					urlDetail: '/base/equipment-plc-param/get',
					queryParams: {
						connectId: alarmForm.id,
						pageNo: 1,
						pageSize: 10,
					},
					tableBtn: [
						this.$auth.hasPermi('base:equipment-plc-param:update')
							? {
									type: 'edit',
									btnName: '修改',
							  }
							: undefined,
						this.$auth.hasPermi('base:equipment-plc-param:delete')
							? {
									type: 'delete',
									btnName: '删除',
							  }
							: undefined,
					].filter((v) => v),
					allowAdd: true,
				},
			]"
			@refreshDataList="getList"
			@cancel="editVisible = false"
			@destroy="editVisible = false" />
	</div>
</template>

<script>
import {
	createEquipmentPlcConnect,
	updateEquipmentPlcConnect,
	deleteEquipmentPlcConnect,
	getEquipmentPlcConnect,
	getEquipmentPlcConnectPage,
	exportEquipmentPlcConnectExcel,
} from '@/api/base/equipmentPlcConnect';
import moment from 'moment';
import basicPageMixin from '@/mixins/lb/basicPageMixin';
// import './http';
import BasicDrawer from './components/BasicDrawer.vue';
import { publicFormatter } from '@/utils/dict';

export default {
	name: 'EquipmentPlcConnect',
	mixins: [basicPageMixin],
	components: { BasicDrawer },
	data() {
		return {
			searchBarKeys: ['equipmentId', 'plcId'],
			// tableBtn: [
			// 	this.$auth.hasPermi('base:equipment-plc:update')
			// 		? {
			// 				type: 'edit',
			// 				btnName: '修改',
			// 		  }
			// 		: undefined,
			// 	this.$auth.hasPermi('base:equipment-plc:delete')
			// 		? {
			// 				type: 'delete',
			// 				btnName: '删除',
			// 		  }
			// 		: undefined,
			// ].filter((v) => v),
			tableBtn: [
				{
					type: 'detail',
					btnName: '参数绑定',
				},
				{
					type: 'edit',
					btnName: '修改',
				},
				// {
				// 	type: 'params-bind',
				// 	btnName: '参数绑定',
				// },
				{
					type: 'delete',
					btnName: '删除',
				},
			],
			tableProps: [
				// {
				// 	prop: 'createTime',
				// 	label: '添加时间',
				// 	fixed: true,
				// 	width: 180,
				// 	filter: (val) => moment(val).format('yyyy-MM-DD HH:mm:ss'),
				// },
				{ prop: 'productionLine', label: '产线' },
				{ prop: 'workshopSection', label: '工段' },
				{ prop: 'equipmentName', label: '设备名' },
				{ prop: 'equipmentCode', label: '设备编码' },
				{ prop: 'plcCode', label: '关联表编码' },
				{ prop: 'plcTableName', label: '关联表名' },
				{ prop: 'plcName', label: '标识名称' },
				{ prop: 'bindingParameters', label: '绑定参数数量' },
				// {
				// 	_action: 'params-bind',
				// 	label: '查看绑定',
				// 	subcomponent: {
				// 		props: ['injectData'],
				// 		render: function (h) {
				// 			const _this = this;
				// 			return h(
				// 				'el-button',
				// 				{
				// 					props: { type: 'text' },
				// 					on: {
				// 						click: function () {
				// 							console.log('inejctdata', _this.injectData);
				// 							_this.$emit('emitData', {
				// 								action: _this.injectData._action,
				// 								payload: _this.injectData,
				// 							});
				// 						},
				// 					},
				// 				},
				// 				'查看绑定'
				// 			);
				// 		},
				// 	},
				// },
			],
			searchBarFormConfig: [
				{
					type: 'select',
					label: '设备名',
					placeholder: '请选择设备',
					param: 'equipmentId',
					selectOptions: [],
				},
				{
					type: 'select',
					label: '编码',
					placeholder: '请选择编码',
					param: 'plcId',
					selectOptions: [],
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'separate',
				},
				{
					// type: this.$auth.hasPermi('base:equipment-plc:create')
					// 	? 'button'
					// 	: '',
					type: 'button',
					btnName: '新增',
					name: 'add',
					plain: true,
					color: 'success',
				},
				// {
				// 	type: this.$auth.hasPermi('base:equipment-plc:export') ? 'button' : '',
				// 	btnName: '导出',
				// 	name: 'export',
				// 	color: 'warning',
				// },
			],
			rows: [
				[
					{
						select: true,
						label: '关联表名',
						prop: 'plcId',
						labelKey: `plcTableName`,
						url: '/base/equipment-plc/listAll',
						rules: [{ required: true, message: '不能为空', trigger: 'blur' }],
						bind: {
							filterable: true,
						},
					},
				],
				[
					{
						select: true,
						label: '设备',
						prop: 'equipmentId',
						url: '/base/equipment/page?pageNo=1&pageSize=99',
						rules: [{ required: true, message: '不能为空', trigger: 'blur' }],
						bind: {
							filterable: true,
						},
					},
				],
			],
			open: false,
			// 查询参数
			queryParams: {
				pageNo: 1,
				pageSize: 10,
				plcId: null,
				equipmentId: null,
			},
			// 表单参数
			form: {},
			// 查看绑定配置
			editVisible: false,
			editMode: '',
			drawerBaseInfoRows: [
				[
					{
						input: true,
						label: '设备名',
						prop: 'equipmentName',
						rules: [{ required: true, message: '不能为空', trigger: 'blur' }],
						// bind: {
						// 	disabled: this.editMode == 'detail', // some condition, like detail mode...
						// }
					},
					{
						input: true,
						label: '关联表名',
						prop: 'plcTableName',
						// url: '/base/equipment/getCode',
					},
				],
			],
			drawerListProps: [
				{ prop: 'plcParamName', label: '参数列名' },
				{ prop: 'name', label: '参数名称' },
				{
					prop: 'unit',
					label: '单位',
					filter: publicFormatter('unit_dict'),
				},
				{
					prop: 'equipmentParamType',
					label: '设备参数类型',
					filter: (val) =>
						val != null
							? ['', '一般参数', '工艺参数', '报警参数', ''][val]
							: '-',
				},
				{
					prop: 'productionParamType',
					label: '生产参数类型',
					filter: (val) =>
						val != null
							? // ? ['', '进片数量', '出片数量', '破损数量', '无类型', ''][val]
							  ['', '进口计数', '出口计数', '损耗计数', '无类型', ''][val]
							: '-',
				},
				{
					prop: 'collection',
					label: '是否采集',
					filter: (val) => (val != null ? ['否', '是'][val] : '-'),
				},
				{ prop: 'minValue', label: '最小值' },
				{ prop: 'maxValue', label: '最大值' },
				{ prop: 'defaultValue', label: '标准值' },
				{ prop: 'description', label: '描述' },
				{ prop: 'remark', label: '备注' },
			],
			alarmForm: {
				id: undefined,
				equipmentName: undefined,
				plcTableName: undefined,
			},
		};
	},
	created() {
		this.getList();
		this.initSearchOptions();
	},
	methods: {
		async getEquipmentOptions() {
			const res = await this.$axios({
				url: '/base/equipment/listAll',
				method: 'get',
			});
			return res.data;
		},

		async getPlcOptions() {
			const res = await this.$axios({
				url: '/base/equipment-plc/listAll',
				method: 'get',
			});
			return res.data;
		},

		/** 初始化查询条件 */
		async initSearchOptions() {
			Promise.all([this.getEquipmentOptions(), this.getPlcOptions()]).then(
				([eqList, plcList]) => {
					this.searchBarFormConfig[0].selectOptions = eqList.map((item) => {
						return {
							name: item.name,
							id: item.id,
						};
					});
					this.searchBarFormConfig[1].selectOptions = plcList.map((item) => {
						return {
							name: item.name,
							id: item.id,
						};
					});
				}
			);
		},
		/** 覆盖 handleEmitFun 的默认实现 */
		handleEmitFun({ action, payload }) {
			switch (action) {
				case 'params-bind':
					this.reset();
					const {
						id,
						equipmentName,
						equipmentId,
						plcId,
						plcName,
						plcTableName,
					} = payload;
					// console.log('Cha看绑定参数弹窗', id, equipmentName, plcTableName);
					this.$router.push({
						name: 'EquipmentPlcParam',
						params: {
							id,
							equipmentName,
							plcTableName,
						},
					});
					break;
			}
		},

		/** 查询列表 */
		getList() {
			this.loading = true;
			// 执行查询
			getEquipmentPlcConnectPage(this.queryParams).then((response) => {
				this.list = response.data.list;
				this.total = response.data.total;
				this.loading = false;
			});
		},
		/** 取消按钮 */
		cancel() {
			this.open = false;
			this.reset();
		},
		/** 表单重置 */
		reset() {
			this.form = {
				id: undefined,
				plcId: undefined,
				equipmentId: undefined,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNo = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm');
			this.handleQuery();
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = '添加设备与实时采集关系表（一对多）';
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id;
			getEquipmentPlcConnect(id).then((response) => {
				this.form = response.data;
				this.open = true;
				this.title = '修改设备与实时采集关系表（一对多）';
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) {
					return;
				}
				// 修改的提交
				if (this.form.id != null) {
					updateEquipmentPlcConnect(this.form).then((response) => {
						this.$modal.msgSuccess('修改成功');
						this.open = false;
						this.getList();
					});
					return;
				}
				// 添加的提交
				createEquipmentPlcConnect(this.form).then((response) => {
					this.$modal.msgSuccess('新增成功');
					this.open = false;
					this.getList();
				});
			});
		},

		// 查看报警
		handleDetail(row) {
			// debugger;
			const {
				id,
				bindingParameters,
				equipmentCode,
				equipmentId,
				equipmentName,
				plcCode,
				plcId,
				plcName,
				plcTableName,
				productionLine,
				workshopSection,
			} = row;
			// 打开抽屉
			this.editMode = 'detail';
			this.alarmForm.id = id;
			this.alarmForm.plcTableName = plcTableName; // 关联表名
			this.alarmForm.equipmentName = equipmentName;
			this.editVisible = true;
			this.$nextTick(() => {
				this.$refs['drawer'].init();
			});
		},

		/** 删除按钮操作 */
		handleDelete(row) {
			const id = row.id;
			this.$modal
				.confirm('是否删除该配置?')
				.then(function () {
					return deleteEquipmentPlcConnect(id);
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess('删除成功');
				})
				.catch(() => {});
		},

		/** 导出按钮操作 */
		handleExport() {
			// 处理查询参数
			let params = { ...this.queryParams };
			params.pageNo = undefined;
			params.pageSize = undefined;
			this.$modal
				.confirm('是否确认导出所有设备与实时采集关系表（一对多）数据项?')
				.then(() => {
					this.exportLoading = true;
					return exportEquipmentPlcConnectExcel(params);
				})
				.then((response) => {
					this.$download.excel(response, '设备与实时采集关系表（一对多）.xls');
					this.exportLoading = false;
				})
				.catch(() => {});
		},
	},
};
</script>
