<template>
	<div class="mod-config">
		<el-form :inline="true" :model="dataForm" @keyup.enter.native="currentChangeHandle(1)">
			<el-form-item>
				<el-input v-model="dataForm.key" :placeholder="$t('eq.name') + ' / ' + $t('eq.code')" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="currentChangeHandle(1)">{{ $t('query') }}</el-button>
				<el-button v-if="$hasPermission('monitoring:equipmentplcconnect:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
			</el-form-item>
		</el-form>

		<base-table :page="pageIndex" :size="pageSize" :data="dataList" :table-head-configs="tableConfigs" :max-height="calcMaxHeight(8)" @operate-event="handleOperations" @refreshDataList="getDataList" />

		<el-pagination
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
			:current-page="pageIndex"
			:page-sizes="[10, 20, 50, 100]"
			:page-size="pageSize"
			:total="totalPage"
			layout="total, sizes, prev, pager, next, jumper"
		>
		</el-pagination>
		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" :configs="addOrUpdateConfigs" @refreshDataList="getDataList" @destory-dialog="addOrUpdateVisible = false" />
	</div>
</template>

<script>
import { calcMaxHeight } from '@/utils'
// import { timeFilter } from '@/utils/filters'
// import AddOrUpdate from './equipmentPlcConnect-add-or-update'
import AddOrUpdate from '@/components/base-dialog/addOrUpdate'
import i18n from '@/i18n'
import BaseTable from '@/components/base-table'
import TableOperateComponent from '@/components/base-table/components/operationComponent'
// import TableTextComponent from '@/components/base-table/components/detailComponent'
import { dictFilter } from '@/utils/filters'
// import axios from '@/utils/request.js'

const tableConfigs = [
	{ type: 'index', width: 100, name: i18n.t('index') },
	{ prop: 'lineName', name: i18n.t('pl.title') },
	{ prop: 'sectionName', name: i18n.t('ws.title') },
	{ prop: 'equName', name: i18n.t('equipment') },
	{ prop: 'equCode', name: i18n.t('eq.code') },
	{ prop: 'plcCode', name: i18n.t('eq.plccode') },
	{ prop: 'plcName', name: i18n.t('eq.plcname') },
	{ prop: 'plcIp', name: 'PLC IP' },
	{ prop: 'operations', name: i18n.t('handle'), fixed: 'right', width: 180, subcomponent: TableOperateComponent, options: ['edit', 'delete'] }
]

const UnitDictTypeId = '1557173812109242370'
const getUnitList = function() {
	const dl = JSON.parse(localStorage.getItem('dictList'))[UnitDictTypeId] || []
	return dl.map(item => ({ label: item.dictLabel, value: item.dictValue }))
}
const addOrUpdateConfigs = {
	type: 'dialog',
	infoUrl: '/monitoring/equipmentPlcConnect',
	fields: [
		{ name: 'equipmentId', label: i18n.t('equipment'), required: true, type: 'select', options: [] },
		{ name: 'plcId', label: i18n.t('eq.plcname'), required: true, type: 'select', options: [] }
	],
	operations: [
		{ name: 'cancel', url: true, showAlways: true },
		{ name: 'save', url: '/monitoring/equipmentPlcConnect', permission: 'monitoring:equipmentplcconnect:save', showOnEdit: false },
		{ name: 'update', url: '/monitoring/equipmentPlcConnect', permission: 'monitoring:equipmentplcconnect:update', showOnEdit: true }
	],
	subtable: {
		title: i18n.t('params.plctitle'),
		url: '/monitoring/equipmentPlcParam',
		relatedField: 'plcConId',
		tableConfigs: [
			{ type: 'index', width: 100, name: i18n.t('index') },
			{ prop: 'paramCode', name: i18n.t('params.code'), formField: true, rules: [{ required: true, message: i18n.t('required'), trigger: 'blur' }] },
			{ prop: 'paramName', name: i18n.t('params.name'), formField: true, rules: [{ required: true, message: i18n.t('required'), trigger: 'blur' }] },
			{ prop: 'paramAddress', name: i18n.t('paramUrl'), formField: true },
			{ prop: 'unitDictValue', name: i18n.t('unit'), filter: dictFilter(UnitDictTypeId), formField: true, formType: 'select', formOptions: getUnitList() },
			{ prop: 'minValue', name: i18n.t('min'), formField: true },
			{ prop: 'maxValue', name: i18n.t('max'), formField: true },
			{ prop: 'defaultValue', name: i18n.t('params.paramStdValue'), formField: true },
			{ prop: 'description', name: i18n.t('desc'), formField: true },
			{
				prop: 'enabled',
				name: i18n.t('enabled'),
				filter: val => [i18n.t('disable'), i18n.t('enable')][+val],
				// filter: val => ({0:i18n.t('disable'), 1:i18n.t('enable')}[+val]),
				rules: [{ required: true, message: i18n.t('required'), trigger: 'blur' }],
				formField: true,
				formType: 'select',
				formOptions: [
					{ value: 0, label: i18n.t('disable') },
					{ value: 1, label: i18n.t('enable') }
				]
			},
			{ prop: 'remark', name: i18n.t('remark'), formField: true },
			{
				prop: 'collection',
				name: i18n.t('collectOrNot'),
				filter: val => [i18n.t('notCollect'), i18n.t('collect')][+val],
				rules: [{ required: true, message: i18n.t('required'), trigger: 'blur' }],
				formField: true,
				formType: 'select',
				formOptions: [
					{ value: 0, label: i18n.t('notCollect') },
					{ value: 1, label: i18n.t('collect') }
				]
			},
			{ prop: 'operations', name: i18n.t('handle'), fixed: 'right', width: 180, subcomponent: TableOperateComponent, options: ['edit', 'delete'] }
		]
	}
}

export default {
	data() {
		return {
			addOrUpdateConfigs,
			calcMaxHeight,
			tableConfigs,
			dataForm: {
				key: ''
			},
			dataList: [],
			pageIndex: 1,
			pageSize: 10,
			totalPage: 0,
			dataListLoading: false,
			dataListSelections: [],
			addOrUpdateVisible: false
		}
	},
	components: {
		AddOrUpdate,
		BaseTable
	},
	activated() {
		this.getEqList()
		this.getPlcList()
		this.getDataList()
	},
	methods: {
		// 设备列表
		getEqList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipment/page'),
				method: 'get',
				params: this.$http.adornParams({
					// page: this.pageIndex,
					// limit: this.pageSize,
					// key: this.dataForm.key
				})
			}).then(({ data }) => {
				const eqConfig = this.addOrUpdateConfigs.fields.find(item => item.name === 'equipmentId')
				eqConfig.options = data.data?.list?.map(item => ({ value: item.id, label: item.name })) || []
			})
		},
		// plc 列表
		getPlcList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipmentPlc/page'),
				method: 'get',
				params: this.$http.adornParams({
					// page: this.pageIndex,
					// limit: this.pageSize,
					// key: this.dataForm.key
				})
			}).then(({ data }) => {
				const plcConfig = this.addOrUpdateConfigs.fields.find(item => item.name === 'plcId')
				plcConfig.options = data.data?.list?.map(item => ({ value: item.id, label: item.name })) || []
			})
		},
		handleOperations({ type, data: id }) {
			switch (type) {
				case 'edit':
					return this.addOrUpdateHandle(id)
				case 'delete':
					return this.deleteHandle(id)
			}
		},
		// 获取数据列表
		getDataList() {
			this.dataListLoading = true
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipmentPlcConnect/page'),
				method: 'get',
				params: this.$http.adornParams({
					page: this.pageIndex,
					limit: this.pageSize,
					key: this.dataForm.key
				})
			}).then(({ data }) => {
				if (data && data.code === 0) {
					this.dataList = data.data.list
					this.totalPage = data.data.total
				} else {
					this.dataList = []
					this.totalPage = 0
				}
				this.dataListLoading = false
			})
		},
		// 每页数
		sizeChangeHandle(val) {
			this.pageSize = val
			this.pageIndex = 1
			this.getDataList()
		},
		// 当前页
		currentChangeHandle(val) {
			this.pageIndex = val
			this.getDataList()
		},
		// 多选
		selectionChangeHandle(val) {
			this.dataListSelections = val
		},
		// 新增 / 修改
		addOrUpdateHandle(id) {
			this.addOrUpdateVisible = true
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(id)
			})
		},
		// 删除
		deleteHandle(id) {
			var ids = id
				? [id]
				: this.dataListSelections.map(item => {
						return item.id
				  })
			this.$confirm(`${i18n.t('prompt.info', { handle: id ? i18n.t('delete').toLowerCase() : i18n.t('deleteBatch').toLowerCase() })}`, i18n.t('prompt.title'), {
				confirmButtonText: i18n.t('confirm'),
				cancelButtonText: i18n.t('cancel'),
				type: 'warning'
			}).then(() => {
				this.$http({
					url: this.$http.adornUrl('/monitoring/equipmentPlcConnect'),
					method: 'delete',
					data: this.$http.adornData(ids, false, 'raw')
				}).then(({ data }) => {
					if (data && data.code === 0) {
						this.$message({
							message: i18n.t('prompt.success'),
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getDataList()
							}
						})
					} else {
						this.$message.error(data.msg)
					}
				})
			})
		}
	}
}
</script>
