<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="摄像机名称" prop="camera_name">
        <el-input v-model="queryParams.camera_name" placeholder="请输入摄像机名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="选择摄像机状态">
          <el-option label="所有" :value="0" />
          <el-option label="在线" :value="10" />
          <el-option label="离线" :value="20" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading">
      <div class="grid col-5">
        <div class="padding-xs" v-for="(item, i) in cameraList" :key="i">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
			  <img :src="cameraPict[item.camera_id]" @click.stop="seeImg(item.camera_id)" style="height: 130px; width: 100%" />
            <!-- <img :src="baseUrl+'/alarm_folder/html_images/asd.png'" style="height: 130px; width: 100%" /> -->
            <div class="padding-sm">
              <div class="flex justify-between align-center">
                <div>{{ item.camera_name }}</div>
                <!-- <el-checkbox label="camera_id" name="type">{{ item.camera_name }}</el-checkbox> -->
                <div>
                  <el-button text link icon="Edit" type="text" @click="handleUpdate(item)"></el-button>
                  <el-button text link icon="Delete" type="text" @click="handleDelete(item)"></el-button>
                </div>
              </div>
              <div>
                <!-- <el-button text bg>绘制监控区域</el-button> -->
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改摄像机列对话框 -->
    <el-dialog :title="title" v-model="open" width="800px">
      <!-- {{ form }} -->
      <el-form ref="cameraRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item>
			<el-button type="primary" @click="copyForm">复制</el-button>
			<el-button @click="pastForm">粘贴</el-button>
        </el-form-item>
		<div class="grid col-2">
          <el-form-item label="摄像机名称" prop="camera_name">
            <el-input v-model="form.camera_name" placeholder="请输入摄像机名称" />
          </el-form-item>
          <el-form-item label="摄像头类型" prop="camera_type" class="flex">
            <el-select class="flex-sub" v-model="form.camera_type" placeholder="请选择摄像头类型">
              <el-option label="其他" :value="0" />
              <el-option label="鱼眼" :value="10" />
              <el-option label="半球" :value="20" />
              <el-option label="球机" :value="30" />
              <el-option label="枪机" :value="40" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型" prop="camera_equipment_type" class="flex">
            <el-select class="flex-sub" v-model="form.camera_equipment_type" placeholder="请选择设备类型">
              <el-option label="摄像头" :value="0" />
              <el-option label="人脸抓拍机" :value="10" />
              <el-option label="RTSP" :value="20" />
              <el-option label="NVR" :value="30" />
              <el-option label="国标平台" :value="40" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户账号" prop="camera_user_name">
            <el-input v-model="form.camera_user_name" placeholder="请输入用户账号" />
          </el-form-item>
          <el-form-item label="密码" prop="camera_password">
            <el-input v-model="form.camera_password" placeholder="请输入密码" type="password" show-password />
          </el-form-item>
          <el-form-item label="IP" prop="camera_ip">
            <el-input v-model="form.camera_ip" placeholder="请输入IP" />
          </el-form-item>
          <el-form-item label="端口" prop="camera_port">
            <el-input v-model="form.camera_port" placeholder="请输入端口" type="number" />
          </el-form-item>
          <el-form-item label="品牌" prop="camera_brand" class="flex">
            <el-select v-model="form.camera_brand" @change="changeCarm" placeholder="请选择品牌" class="flex-sub">
              <el-option label="其他" :value="0" />
              <el-option label="海康" :value="10" />
              <el-option label="大华" :value="20" />
              <el-option label="华为" :value="30" />
              <el-option label="宇视" :value="40" />
              <el-option label="天地伟业" :value="50" />
            </el-select>
          </el-form-item>
          <el-form-item label="型号">
            <el-input v-model="form.camera_model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="出入检测类型" prop="camera_access_detection_type" class="flex">
            <el-select v-model="form.camera_access_detection_type" placeholder="请选择出入检测类型" class="flex-sub">
              <el-option label="无" :value="0" />
              <el-option label="离开" :value="10" />
              <el-option label="进入" :value="20" />
            </el-select>
          </el-form-item>
          <el-form-item prop="camera_rtsp" style="width:100%">
			  <template #label>
			     <span>
			        <el-tooltip content="请修改rtsp路径模板正确的账号/密码/ip" placement="top">
			           <el-icon>
			              <question-filled />
			           </el-icon>
			        </el-tooltip>rtsp地址
			     </span>
			  </template>
            <el-input v-model="form.camera_rtsp" placeholder="请输入rtsp地址" style="width:calc(100% - 82px);"/>
			<el-button class="margin-left-sm" size="small" type="primary" :disabled="rtspDis" @click="conFirmRtsp">地址诊断</el-button>
          </el-form-item>
          <el-form-item label="国标id">
            <el-input v-model="form.camera_national_id" placeholder="请输入国标id" />
          </el-form-item>
          <el-form-item label="帐号状态" prop="status" style="width:100%">
            <el-radio-group v-model="form.status">
              <el-radio label="0">启用</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="封面" prop="cover">
          <image-upload v-model="form.cover" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
	<el-dialog
	  title="图片预览"
	  top="20px"
	  v-model="imgVisible"
	  width="80%">
		<img :src="imgSrc" style="width:100%;" alt="">
	</el-dialog>
  </div>
</template>

<script setup>
import {
  listCamera,
  getCamera,
  delCamera,
  addCamera,
  updateCamera,
  downloadCamera,
  getCameraPhoto
} from "@/api/camera";
import { pingRTSP } from "@/api/settConfiguration"
import { deviceRestart, deviceClose } from "@/api/settConfiguration"
const baseUrl = location.protocol+"//"+window.location.host+"/";
// const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance();
const showSearch = ref(true);
const total = ref(0);
const loading = ref(true);
const open = ref(false);
const rtspDis = ref(false);
const title = ref("");
const ids = ref([]);

const cameraList = ref([]);
const cameraPict = ref({});
const cameraTotalList = ref([]);
const imgVisible = ref(false);
const imgSrc = ref("");
const copyFormVal = ref({});

const data = reactive({
  form: {
    status: 0,
    camera_type: 0,
    camera_brand: 0,
    camera_access_detection_type: 0,
    camera_equipment_type: 0,
	camera_rtsp: ""
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // camera_name: null,
  },
  rules: {
    camera_name: [
      {
        required: true,
        message: "摄像机名称不能为空",
        trigger: "blur",
      },
    ],
    camera_type: [
      {
        required: true,
        message: "摄像头类型不能为空",
        trigger: "blur",
      },
    ],
    camera_equipment_type: [
      {
        required: true,
        message: "设备类型不能为空",
        trigger: "blur",
      },
    ],
    camera_user_name: [
      {
        required: true,
        message: "用户账号不能为空",
        trigger: "blur",
      },
    ],
    camera_password: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur",
      },
    ],
    camera_ip: [
      {
        required: true,
        message: "IP不能为空",
        trigger: "blur",
      },
    ],
    camera_port: [
      {
        required: true,
        message: "端口不能为空",
        trigger: "blur",
      },
    ],
    camera_brand: [
      {
        required: true,
        message: "品牌不能为空",
        trigger: "blur",
      },
    ],
    camera_access_detection_type: [
      {
        required: true,
        message: "出入检测类型不能为空",
        trigger: "blur",
      },
    ],
    camera_rtsp: [
      {
        required: true,
        message: "rtsp地址不能为空",
        trigger: "blur",
      },
    ],
    status: [
      {
        required: true,
        message: "帐号状态不能为空",
        trigger: "blur",
      },
    ],
  },
	brandRtsp:{
		"0":"",
		"10":"rtsp://admin:12345@192.0.0.64:554/h264/ch1/main/av_stream",
		"20":"rtsp://admin:123456@192.0.0.68:554/cam/realmonitor?channel=1&subtype=0",
		"30":"rtsp://admin:admin123@192.168.1.110/LiveMedia/ch1/Media2",
		"40":"rtsp://admin:admin123@192.168.1.107/media/video2",
		"50":""
	}
});

const { queryParams, form, rules, brandRtsp } = toRefs(data);

/** 查询摄像机列列表 */
function getList() {
  loading.value = true;
  listCamera(queryParams.value).then((response) => {
    cameraList.value = response.data;
    // console.log((queryParams.value.pageNum - 1) * queryParams.value.pageSize, (queryParams.value.pageNum - 1) * queryParams.value.pageSize + queryParams.value.pageSize)
    // cameraList.value = response.data.slice((queryParams.value.pageNum - 1) * queryParams.value.pageSize, (queryParams.value.pageNum - 1) * queryParams.value.pageSize + queryParams.value.pageSize)
    total.value = response.total;
    loading.value = false;
	getPhoto();
  });
}
function changeCarm(val){
	form.value.camera_rtsp = brandRtsp.value[val]
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加摄像机";
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 复制按钮
function copyForm(){
	let _obj = form.value;
	delete _obj["camera_id"];
	copyFormVal.value = _obj;
	proxy.$modal.msgSuccess("复制成功");
}
// 粘贴按钮
function pastForm(){
	if(copyFormVal.value.camera_type != undefined){
		form.value = copyFormVal.value;
	}
}
// 表单重置
function reset() {
  form.value = {
    status: 0,
    camera_type: 0,
    camera_brand: 0,
    camera_access_detection_type: 0,
    camera_equipment_type: 0,
	camera_rtsp: ""
  };
  proxy.resetForm("cameraRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cameraRef"].validate((valid) => {
    if (valid) {
		console.log(form.value)
    //   if (form.value.camera_id != null) {
    //     updateCamera(form.value).then((response) => {
    //       proxy.$modal.msgSuccess("修改成功");
    //       open.value = false;
    //       getList();
		  // reStart();
    //     });
    //   } else {
    //     addCamera(form.value).then((response) => {
    //       proxy.$modal.msgSuccess("新增成功");
    //       open.value = false;
    //       getList();
		  // reStart();
    //     });
    //   }
    }
  });
}
function reStart(){
	proxy.$modal.confirm('算法设置完成，需要重启设备方可生效，是否现在重启！').then(function () {
		deviceClose().then((response) => {
			setTimeout(()=>{
				deviceRestart().then((response) => {})
			},3000)
		})
	}).then(() => {
		
	}).catch(() => { });
}
function handleUpdate(row) {
  reset();
  const camera_id =
    row.camera_id || ids.value
  getCamera(camera_id).then(response => {
    // proxy.$modal.msg(JSON.stringify(response.data));
    form.value = response.data[0];
    open.value = true;
    title.value = "修改摄像头配置信息";
  });

  // form.value = cameraList.value.filter(item => item.camera_id == camera_id)[0]
  // open.value = true;
  // title.value = "修改摄像头配置信息";
}

function handleDelete(row) {
  proxy.$modal.confirm('是否确认摄像头名称为"' + row.camera_name + '"的数据项？').then(function () {
    return delCamera(row.camera_id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getList();
var _len = 0;
const getPhoto = function(key){
	if(cameraList.value.length){
		let _obj = cameraList.value, imgPict = {}, rtspStr = "";
		_obj.forEach((item,idnex) => {
			let _thor = 0;
			if(item.camera_brand == 20){
				_thor = item.camera_rtsp.split("channel=")[1].split("&")[0];
			}else if(item.camera_brand == 10){
				_thor = item.camera_rtsp.split("h264/ch")[1].split("/")[0];
			}else if(item.camera_brand == 30){
				_thor = item.camera_rtsp.split("LiveMedia/ch")[1].split("/")[0];
			}
			rtspStr += item.camera_rtsp + ",";
			imgPict[item.camera_id] = baseUrl+"alarm_folder/display_image/"+(item.camera_ip+"_"+_thor)+"_small.jpg";
		});
		cameraPict.value= imgPict;
		cycleCamera(rtspStr, imgPict);
	}
}
const cycleCamera = function(key, xju){
	getCameraPhoto(key.slice(0, -1)).then((response)=>{
		setTimeout(()=>{
			cameraPict.value = {};
			cameraPict.value = xju;
		},3000)
	})
}
function seeImg(_src){
	imgVisible.value = true;
	imgSrc.value = cameraPict.value[_src].replace('_small','');
};
// const getPhoto = function(key){
// 	_len = 0;
// 	if(cameraList.value.length){
// 		cycleCamera();
// 	}
// }
// const cycleCamera = function(key){
// 	let _obj = cameraList.value;
// 	let _acb = _obj[_len];
// 	let _thor = 0;
// 	if(_acb.camera_brand == 20){
// 		_thor = _acb.camera_rtsp.split("channel=")[1].split("&")[0];
// 	}else if(_acb.camera_brand == 10){
// 		_thor = _acb.camera_rtsp.split("h264/ch")[1].split("/")[0];
// 	}else if(_acb.camera_brand == 30){
// 		_thor = _acb.camera_rtsp.split("LiveMedia/ch")[1].split("/")[0];
// 	}
// 	// cameraPict.value[_acb.camera_id] = baseUrl+"alarm_folder/display_image/"+(_acb.camera_ip.split(".")[2]+"."+_acb.camera_ip.split(".")[3])+".jpg";
// 	cameraPict.value[_acb.camera_id] = baseUrl+"alarm_folder/display_image/"+(_acb.camera_ip+"_"+_thor)+"_small.jpg";
// 	getCameraPhoto(_acb.camera_rtsp).then((response)=>{
// 		 _len += 1;
// 		setTimeout(()=>{
// 			cameraPict.value[_acb.camera_id] = baseUrl+"alarm_folder/display_image/"+(_acb.camera_ip+"_"+_thor)+"_small.jpg";
// 		},4000)
// 		if(_len<_obj.length){
// 			cycleCamera();
// 		}
// 	})
// }
const conFirmRtsp = function(){
	if(form.value.camera_rtsp != ""){
		rtspDis.value = true;
		pingRTSP(form.value.camera_rtsp ).then((response) => {
			if(response.code == 200){
				proxy.$modal.alert((response.data[1].success == 'true'?"连接成功":"连接失败"), {
					confirmButtonText: '确定',
					callback: action => {
					}
				});
				rtspDis.value = false;
			}
		})
	}else{
		proxy.$modal.alert("请先填写正确的视频rtsp地址", {
			confirmButtonText: '确定',
			callback: action => {
			}
		});
	}
}
total.value = cameraList.value.length;
loading.value = false;
</script>

<style>
</style>