<template>
	<div class="mod-config">
		<el-form :inline="true" :model="dataForm" :rules="dataFormRules" @keyup.enter.native="currentChangeHandle(1)" class="blueTip" size="small">
			<el-form-item>
				{{ $t('inspect.det') }}
			</el-form-item>
			<el-form-item>
				<!-- <el-input v-model="dataForm.key" :placeholder="$t('eq.name') + ' / ' + $t('eq.code')" clearable></el-input> -->
				<el-input v-model="dataForm.key" :placeholder="$t('inspect.det')" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button class="buttonColor" @click="currentChangeHandle(1)">{{ $t('search') }}</el-button>
				<!-- <el-button v-if="$hasPermission('monitoring:qualityInspectionBoxBtn:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button> -->
				<!-- <el-button v-if="$hasPermission('monitoring:equipment:export')" @click="exportHandle()">{{ $t('export') }}</el-button> -->
			</el-form-item>
		</el-form>

		<base-table
			:top-btn-config="topBtnConfig"
			:page="pageIndex"
			:size="pageSize"
			:data="dataList"
			:table-head-configs="tableConfigs"
			:max-height="calcMaxHeight(8)"
			@operate-event="handleOperations"
			@refreshDataList="getDataList"
			@clickTopBtn="clickTopBtn" />
		<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="addSuccess"
			@select-change="handleDialogSelectChange"
			@destory-dialog="handleDestroyDialog" />
	</div>
</template>

<script>
import i18n from '@/i18n'
import AddOrUpdate from '@/components/base-dialog/addOrUpdate'
// import AddOrUpdate from './equipment-add-or-update'
import BaseTable from '@/components/base-table'
import TableOperateComponent from '@/components/base-table/components/operationComponent'
// import TableTextComponent from '@/components/base-table/components/detailComponent'
// import CKEditor from 'ckeditor4-vue'
import { calcMaxHeight } from '@/utils'
import { timeFilter } from '@/utils/filters'
import { iteratee } from 'lodash'
// import Cookies from 'js-cookie'
const topBtnConfig = [
	{
		type: 'add',
		btnName: i18n.t('add')
	}
]
const tableConfigs = [
	{
		type: 'index',
		width: 100,
		name: i18n.t('index')
	},
	{
		prop: 'createTime',
		name: i18n.t('createTime'),
		filter: timeFilter
	},
	{ prop: 'inspectionDetContent', name: i18n.t('andeng.inspectContent') }, // name: '检测内容' },
	{ prop: 'keyValue', name: i18n.t('andeng.btnVal') }, // name: '按钮值' },
	{ prop: 'model', name: i18n.t('andeng.btnBoxModel') }, // name: '按钮盒模式' },

	{
		prop: 'operations',
		name: i18n.t('handle'),
		fixed: 'right',
		width: 180,
		subcomponent: TableOperateComponent,
		options: ['edit', 'delete']
	}
]

const addOrUpdateConfigs = {
	type: 'dialog',
	infoUrl: '/monitoring/qualityInspectionBoxBtn',
	fields: [
		// { name: 'productionId', label: i18n.t('eq.name'), required: true },
		{ name: 'productionId', label: i18n.t('pl.title'), required: true, type: 'select', options: [], relatedField: 'sectionId' },
		{ name: 'sectionId', label: i18n.t('ws.title'), required: true, type: 'select', options: [], isDisabled: true },
		{ name: 'model', label: i18n.t('andeng.btnBoxModel') },
		{
			// name: 'keyValue',
			// label: i18n.t('andeng.btnVal'),
			// required: true,
			// rules: [{ type: 'integer', trigger: 'blur', message: i18n.t('hints.integer'), transform: (val) => Number(val) }]

			// keyValue: [
			// 	{
			// 		type: 'number',
			// 		message: i18n.t('validate.keyValueWarning'),
			// 		trigger: 'blur',
			// 		transform(value) {
			// 			if (value) {
			// 				// 将输入的转为数字
			// 				var val = Number(value)
			// 				// 正则校验输入的数字是否在0-128之内并且属于整数
			// 				if (/^(?:[1-9]?\d|128)$/.test(val)) return val
			// 				// 返回false即为校验失败
			// 				return false
			// 			}
			// 		}
			// 	}
			// ]
			name: 'keyValue',
			label: i18n.t('andeng.btnVal'),
			required: true,
			rules: [
				{
					type: 'integer',
					trigger: 'blur',
					message: i18n.t('validate.keyValueWarning'),
					transform(value) {
						if (value) {
							// 将输入的转为数字
							var val = Number(value)
							// 正则校验输入的数字是否在[0-100]之内并且属于整数
							if (/^(?:[1-9]?\d|100)$/.test(val)) return val
							// 返回false即为校验失败
							return false
						}
					}
				}
			]
		},
		{
			name: 'inspectionDetContent',
			label: i18n.t('andeng.inspectContent'),
			required: true,
			type: 'select',
			options: []
		}
	],
	operations: [
		{ name: 'cancel', showAlways: true },
		{
			name: 'save',
			url: '/monitoring/qualityInspectionBoxBtn',
			permission: 'monitoring:qualityInspectionBoxBtn:save',
			showOnEdit: false
		},
		{
			name: 'update',
			url: '/monitoring/qualityInspectionBoxBtn',
			permission: 'monitoring:qualityInspectionBoxBtn:update',
			showOnEdit: true
		}
	]
}

export default {
	data() {
		return {
			topBtnConfig,
			calcMaxHeight,
			tableConfigs,
			addOrUpdateConfigs,
			dataForm: {
				key: '',
				inspectionDetId: ''
			},
			dataList: [],
			pageIndex: 1,
			pageSize: 10,
			totalPage: 0,
			dataListLoading: false,
			dataListSelections: [],
			addOrUpdateVisible: false,
			dataFormRules: {
				keyValue: [
					{
						type: 'number',
						message: i18n.t('validate.keyValueWarning'),
						trigger: 'blur',
						transform(value) {
							if (value) {
								// 将输入的转为数字
								var val = Number(value)
								// 正则校验输入的数字是否在0-128之内并且属于整数
								if (/^(?:[1-9]?\d|128)$/.test(val)) return val
								// 返回false即为校验失败
								return false
							}
						}
					}
				]
			}
		}
	},
	components: {
		AddOrUpdate,
		BaseTable
	},
	activated() {
		this.getInspectionContentList()
		this.getDataList()
		this.getPlList()
		this.getWsList()
	},
	methods: {
		// destroy dialog
		handleDestroyDialog() {
			this.$set(this.addOrUpdateConfigs.fields[1], 'isDisabled', true)
			setTimeout(() => {
				this.addOrUpdateVisible = false
			}, /** after dialog animated */ 200)
		},
		// 获取产线列表，用于刷新工段列表
		getPlList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/productionLine/list'),
				method: 'get'
			}).then(({ data: res }) => {
				const plConfig = this.addOrUpdateConfigs.fields.find((item) => item.name === 'productionId')
				plConfig.options =
					res.data?.map((item) => ({
						value: item.id,
						label: item.name
					})) || []
			})
		},
		// 获取工段列表
		getWsList(id) {
			let params = {
				page: 1,
				limit: 999
			}
			if (id) {
				params.lineId = id
			}
			this.$http({
				url: this.$http.adornUrl('/monitoring/workshopSection/page'),
				method: 'get',
				params: this.$http.adornParams(params)
			}).then(({ data: res }) => {
				const wsConfig = this.addOrUpdateConfigs.fields.find((item) => item.name === 'sectionId')
				wsConfig.options =
					res.data?.list?.map((item) => ({
						value: item.id,
						label: item.name
					})) || []
			})
		},
		// 获取设备类型列表
		getTypeList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipmentType/page'),
				method: 'get',
				params: this.$http.adornParams({
					// page: this.pageIndex,
					// limit: this.pageSize,
					// key: this.dataForm.key
				})
			}).then(({ data }) => {
				const eqTypeConfig = this.addOrUpdateConfigs.fields.find((item) => item.name === 'equipmentTypeId')
				eqTypeConfig.options =
					data.data?.list?.map((item) => ({
						value: item.id,
						label: item.name
					})) || []
			})
		},
		// 获取设备分组列表
		getGroupList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipmentGroup/page'),
				method: 'get',
				params: this.$http.adornParams({
					// page: this.pageIndex,
					// limit: this.pageSize,
					// key: this.dataForm.key
				})
			}).then(({ data }) => {
				const groupConfig = this.addOrUpdateConfigs.fields.find((item) => item.name === 'groupId')
				groupConfig.options =
					data.data?.list?.map((item) => ({
						value: item.id,
						label: item.name
					})) || []
			})
		},
		// 获取数据列表
		getDataList() {
			this.dataListLoading = true
			this.$http({
				url: this.$http.adornUrl('/monitoring/qualityInspectionBoxBtn/page'),
				method: 'get',
				// key 查询
				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.dataList = new Array(20).fill('1')
					// console.log('data list', this.dataList)
					this.totalPage = data.data.total
				} else {
					this.dataList = []
					this.totalPage = 0
				}
				this.dataListLoading = false
			})
		},
		// 获取产检测内容列表
		getInspectionContentList() {
			this.$http({
				url: this.$http.adornUrl('/monitoring/qualityInspectionDet/page'),
				method: 'get',
				params: this.$http.adornParams({
					limit: 999,
					page: 1
				})
			}).then(({ data: res }) => {
				if (res && res.code === 0) {
					this.addOrUpdateConfigs.fields.forEach((item) => {
						// console.log('item',item)
						// console.log('res',res)
						if (item.name === 'inspectionDetContent') item.options = res.data.list.map((item) => ({ label: item.content, value: item.content, inspectionDetId: item.code }))
						// console.log('item',item)
					})
				} else {
					this.addOrUpdateConfigs.fields.forEach((item) => {
						if (item.name === 'inspectionDetContent') item.options.splice(0)
					})
				}
			})
		},
		// 每页数
		sizeChangeHandle(val) {
			this.pageSize = val
			this.pageIndex = 1
			this.getDataList()
		},
		// 当前页
		currentChangeHandle(val) {
			this.pageIndex = val
			this.getDataList()
		},
		// 多选
		selectionChangeHandle(val) {
			this.dataListSelections = val
		},
		// 对话框里的某个选择改变了
		async handleDialogSelectChange({ name, id }) {
			switch (name) {
				case 'productionId':
					// this.getWsList(id)
					if (name === 'productionId') {
						// 如果选择了产线，就依据此更新工单的选项
						if (id) {
							this.$set(this.addOrUpdateConfigs.fields[1], 'isDisabled', false)
						} else {
							this.$set(this.addOrUpdateConfigs.fields[1], 'isDisabled', true)
						}
						await this.getWsList(id)
					}
				case 'inspectionDetContent':
					// this.dataForm.inspectionDetId = id
					// console.log(id)
					// console.log(this.addOrUpdateConfigs.fields[4].options)
					for (var i = 0; i < this.addOrUpdateConfigs.fields[4].options.length; i++) {
						if (this.addOrUpdateConfigs.fields[4].options[i].label == id) {
							this.dataForm.inspectionDetId = this.addOrUpdateConfigs.fields[4].options[i].inspectionDetId
							this.addOrUpdateConfigs.fields.inspectionDetId = this.addOrUpdateConfigs.fields[4].options[i].inspectionDetId
						}
					}
					console.log('dataForm', this.dataForm)
					console.log('addOrUpdateConfigs', this.addOrUpdateConfigs.fields)
			}
		},
		addSuccess() {
			this.getDataList()
			this.$set(this.addOrUpdateConfigs.fields[1], 'options', [])
			this.$set(this.addOrUpdateConfigs.fields[1], 'isDisabled', true)
		},
		handleOperations({ type, data: id }) {
			switch (type) {
				case 'view-detail':
					// const { name, code } = this.dataList.find(item => item.id === id)
					// this.$router.push({
					// 	name: 'monitoring-equipmentAdd',
					// 	params: {
					// 		isdetail: true,
					// 		equipmentId: id
					// 	}
					// })
					// break
					return this.addOrUpdateHandle(id, true)
				case 'edit':
					return this.addOrUpdateHandle(id)
				case 'delete':
					return this.deleteHandle(id)
			}
		},
		exportHandle() {
			// this.$http.get(this.$http.adornUrl('/monitoring/equipment/export')).then(({ data: res }) => {
			this.$http({
				url: this.$http.adornUrl('/monitoring/equipment/export'),
				method: 'get',
				responseType: 'blob'
			}).then((res) => {
				let fileName = 'equipment-list.xls'
				if (res.headers['content-disposition']) {
					const contentDisposition = res.headers['content-disposition']
					fileName = contentDisposition.slice(contentDisposition.indexOf('filename=') + 9)
				}

				fileName = decodeURIComponent(fileName)

				const blob = new Blob([res.data])

				if ('download' in document.createElement('a')) {
					const alink = document.createElement('a')
					alink.download = fileName
					alink.style.display = 'none'
					alink.target = '_blank'
					alink.href = URL.createObjectURL(blob)
					document.body.appendChild(alink)
					alink.click()
					URL.revokeObjectURL(alink.href)
					document.body.removeChild(alink)
				} else {
					navigator.msSaveBlob(blob, fileName)
				}
			})
		},
		// 新增 / 修改
		addOrUpdateHandle(id, isdetail = false) {
			this.addOrUpdateVisible = true
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(id, isdetail)
			})
			// this.$router.push({
			// 	name: 'monitoring-equipmentAdd',
			// 	params: {
			// 		equipmentId: id
			// 	}
			// })
		},
		clickTopBtn() {
			this.addOrUpdateVisible = true
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init()
			})
		},
		// 删除
		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/qualityInspectionBoxBtn'),
					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>

<style>
.blueTip::before {
	display: inline-block;
	content: '';
	width: 4px;
	height: 24px;
	background: #0b58ff;
	border-radius: 1px;
	margin-right: 8px;
	margin-top: 4px;
}
.buttonColor {
	color: #fff;
	background: #0b58ff;
}
</style>
