<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
		<!-- 搜索 -->
		<!--<el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery"/>
		<el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
		<el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
		</el-select>
		<el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>-->
		<!-- 新增 -->
		<div style="display: inline-block;margin: 0px 2px;">
			<el-button v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_CREATE']" class="filter-item" size="mini" type="success" icon="el-icon-plus" @click="add">新增控制器</el-button>

			<el-button v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_CREATE']" class="filter-item" size="mini" type="primary" icon="el-icon-edit" @click="editCtrlDiaLog">修改控制器名称</el-button>
		</div>
    </div>
    <!--表单组件-->
    <eForm ref="form" :is-add="isAdd" :dicts="dicts"/>
    <logForm ref="logform"/>
	
	<!-- 表单组件-在线控制 -->
	<el-dialog append-to-body :close-on-click-modal="false" :before-close="closeCtrlDialog" :visible.sync="ctrlDialog.waydialog" :title="'在线控制'" class="dialogVideo" width="60%">
		<div class="ctrl-list">
			<el-select v-model="form.item.videoIndex" placeholder="请选择视频" size="small" @change="selectVideo" v-if="ctrlDialog.videoShow" label="操作">
				<el-option v-for="(obj, index) in form.videoList" :label="obj.name" :value="index"></el-option>
			</el-select>
			<div class="video" id="videoCtn"></div>
			<ul>
				<li v-for="item in ctrlDialog.ctrlList">
					<label class="el-form-item-label">{{item.wayname}}</label>
					<el-switch v-model="item.status" @change="changeStatus(item)" :disabled="getStatus(item)" active-value="1" inactive-value="0" ></el-switch>
				</li>
			</ul>
		</div>
	</el-dialog>
	
	<!-- 远程控制 -->
	<el-dialog append-to-body :close-on-click-modal="false" :before-close="closeRemoteCtrlDialog" :visible.sync="ctrlDialog.remoteCtrl" :title="''" class="dialogVideo2" width="60%">
		<div class="in-box">
			<div class="el-loading-mask" v-show="ctrlDialog.remoteCtrlLoading"><div class="el-loading-spinner"><svg viewBox="25 25 50 50" class="circular"><circle cx="50" cy="50" r="20" fill="none" class="path"></circle></svg><!----></div></div>
			<div id="remoteCtrlBox" class="km-a"></div>
		</div>
	</el-dialog>

	<!-- 表单组件-修改控制器 -->
	<el-dialog append-to-body :close-on-click-modal="false" :before-close="closeEditCtrlDialog" :visible.sync="ctrlEdit.waydialog" :title="'修改控制器名称'" class="dialogVideo" width="40%">
		<!-- <el-switch v-model="value1" active-text="按月付费" inactive-text="按年付费"></el-switch> -->
		<div class="ctrl-list" style="height:500px">
			<el-select v-model="ctrlEdit.projectIndex" placeholder="请选择项目" size="small" @change="selectCtrl">
				<el-option v-for="(obj, index) in data" :label="obj.name" :value="index"></el-option>
			</el-select>

			<el-table v-loading="loading" :data="ctrlEdit.data" size="small" style="width:100%;margin-top:20px;">
				<el-table-column prop="wayname" label="支路名称" align="center">
					<template slot-scope="scope">
						<el-input v-model="scope.row.wayname" />
					</template>
				</el-table-column>
				<el-table-column prop="way" label="支路"/>
				<el-table-column v-if="checkPermission(['ADMIN','SDEVICEWAY_ALL','SDEVICEWAY_EDIT','SDEVICEWAY_DELETE'])" label="操作" align="center">
					<template slot-scope="scope">
						<el-button v-permission="['ADMIN','SDEVICEWAY_ALL','SDEVICEWAY_EDIT']" size="mini" type="primary"  @click="editCtrl(scope.row)">确认</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
	</el-dialog>

    <!--表格渲染-->
    <el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
      <el-table-column prop="deviceid" label="设备id" min-width="130%"/>
      <el-table-column prop="name" label="设备名称" min-width="130%"/>
      <el-table-column prop="online" label="在线状态"/>
      <el-table-column prop="workmode" label="工作模式">
        <template slot-scope="scope">
          <div v-for="item in dictMap.workmode" :key="item.id">
            <div v-if="scope.row.workmode === item.value">{{ item.label }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="设备类型">
        <template slot-scope="scope">
          <div v-for="item in dictMap.type" :key="item.id">
            <div v-if="scope.row.type === item.value">{{ item.label }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="devicetype" label="控制器类型">
        <template slot-scope="scope">
          <div v-for="item in devicetypes" :key="item.id">
            <div v-if="parseInt(scope.row.devicetype) === item.id">{{ item.typename }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nt" label="所属项目">
        <template slot-scope="scope">
          <div v-for="item in projects" :key="item.id">
            <div v-if="parseInt(scope.row.nt) === item.id">{{ item.proname }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['ADMIN','SDEVICE_ALL','SDEVICE_EDIT','SDEVICE_DELETE'])" label="在线控制" width="150px" align="center">
        <template slot-scope="scope">
          <!--<a href="javascript:void(0);" onclick="showWay(scope.row)"><i class="el-icon-s-operation" style="height: 10px;width: 10px;"/></a>-->
          <el-button v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_EDIT']" size="mini" type="primary" icon="el-icon-s-operation" @click="showWay(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['ADMIN','SDEVICE_ALL','SDEVICE_EDIT','SDEVICE_DELETE'])" label="控制记录" width="150px" align="center">
        <template slot-scope="scope">
          <el-button v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_EDIT']" size="mini" type="success" icon="el-icon-time" @click="showLog(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['ADMIN','SDEVICE_ALL','SDEVICE_EDIT','SDEVICE_DELETE'])" label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <el-button v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_EDIT']" size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"/>
          <el-popover
            v-permission="['ADMIN','SDEVICE_ALL','SDEVICE_DELETE']"
            :ref="scope.row.id"
            placement="top"
            width="180">
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id, scope.row.relay, scope.row.deviceid, scope.row.nt)">确定</el-button>
            </div>
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"/>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page + 1"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"/>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import { del } from '@/api/sDevice'
import { deleteByDeviceid, add, edit, loadByDeviceid, controlWay, getRemoteControl } from '@/api/sDeviceWay'
import { deleteByProjectidAndDeviceid } from '@/api/sProjectDevice'
import { getSProjectsNopage } from '@/api/sProject'
import { getDevicetypeNopage } from '@/api/sDevicetype'
import { videoList, getVideoIframe } from '@/utils/video'
import eForm from './form'
import logForm from './logform'

export default {
	components: {
		eForm,
		logForm
	},
	mixins: [initData, initDict],
	data() {
		return {
			delLoading: false, projects: '', devicetypes: '',
			queryTypeOptions: [
				{ key: 'imei', display_name: 'IMEI码' },
				{ key: 'deviceid', display_name: '设备id' },
				{ key: 'name', display_name: '设备名称' }
			],
			deldata: {
				projectid: '',
				deviceid: ''
			},
			ctrlDialog:{
				waydialog:false,
				loading:true,
				videoShow:false,
				form:{
					value1:false,
				},
				ctrlList:[],
				remoteCtrl:false,
				remoteCtrlLoading:false,
			},
			ctrlEdit:{
				waydialog:false,
				loading:true,
				projectIndex:0,
				form:{
					value1:false,
				},
				ctrlList:[],
				data:[],
			},

			form:{
				item:{
					videoIndex:0
				},

				videoList:videoList,
			},
		}
	},
	created() {
		this.$nextTick(() => {
			this.ctrlDialog.videoShow = this.getUsername() === 'zhuyang';

			this.init()
			// 加载数据字典
			this.getDictMap('type,workmode')
			this.getProjects()
			this.getDevicetype();
		})
	},
	methods: {
		checkPermission,
		beforeInit() {
			this.url = 'api/sDeviceByUseridAnddevType'
			const sort = 'id,desc'
			this.params = { page: this.page, size: this.size, sort: sort }
			const query = this.query
			const type = query.type
			const value = query.value
			if (type && value) { this.params[type] = value }
			return true
		},
		subDelete(id, relay, deviceid, nt) {
		  this.delLoading = true
		  // console.log(devicetype, deviceid, nt)
		  del(id).then(res => {
			this.delLoading = false
			this.$refs[id].doClose()
			this.dleChangePage()
			this.init()
			// 删除设备项目绑定关系
			this.deldata.projectid = nt
			this.deldata.deviceid = deviceid
			deleteByProjectidAndDeviceid(this.deldata).then(respeoiddevid => {}).catch(errproiddevid => {
			  console.log(errproiddevid.response.data.message)
			})
			// 如果是1 控制器还要删除控制器支路表
			if (relay === '1') {
			  deleteByDeviceid(deviceid).then(resdeviceid => {}).catch(errdeviceid => {
				console.log(errdeviceid.response.data.message)
			  })
			}
			this.$notify({
			  title: '删除成功',
			  type: 'success',
			  duration: 2500
			})
		  }).catch(err => {
			this.delLoading = false
			this.$refs[id].doClose()
			console.log(err.response.data.message)
		  })
		},
		getUsername(){
			return this.$store.state.user.user.username
		},
		getProjects() {
		  getSProjectsNopage().then(response => {
			this.projects = response
		  })
		},
		getDevicetype() {
		  getDevicetypeNopage().then(response => {
			this.devicetypes = response
		  })
		},
		add() {
		  this.isAdd = true
		  this.$refs.form.dialog = true
		  this.$refs.form.initProjectUser()
		  this.$refs.form.menuKeyPlus()
		  // this.$refs.form.handler()
		},
		showWay(data) {
			var deviceid = data.deviceid;
			this.ctrlDialog.loading = true;
			this.workmode = data.workmode;
			this.online = data.online;

			// 权限
			if(this.ctrlDialog.videoShow){
				// 加载视频
				this.$nextTick(() => {
					this.selectVideo(this.form.item.videoIndex);
				});
			};
			
			if(data.telecomcode === 'PLC'){
				this.ctrlDialog.remoteCtrl = true;
				this.ctrlDialog.remoteCtrlLoading = true;
				var param = {
					account:'15634301359',
					platform:'1',
					privateKey:'5985446b4fed93276729',
					machineCode:data.deviceid,
				};

				// 加控远程控制
				getRemoteControl(param).then(res => {
					this.remoteCtrlBox = this.remoteCtrlBox || document.getElementById("remoteCtrlBox");;
					var result = res.result || {};
					var url = result.url;
					this.remoteCtrlBox.innerHTML = "<iframe src='"+url+"' width=\"100%\" height=\"100%\" frameborder=\"no\" border=\"0\" allowfullscreen> </iframe>";
					this.remoteCtrlBox.firstElementChild.onload = (e) => {
						this.ctrlDialog.remoteCtrlLoading = false;
					};
				});
			}else{
				this.ctrlDialog.waydialog = true;
				// 加载控制器
				loadByDeviceid({deviceid:deviceid}).then(res => {
					var list = res;
					this.ctrlDialog.ctrlList = list;
				});
			};
		},
		selectVideo(index){
			//var videoList = this.form.videoList;
			//var videoItem = videoList[index];

			getVideoIframe(index).then(iframeText => {
				this.videoCtn = this.videoCtn || document.getElementById("videoCtn");
				this.videoCtn.style.height = '440px';
				this.videoCtn.innerHTML = iframeText;
			});
		},

		showLog(data) {
		  this.$refs.logform.logdialog = true
		  this.$refs.logform.initLog()
		  this.$refs.logform.form.deviceid = data.deviceid
		},
		edit(data) {
		  this.isAdd = false
		  const _this = this.$refs.form
		  _this.form = {
			id: data.id,
			nt: data.nt,
			jd: data.jd,
			name: data.name,
			wd: data.wd,
			qrcode: data.qrcode
		  }
		  _this.dialog = true
		  this.$refs.form.initProjectUser()
		  this.$refs.form.menuKeyPlus()
		},

		closeCtrlDialog() {
			this.ctrlDialog.waydialog = false;
			this.ctrlDialog.loading = false;
			this.videoCtn && (this.videoCtn.innerHTML = '');
		},

		closeRemoteCtrlDialog() {
			this.ctrlDialog.remoteCtrl = false;
			this.ctrlDialog.loading = false;
			//this.videoCtn && (this.videoCtn.innerHTML = '');
		},

		closeEditCtrlDialog() {
			this.ctrlEdit.waydialog = false
			this.ctrlEdit.loading = true;
		},

		getStatus(item) {
			// deviceStatus==='在线' ? false:true
			// workmode 工作模式 0远程 1本地

			if (this.online === '在线') {
				if (this.workmode === '0') {
					return false
				} else {
					return true
				}
			} else {
				return true
			}
		},

		changeStatus(data) {
			this.loading = true
			controlWay(data).then(response => {
				this.loading = false
				if(response === 'success') {
					//this.initdeviceWay()
					this.$notify({
						title: '操作成功',
						type: 'success',
						duration: 2500
					})
				}
			}).catch(err => {
				//this.initdeviceWay()
				this.loading = false
				/* this.$notify({
				  title: '操作失败',
				  type: 'warning',
				  duration: 2500
				})*/
				if (data.status === '0') {
					data.status = '1'
				} else {
					data.status = '0'
				}
				console.log(err.response.data.message)
			})
		},

		selectCtrl(index){
			this.loadByDevice(index)
		},

		editCtrlDiaLog(data) {
			this.ctrlEdit.waydialog = true;
			this.ctrlEdit.loading = false;
			var index = this.ctrlEdit.projectIndex;

			this.loadByDevice(index)
		},
		loadByDevice(index){
			var dataItem = this.data[index];
			var deviceid = dataItem.deviceid;
			// 加载控制器
			loadByDeviceid({deviceid:deviceid}).then(res => {
				var list = res;
				this.ctrlEdit.data = list;
			});
		},
		editCtrl(item){
			item.msg = null
			edit(item).then(res => {
				this.$notify({
				  title: '修改成功',
				  type: 'success',
				  duration: 2500
				});
			}).catch(err => {
				this.loading = false
			})
		},
	}
}
</script>

<style lang="scss">
	.ctrl-list{
		overflow-y:auto;
		ul{font-size:0;}
		li{
			font-size:14px;display:inline-block;padding:10px 0;margin-right:40px;
			label{margin-right:5px;}
		}
		.video{margin:15px 0 5px;}
	}
	
	.dialogVideo{
		display:flex;align-items:center;justify-content:center;
		.el-dialog{margin:0 !important;}
		.el-dialog__body{padding:5px 20px;}


		.el-table{
			.el-input__inner{height:25px;line-height:25px;}

			.el-table--small td{padding:5px 0;}
		}
	}

	.dialogVideo2{
		.el-dialog__header{
			button{top:8px;right:8px;}
		}
		.el-dialog__body{padding-top:0;}
		.in-box{
			border:1px solid #aaa;
			position:relative;height:60vh;
			.km-a{height:100%;width:100%;}
			iframe{height:100%;width:100%;border:0;}
		}
	}
</style>
