<template>
  <div class="flex" style="height: calc(100vh - 84px)">
    <scrollContainer style="width: 180px; height: 100%; overflow-x: hidden">
      <el-menu
		:default-active="deftActive"
		@select="handleSelect"
        style="min-height: 100%"
      >
		<el-sub-menu :index="sji+1+''" v-for="(sud,sji) in typeList" :key="sji">
		  <template #title>
		    <span>{{sud.name}}</span>
		  </template>
		  <el-menu-item :index="sudsf.type" v-for="(sudsf,sjisf) in sud.child" :key="sjisf">{{sudsf.name}}</el-menu-item>
		</el-sub-menu>
      </el-menu>
    </scrollContainer>
    <div class="flex-sub padding-lr" style="overflow-y: auto">
      <div class="solid-bottom padding-tb margin-bottom">
        <span class="text-bold">基本配置</span>
      </div>
      <el-form ref="algorRef" :model="form" :rules="rules" label-width="120px">
        <div v-loading="loading">
          <el-form-item label="算法名称" prop="algorithm_configuration_name">
            <el-input v-model="form.algorithm_configuration_name" :disabled="form.algorithm_configuration_name !=''" />
          </el-form-item>
          <el-form-item label="任务类型" prop="algorithm_configuration_type">
            <el-select
              v-model="form.algorithm_configuration_type"
              placeholder="选择任务类型"
            >
              <el-option label="常驻任务" :value="0" />
              <el-option label="单次任务" :value="10" />
              <el-option label="周期任务" :value="20" />
            </el-select>
          </el-form-item>
          <el-form-item label="置信度阈值" prop="algorithm_confidence">
            <el-input
              v-model="form.algorithm_confidence"
              type="number"
              min="0"
              @input="isBiggerThanZero('algorithm_confidence')"
              @change="isBiggerThanZero('algorithm_confidence')"
            >
			</el-input>
          </el-form-item>
          <el-form-item label="实体阈值" prop="algorithm_object">
            <el-input
              v-model="form.algorithm_object"
              type="number"
              min="0"
              @input="isBiggerThanZero('algorithm_object')"
              @change="isBiggerThanZero('algorithm_object')"
            >
            </el-input>
          </el-form-item>
		  <el-form-item label="遮盖比例阈值" prop="algorithm_IOU">
		    <el-input
		      v-model="form.algorithm_IOU"
		      type="number"
		      min="0"
		      @input="isBiggerThanZero('algorithm_IOU')"
		      @change="isBiggerThanZero('algorithm_IOU')"
		    >
		    </el-input>
		  </el-form-item>
		  <!-- <el-form-item label="检测类别" prop="algorithm_class" style="width:100%">
		    <el-radio-group v-model="form.algorithm_class">
		      <el-radio label="0">0</el-radio>
		      <el-radio label="1">1</el-radio>
		    </el-radio-group>
		  </el-form-item> -->
		<el-form-item label="检测类别" prop="algorithm_class" style="width:100%">
			<el-select v-model="form.algorithm_class" multiple placeholder="请选择">
				<el-option v-for="item in classOption[queryParams.algorithm_configuration_name]"
				 :key="item.value"
				 :label="item.label"
				 :value="item.value">
			    </el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="报警等级" prop="algorithm_alarm_level">
		  <el-select
		    v-model="form.algorithm_alarm_level"
		    placeholder="选择报警等级"
		  >
		    <el-option label="0级" :value="0" />
		    <el-option label="1级" :value="1" />
		    <el-option label="2级" :value="2" />
			<el-option label="3级" :value="3" />
			<el-option label="4级" :value="4" />
			<el-option label="5级" :value="5" />
			<el-option label="6级" :value="6" />
		  </el-select>
		</el-form-item>
		<el-form-item label="检测间隙" prop="algorithm_alarm_gap">
		  <el-input type="number" v-model="form.algorithm_alarm_gap" placeholder="检测间隙">
		    <template #append>秒</template>
		  </el-input>
		</el-form-item>
		<el-form-item label="检测周期" prop="algorithm_alarm_cycle">
		  <el-input type="number" v-model="form.algorithm_alarm_cycle" placeholder="检测周期">
		    <template #append>秒</template>
		  </el-input>
		</el-form-item>
		<el-form-item label="检测航速" prop="algorithm_alarm_speed">
		  <el-input type="number" v-model="form.algorithm_alarm_speed" placeholder="检测航速">
		    <template #append>海里/时</template>
		  </el-input>
		</el-form-item>
        <el-form-item label="启用状态" prop="del_flag">
            <el-switch
              v-model="form.del_flag"
              active-value="0"
              inactive-value="1"
            />
          </el-form-item>
        </div>

        <div v-loading="loading">
          <el-form-item label="配置摄像机">
            <!-- <div class="solid">
             <scroll-container style="height: 900px"> -->
            <el-checkbox-group
              v-model="form.algorithm_configuration_camera_index"
              class="grid col-4"
              style="width: 100%"
            >
              <div class="padding-xs" v-for="(item, i) in cameraList" :key="i">
                <el-card :body-style="{ padding: '0px' }" shadow="hover">
                 <!-- <img
                    :src="baseUrl+'/alarm_folder/html_images/asd.png'"
                    style="height: 130px; width: 100%"
                  /> -->
				 <img
				    :src="cameraPict[item.camera_id]"
				    style="height: 130px; width: 100%"
					@click.stop="seeImg(item.camera_id)"
				  />
                 <div class="padding-sm">
                    <div class="flex justify-between">
                    <!-- <div>camera_name</div> -->
						<el-checkbox :label="item.camera_id" name="type">{{item.camera_name}}</el-checkbox>
                  </div>
                  <div>
                    <el-button @click="handleDrawDialog(item)" text bg
                      >绘制监控区域</el-button
                    >
                  </div>
                 </div>
                </el-card>
              </div>
            </el-checkbox-group>
            <!-- </scroll-container> 
            </div>-->
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存配置</el-button>
		  <el-button type="danger" :disabled="form.algorithm_configuration_id == null" @click="delForm">删除配置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <canvasDrawDialog ref="canvasDrawDialogRef" :camsId="randId" />
	<el-dialog
	  title="图片预览"
	  top="20px"
	  v-model="imgVisible"
	  width="80%">
		<img :src="imgSrc" style="width:100%;" alt="">
	</el-dialog>
  </div>
</template>

<script setup>
import canvasDrawDialog from "@/views/components/canvasDraw/dialog";
import { listAlgorithmConfiguration, addAlgorithm, updateAlgorithm,delAlgorithm } from "@/api/algorithmConfiguration";
import { listCamera,getCameraPhoto } from "@/api/camera";
import { deviceRestart, deviceClose } from "@/api/settConfiguration";
import { getAlarmType } from "@/api/algorithmConfiguration";
const { proxy } = getCurrentInstance();
const baseUrl = location.protocol+"//"+window.location.host+"/";
// const baseUrl = import.meta.env.VITE_APP_BASE_API;
const loading = ref(false);
const algorithList = ref([]);
const cameraList = ref([]);
const cameraPict = ref({});
const deftActive = ref("");

const imgVisible = ref(false);
const imgSrc = ref("");

const data = reactive({
  form: {
	 algorithm_configuration_camera_index:[],
	 algorithm_configuration_name:"",
	 algorithm_configuration_type:0,
	 algorithm_confidence:0.5,
	 algorithm_object:0.3,
	 algorithm_IOU:0.3,
	 algorithm_class:'0',
	 del_flag: '0',
	 algorithm_alarm_level: 0,
	 algorithm_alarm_gap: 30,
	 algorithm_alarm_cycle: 180,
	 algorithm_alarm_speed: 3
  },
  queryParams: {
	"algorithm_configuration_name":""
  },
  rules: {
    algorithm_configuration_name: [{
        required: true,
        message: "算法名称不能为空",
        trigger: "blur",
    }],
    algorithm_configuration_type: [{
        required: true,
        message: "任务类型不能为空",
        trigger: "blur",
    }],
    algorithm_confidence: [{
        required: true,
        message: "置信度阈值不能为空",
        trigger: "blur",
    }],
    algorithm_object: [{
        required: true,
        message: "实体阈值不能为空",
        trigger: "blur",
    }],
    algorithm_IOU: [{
        required: true,
        message: "遮盖比例阈值不能为空",
        trigger: "blur",
    }],
	algorithm_alarm_gap: [{
        required: true,
        message: "检测间隙不能为空",
        trigger: "blur",
    }],
	algorithm_alarm_cycle: [{
        required: true,
        message: "检测周期不能为空",
        trigger: "blur",
    }],
	algorithm_alarm_speed: [{
        required: true,
        message: "检测航速不能为空",
        trigger: "blur",
    }],
	// algorithm_class: [
	//   {
	//     required: true,
	//     message: "帐号状态不能为空",
	//     trigger: "blur",
	//   },
	// ],
    // status: [
    //   {
    //     required: true,
    //     message: "启用状态不能为空",
    //     trigger: "blur",
    //   },
    // ],
  },

  classOption:{
	helmet :[{
	  value: '0',
	  label: '不戴头盔'
	},{
		value: '1',
		label: '戴头盔'
	}],
	mask :[{
	  value: '0',
	  label: '不戴口罩'
	},{
		value: '1',
		label: '戴口罩'
	}],
	humanOut :[{
	  value: '0',
	  label: '离岗检测'
	}],
	humanIn :[{
	  value: '0',
	  label: '区域警戒'
	}],
	drowsy :[{
	  value: '0',
	  label: '疲劳检测'
	}],
	cigarette :[{
	  value: '0',
	  label: '不抽烟检测'
	},{
	  value: '1',
	  label: '抽烟检测'
	}],
	phone :[{
	  value: '0',
	  label: '打电话检测'
	}],
	smoke :[{
	  value: '0',
	  label: '烟火检测'
	}],
	ship :[{
	  value: '0',
	  label: '船体检测'
	}],
	shipDetection:[{
	  value: '0',
	  label: '船体识别'
	}]
  },
  randId: {
	  'camre':"",
	  'line':"",
	  'num':0,
	  'img':""
  },
  typeList:[],
  
});

const { queryParams, form, rules, classOption, randId, typeList } = toRefs(data);
const handleSelect = (key) => {
	if(queryParams.value.algorithm_configuration_name != key){
		queryParams.value.algorithm_configuration_name = key;
		getList()
	}
};
function seeImg(_src){
	imgVisible.value = true;
	imgSrc.value = cameraPict.value[_src].replace('_small','');
};
const delForm = () => {
	proxy.$modal.confirm('是否确认摄像头名称为"' + form.value.algorithm_configuration_name + '"的数据项？').then(function () {
	  return delAlgorithm(form.value.algorithm_configuration_id);
	}).then(() => {
	  getList();
	  proxy.$modal.msgSuccess("删除成功");
	}).catch(() => { });
}
const submitForm = () => {
  proxy.$refs["algorRef"].validate((valid) => {
    if (valid) {
      loading.value = true;
	  form.value.algorithm_configuration_camera_index = form.value.algorithm_configuration_camera_index.toString();
	  form.value.algorithm_class = form.value.algorithm_class.toString();
      if (form.value.algorithm_configuration_id != null) {
        updateAlgorithm(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          loading.value = false;
		  getList();
		  reStart();
        });
      } else {
        addAlgorithm(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          loading.value = false;
		   getList();
		   reStart();
        });
      }
    }
  });
};

function reStart(){
	proxy.$modal.confirm('算法设置完成，需要重启设备方可生效，是否现在重启！').then(function () {
		deviceClose().then((response) => {
			setTimeout(()=>{
				deviceRestart().then((response) => {})
			},3000)
		})
	}).then(() => {
		
	}).catch(() => { });
}
function isBiggerThanZero(key) {
  // console.log(form.value[key]);
  // console.log(form.value[key] == null);
  // console.log(typeof form.value[key]);
  form.value[key] = Number(form.value[key]);
  if (form.value[key] < 0) {
    form.value[key] = 0;
  }
}

function handleDrawDialog(id) {
	randId.value = {
		'camre':id.camera_id,
		'line':form.value.algorithm_configuration_id,
		'num':Math.random()*10,
		'img':cameraPict.value[id.camera_id].replace('_small','')
	}
	proxy.$refs["canvasDrawDialogRef"].show();
}
// 表单重置
function reset() {
  form.value = {
    algorithm_configuration_camera_index:[],
    algorithm_configuration_name:"",
    algorithm_configuration_type:0,
    algorithm_confidence:0.5,
    algorithm_object:0.3,
    algorithm_IOU:0.3,
    algorithm_class:['0'],
	del_flag: '0',
	algorithm_alarm_level: 0
  };
  proxy.resetForm("algorRef");
}
function getList() {
  loading.value = true;
  listAlgorithmConfiguration(queryParams.value).then((response) => {
	algorithList.value = response.data;
	if(algorithList.value.length){
		let dfj = algorithList.value[0];
		let fd = dfj.algorithm_configuration_camera_index.split(",");
		dfj.algorithm_configuration_camera_index = fd.map(Number);
		dfj.algorithm_class = dfj.algorithm_class.split(",")
		form.value = dfj;
	}else{
		reset();
		 proxy.$modal.msgError("该算法未配置！");
	}
	loading.value = false;
  });
}
function getCamList() {
  listCamera({}).then((response) => {
    cameraList.value = response.data;
	getPhoto();
  });
}
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)
	})
}
const switchKey = function(key){
	let _str = "",_syy = 0;
	switch (key){
		case "humanOut": 
			_str = "离岗检测";
			_syy = 0;
			break;
		case "humanIn":
			_str = "区域警戒";
			_syy = 0;
			break;
		case "drowsy":
			_str = "疲劳检测";
			_syy = 0;
			break;
		case "cigarette":
			_str = "抽烟检测";
			_syy = 0;
			break;
		case "phone":
			_str = "打电话检测";
			_syy = 0;
			break;
		case "mask":
			_str = "口罩检测";
			_syy = 1;
			break;
		case "helmet":
			_str = "安全帽检测";
			_syy = 1;
			break;
		case "smoke":
			_str = "烟火检测";
			_syy = 1;
			break;
		case "ship":
			_str = "船体检测";
			_syy = 1;
			break;
		case "shipDetection":
			_str = "船体识别";
			_syy = 1;
			break;
			
		default: 
			_str = "其他";
			break;
	}
	return [_str, _syy];
}
function getAlarmRouter(){
	getAlarmType().then((result)=>{
		if(result.code == 200&&result.data.length){
			let _iic = result.data;
			let _type = [{
					"name":"行为告警",
					"show":true,
					"child":[]
				},{
					"name":"物品检测",
					"show":false,
					"child":[],
				}];
			_iic.forEach(item => {
				let dki = switchKey(item.algorithm_configuration_name);
				_type[dki[1]].child.push({
					type: item.algorithm_configuration_name,
					name: dki[0]
				})
			});
			typeList.value = _type;
			queryParams.value["algorithm_configuration_name"] = _type[0].child[0].type;
			deftActive.value = _type[0].child[0].type;
			getList();
		}else{
			typeList.value = [];
		}
	})
}
getAlarmRouter();
getCamList();
</script>

<style lang="scss" scoped>
</style>
