<template>
	<el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="550px">
		<el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
			<el-form-item label="设备" prop="deviceid">
				<!-- <el-input v-model="form.deviceid" style="width: 370px;"/>-->
				<!-- <el-select v-model="form.deviceid" clearable placeholder="请选择设备" class="filter-item" style="width: 370px" @change="loaditem()">
					<el-option v-for="item in devices" :key="item.deviceid" :label="item.name" :value="item.deviceid" />
				</el-select> -->
				<el-select v-model="form.deviceid" clearable placeholder="请选择设备" class="filter-item" style="width: 370px" @change="loaditem()">
					<el-option v-for="item in devices" :key="item.deviceid" :label="item.name" :value="item.deviceid" />
				</el-select>
			</el-form-item>
			<el-form-item label="检测项" prop="item">
				<!--<el-input v-model="form.item" style="width: 370px;"/>-->
				<el-select v-model="form.item" :disabled="deviceidflag ? false : true" clearable placeholder="请选择检测项" class="filter-item" style="width: 370px">
					<el-option v-for="item in items" :key="item.code" :label="item.subject" :value="item.code" />
				</el-select>
			</el-form-item>
			<el-form-item label="控制名称" prop="name">
				<el-input v-model="form.name" style="width: 370px" />
			</el-form-item>
			<el-form-item label="通知消息" prop="msg">
				<el-input v-model="form.msg" style="width: 370px" />
			</el-form-item>
			<el-form-item label="控制类型">
				<!--<el-input v-model="form.warntype" style="width: 370px;"/>-->
				<el-radio-group v-model="form.warntype" size="mini" style="width: 370px">
					<!--<el-radio-button label="1">数值报警</el-radio-button>
          <el-radio-button label="0">开关报警</el-radio-button>-->
					<el-radio-button label="2">智能控制</el-radio-button>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.warntype === '0'" label="开关状态">
				<!--<el-input v-model="form.state" style="width: 370px;"/>-->
				<el-radio v-for="item in dictMap.radiostatus" :key="item.id" v-model="form.state" :label="item.value">{{ item.label }}</el-radio>
			</el-form-item>
			<el-card v-if="form.warntype === '1' || form.warntype === '2'" shadow="hover" class="box-card">
				<el-form-item v-if="form.warntype === '1' || form.warntype === '2'" label="控制值下限">
					<el-input v-model="form.min" style="width: 370px" />
				</el-form-item>
				<el-form-item v-if="form.warntype === '2'" label="超下限控制器">
					<el-select v-model="form.rMin" :disabled="isAdd ? false : true" clearable placeholder="请选择控制器" class="filter-item" style="width: 370px" @change="loadwaymin">
						<el-option v-for="(item, index) in firData" :key="index" :label="item.changeName" :value="item.changeName" />
					</el-select>
				</el-form-item>
				<el-table height="500" v-loading="loadingtabmin" v-if="form.warntype === '2'" :data="warnwaysmin" :row-class-name="tableRowClassName" size="small" style="width: 100%; text-align: center">
					<!--<el-table-column prop="deviceid" label="设备ID" min-width="130%"/>-->
					<!--<el-table-column prop="wayname" label="支路名称" />-->
					<el-table-column prop="changeValve" label="支路名称">
						<!-- <template slot-scope="scope">
							<div v-for="item in deviceWays" :key="item.id">
								<div v-if="parseInt(scope.row.nt) === item.id">{{ item.wayname }}</div>
							</div>
						</template> -->
					</el-table-column>
					<el-table-column prop="ieName" label="支路" />
					<el-table-column prop="status" label="状态" align="center">
						<template slot-scope="scope">
							<el-switch v-loading.fullscreen.lock="false" v-model="scope.row.status" active-value="1" inactive-value="0" active-text="开" inactive-text="关" />
						</template>
					</el-table-column>
					<el-table-column label="是否控制" align="center">
						<template slot-scope="scope">
							<!--<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteway(scope.row, scope)"/>-->
							<el-switch v-loading.fullscreen.lock="false" v-model="scope.row.valid" value="true" active-value="1" inactive-value="0" active-text="是" inactive-text="否" @change="changeDisablemin(scope.row, scope)" />
						</template>
					</el-table-column>
				</el-table>
			</el-card>
			<el-card v-if="form.warntype === '1' || form.warntype === '2'" shadow="hover" class="box-card">
				<el-form-item v-if="form.warntype === '1' || form.warntype === '2'" label="控制值上限">
					<el-input v-model="form.max" style="width: 370px" />
				</el-form-item>
				<el-form-item v-if="form.warntype === '2'" label="超上限控制器">
					<el-select v-model="form.rMax" :disabled="isAdd ? false : true" clearable placeholder="请选择控制器" class="filter-item" style="width: 370px" @change="loadwaymax">
						<el-option v-for="(item, index) in firData" :key="index" :label="item.changeName" :value="item.changeName" />
					</el-select>
				</el-form-item>
				<el-table height="500" v-loading="loadingtabmax" v-if="form.warntype === '2'" :data="warnwaysmax" :row-class-name="tableRowClassName" size="small" style="width: 100%; text-align: center">
					<!--<el-table-column prop="deviceid" label="设备ID" min-width="130%"/>-->
					<!--<el-table-column prop="wayname" label="支路名称" />-->
					<el-table-column prop="changeValve" label="支路名称">
						<!-- <template slot-scope="scope">
							<div v-for="item in deviceWays" :key="item.id">
								<div v-if="parseInt(scope.row.nt) === item.id">{{ item.wayname }}</div>
							</div>
						</template> -->
					</el-table-column>
					<el-table-column prop="ieName" label="支路" />
					<el-table-column prop="status" label="状态" align="center">
						<template slot-scope="scope">
							<el-switch v-loading.fullscreen.lock="false" v-model="scope.row.status" active-value="1" inactive-value="0" active-text="开" inactive-text="关" @change="changeDisablemax(scope.row, scope)" />
						</template>
					</el-table-column>
					<el-table-column label="是否控制" align="center">
						<template slot-scope="scope">
							<!--<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteway(scope.row, scope)"/>-->
							<el-switch v-loading.fullscreen.lock="false" v-model="scope.row.valid" value="true" active-value="1" inactive-value="0" active-text="是" inactive-text="否" @change="changeDisablemax(scope.row, scope)" />
						</template>
					</el-table-column>
				</el-table>
			</el-card>
			<el-form-item label="是否启用">
				<!--<el-input v-model="form.enable" style="width: 370px;"/> -->
				<!--<el-option v-for="item in dictMap.isnot" :key="item.value" :label="item.label" :value="item.value"/>-->
				<el-radio v-for="item in dictMap.isnot" :disabled="isAdd ? true : false" :key="item.id" v-model="form.enable" :label="item.value">{{ item.label }}</el-radio>
			</el-form-item>
			<!--<el-form-item label="创建时间" >
        <el-input v-model="form.createTime" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="更新时间" >
        <el-input v-model="form.updateTime" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="备注" >
        <el-input v-model="form.nt" style="width: 370px;"/>
      </el-form-item>-->
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button type="text" @click="cancel">取消</el-button>
			<el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { add, edit } from '@/api/sWarn'
import { loaddevice } from '@/api/sDevice'
import { loadByWarnidAndFlag } from '@/api/sWarnWay'
import initDict from '@/mixins/initDict'
import { selectAll } from '@/api/sItem'
import { queryAllRelayByUseridNoPage } from '@/api/sDevice'
import { loadTaskwayByDeviceid, sDeviceWayNoPage } from '@/api/sDeviceWay'
import { mapGetters } from 'vuex'
import { reqApi } from '@/api/sfyt.js'

export default {
	mixins: [initDict],
	props: {
		isAdd: {
			type: Boolean,
			required: true,
		},
	},
	data() {
		return {
			cur_page: 0,
			loading: false,
			dialog: false,
			deviceparam: '',
			devices: '',
			items: [],
			itemparam: '',
			deviceidflag: false,
			loadingtabmin: false,
			loadingtabmax: false,
			warnwaysmin: [],
			warnwaysmax: [],
			valueseldatamin: [],
			valueseldatamax: [],
			valueseldata: '',
			valueseldata1: '',
			deviceWays: [],
			relays: '',
			firData: [],

			form: {
				id: '',
				deviceid: '',
				// relayidmin: '',
				// relayidmax: '',
				rMin: '',
				rMax: '',
				item: '',
				warntype: '2',
				state: '1',
				min: '',
				max: '',
				name: '',
				msg: '',
				enable: '1',
				deviceName: '',
				upData: [],
				lowData: [],
			},

			rules: {
				deviceid: [{ required: true, message: '请选择设备信息', trigger: 'blur' }],
				item: [{ required: true, message: '请选择检测项信息', trigger: 'blur' }],
				name: [{ required: true, message: '请输入报警名称', trigger: 'blur' }],
				msg: [{ required: true, message: '请输入报警消息', trigger: 'blur' }],
			},
		}
	},
	computed: {
		...mapGetters(['user']),
	},
	created() {
		this.$nextTick(() => {
			// this.init()
			this.getRelay()
			this.loaddevice()
			this.getDictMap('isnot,radiostatus')
			this.selectAllForm()
			this.sDeviceWayNoPage()
			this.getChangeData()
		})
	},
	methods: {
		//获取数据
		getChangeData() {
			let param = {}
			param.username = this.user.username

			reqApi.sfytLogin(param).then(res => {
				if (res.Code == '200') {
					this.firData = res.Data
				} else {
				}
			})
		},
		cancel() {
			this.resetForm()
		},
		getRelay() {
			queryAllRelayByUseridNoPage()
				.then(res => {
					this.relays = res
				})
				.catch(err => {
					this.loading = false
				})
		},
		tableRowClassName({ row, rowIndex }) {
			if (row.valid === '0') {
				return 'danger-row'
			} else {
				if (row.status === '0') {
					return 'warning-row'
				} else if (row.status === '1') {
					return 'success-row'
				}
			}
			return ''
		},
		loadwaymin(rows) {
			if (this.form.rMin === '') {
				this.warnwaysmin = []
			} else {
				this.form.rMin = rows
				let param = {}
				param.changename = rows

				reqApi.sfytDiv(param).then(res => {
					this.warnwaysmin = res.Data
				})
			}
		},
		loadwaymax(rows) {
			if (this.form.rMax === '') {
				this.warnwaysmax = []
			} else {
				this.form.rMax = rows
				let param = {}
				param.changename = rows
				reqApi.sfytDiv(param).then(res => {
					this.warnwaysmax = res.Data
				})
			}
		},

		loadMinByWarnid() {
			var flag = 'min'
			let param = {}
			param.id = this.form.id
			reqApi.aiEditTab(param).then(res => {
				this.warnwaysmin = res.lowData
				this.form.lowData = this.warnwaysmin
			})
			// loadByWarnidAndFlag(this.form.id, flag)
			// 	.then(res => {
			// 		this.warnwaysmin = res
			// 	})
			// 	.catch(err => {
			// 		// this.loading = false
			// 		console.log(err.response.data.message)
			// 	})
		},
		loadMaxByWarnid() {
			let param = {}
			param.id = this.form.id
			reqApi.aiEditTab(param).then(res => {
				this.warnwaysmax = res.upData
				this.form.upData = this.warnwaysmax
			})
			// var flag = 'max'
			// loadByWarnidAndFlag(this.form.id, flag)
			// 	.then(res => {
			// 		this.warnwaysmax = res
			// 	})
			// 	.catch(err => {
			// 		// this.loading = false
			// 		console.log(err.response.data.message)
			// 	})
		},
		sDeviceWayNoPage() {
			sDeviceWayNoPage()
				.then(res => {
					this.deviceWays = res
				})
				.catch(err => {
					// this.loading = false
					console.log(err.response.data.message)
				})
		},
		returnMsg(msg) {
			this.$notify({
				title: msg,
				type: 'warning',
				duration: 2500,
			})
		},
		doSubmit() {
			this.$refs['form'].validate(valid => {
				if (valid) {
					this.loading = true
					if (this.form.warntype === '1') {
						// 清空开关
						this.form.state = ''
						// 清空智能控制
						this.form.relayidmin = ''
						this.form.relayidmax = ''
						this.warnwaysmin = []
						this.warnwaysmax = []
					}
					if (this.form.warntype === '0') {
						// 清空数值
						this.form.min = ''
						this.form.max = ''
						// 清空智能控制
						this.form.relayidmin = ''
						this.form.relayidmax = ''
						this.warnwaysmin = []
						this.warnwaysmax = []
					}
					if (this.form.warntype === '1' || this.form.warntype === '2') {
						// min max不能同时为空
						if (this.form.min === '' && this.form.max === '') {
							this.loading = false
							this.returnMsg('请至少输入报警值下限或者上限！')
							return false
						}
						if (this.form.min !== '' && this.form.min !== null) {
							if (!Number(this.form.min)) {
								this.loading = false
								this.returnMsg('报警值下限：请输入正确格式数字！')
								return false
							}
						}
						if (this.form.max !== '' && this.form.max !== null) {
							if (!Number(this.form.max)) {
								this.loading = false
								this.returnMsg('报警值上限：请输入正确格式数字！')
								return false
							}
						}
						if (this.form.warntype === '2') {
							console.log(this.form)
							// 清空开关
							this.form.state = ''
							// 验证min
							if (this.form.min !== '' && this.form.min !== null) {
								if (this.form.rMin === '' || this.form.rMin === null) {
									this.loading = false
									this.returnMsg('超下限控制器：请选择控制器！')
									return false
								}
							}
							// 验证max
							if (this.form.max !== '' && this.form.max !== null) {
								if (this.form.rMax === '' || this.form.rMax === null) {
									this.loading = false
									this.returnMsg('超上限控制器：请选择控制器！')
									return false
								}
							}
						}
					}
					if (this.form.min !== '' && this.form.max !== '' && this.form.max !== null && this.form.min !== null) {
						if (Number(this.form.min) > Number(this.form.max)) {
							this.loading = false
							this.returnMsg('报警值下限应该小于报警值上限！')
							return false
						}
					}
					if (this.isAdd) {
						this.doAdd()
					} else this.doEdit()
				} else {
					return false
				}
			})
		},
		selectAllForm() {
			selectAll().then(response => {
				this.items = response
			})
		},
		loaddevice() {
			loaddevice(this.deptparam).then(response => {
				this.devices = response
			})
		},
		loaditem() {
			this.deviceidflag = true
			this.items = []
			this.clickFlag = false
			// console.log(this.form.deviceid, 'warn111')
			for (var i = 0; i < this.devices.length; i++) {
				if (this.form.deviceid === this.devices[i].deviceid) {
					var code = this.devices[i].code.split(',')
					var subject = this.devices[i].subject.split(',')
					for (var j = 0; j < code.length; j++) {
						this.sub = {}
						this.sub.code = code[j]
						this.sub.subject = subject[j]
						this.items[j] = this.sub
					}
				}
			}
			this.form.deviceName = this.devices[0].name
			this.form.deviceid = this.devices[0].deviceid
		},
		doAdd() {
			let param = this.form
			param.upData = this.warnwaysmax
			param.lowData = this.warnwaysmin
			console.log(param, 'param')

			let data = param
			reqApi.aiAdd(data).then(res => {
				if (res.Code == '200') {
					this.resetForm()
					this.$notify({
						title: '添加成功',
						type: 'success',
						duration: 2500,
					})
					this.loading = false
					this.$parent.selectAllForm()
				} else {
				}
			})

			// add(this.form, this.warnwaysmin, this.warnwaysmax)
			// 	.then(res => {
			// 		this.resetForm()
			// 		this.$notify({
			// 			title: '添加成功',
			// 			type: 'success',
			// 			duration: 2500,
			// 		})
			// 		this.loading = false
			// 		this.$parent.init()
			// 	})
			// 	.catch(err => {
			// 		this.loading = false
			// 		console.log(err.response.data.message)
			// 	})
		},
		doEdit() {
			console.log(typeof this.form.min, this.form.min)
			console.log(typeof this.form.max, this.form.max)

			let param = this.form
			param.upData = this.warnwaysmax
			param.lowData = this.warnwaysmin
			// console.log(param, 'param')
			console.log(typeof param.min, 'typeof param.min')

			let data = param
			reqApi.aiEdit(data).then(res => {
				if (res.Code == '200') {
					this.resetForm()
					this.$notify({
						title: '修改成功',
						type: 'success',
						duration: 2500,
					})
					this.loading = false
					this.$parent.selectAllForm()
				} else {
				}
			})
			// edit(this.form, this.warnwaysmin, this.warnwaysmax)
			// 	.then(res => {
			// 		this.resetForm()
			// 		this.$notify({
			// 			title: '修改成功',
			// 			type: 'success',
			// 			duration: 2500,
			// 		})
			// 		this.loading = false
			// 		this.$parent.init()
			// 	})
			// 	.catch(err => {
			// 		this.loading = false
			// 		console.log(err.response.data.message)
			// 	})
		},
		changeDisablemin(data, scope) {
			var size = this.warnwaysmin.length
			var length = 0
			for (var i = 0; i < size; i++) {
				if (this.warnwaysmin[i].valid === '1') {
					length = length + 1
				}
			}
			// if (length === 0) {
			// 	this.$notify({
			// 		title: '至少保留一路控制器',
			// 		type: 'warning',
			// 		duration: 2500,
			// 	})
			// 	if (data.valid === '0') {
			// 		data.valid = '1'
			// 	} else {
			// 		data.valid = '0'
			// 	}
			// }
			// scope.
		},
		changeDisablemax(data, scope) {
			var size = this.warnwaysmax.length
			var length = 0
			for (var i = 0; i < size; i++) {
				if (this.warnwaysmax[i].valid === '1') {
					length = length + 1
				}
			}
			// console.log(length)
			// if (length === 0) {
			// 	this.$notify({
			// 		title: '至少保留一路控制器',
			// 		type: 'warning',
			// 		duration: 2500,
			// 	})
			// 	if (data.valid === '0') {
			// 		data.valid = '1'
			// 	} else {
			// 		data.valid = '0'
			// 	}
			// }
			// scope.
		},
		resetForm() {
			this.dialog = false
			this.$refs['form'].resetFields()
			this.deviceidflag = false
			this.warnwaysmin = []
			this.warnwaysmax = []
			this.form = {
				id: '',
				deviceid: '',
				item: '',
				warntype: '2',
				state: '1',
				min: '',
				max: '',
				name: '',
				msg: '',
				enable: '1',
				createTime: '',
				updateTime: '',
				nt: '',
			}
		},
	},
}
</script>

<style scoped>
</style>
<style>
.el-table__body-wrapper::-webkit-scrollbar {
	width: 8px;
}
.el-table__body-wrapper::-webkit-scrollbar-thumb {
	background-color: #9093994d;
	border-radius: 8px;
}
.el-table .warning-row {
	background: oldlace;
}

.el-table .success-row {
	background: #e1f3d8;
}

.el-table .danger-row {
	background: #fde2e2;
}
</style>
