<template>
  <el-dialog v-model="algorithmManage.visible.value" width="60%" append-to-body>
    <template v-slot:header>
      <div
        class="cleartitle"
        style="display: flex; justify-content: flex-start; align-items: center"
      >
        <img src="@/assets/images/logo_video.png" width="25px" alt="" />
        <span>{{ title }}</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-row :gutter="10" class="mb8" style="justify-content: space-between">
          <el-col :span="1.5">
            <div
              class="form-title"
              style="
                display: flex;
                justify-content: flex-start;
                align-items: center;
              "
            >
              <span>基础信息</span>
            </div>
          </el-col>
          <el-col :span="6.8" style="display: flex"> </el-col>
        </el-row>
        <div class="left-form">
          <el-form
            ref="algLevelRef"
            :model="unref(algorithmManage.form)"
            :rules="rules"
            label-position="left"
            label-width="100px"
            class="demo-form-inline"
          >
            <el-form-item
              label="摄像头名称"
              prop="deviceId"
              v-if="unref(device.list).length"
            >
              <el-select
                v-model="unref(algorithmManage.form).deviceId"
                placeholder="请选择摄像头"
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="item in unref(device.list)"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- RTSP地址 -->
            <el-form-item label="RTSP地址" prop="vedioUrl">
              <el-input
                v-model="unref(algorithmManage.form).videoUrl"
                readonly
              />
            </el-form-item>
            <el-form-item label="是否重新拉流" prop="restartFlow">
              <el-switch
                v-model="unref(algorithmManage.form).restartFlow"
                inline-prompt
                active-text="是"
                inactive-text="否"
                active-value="true"
              />
            </el-form-item>
            <el-form-item label="重新拉流时间" prop="reStreamingTime">
              <el-date-picker
                v-model="unref(algorithmManage.form).reStreamingTime"
                type="datetime"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="left-list">
          <div class="form-title">算法列表</div>
          <el-table
            :data="
              unref(algorithmManage.form).aiRegionalLocationList ||
              aiAlgorithm.list.value
            "
          >
            <el-table-column
              label="算法名称"
              align="center"
              prop="algorithmName"
            />
            <el-table-column label="选择" align="center" prop="alarmColor">
              <template #default="scope">
                <span>
                  <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                  ></el-switch>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="识别区域"
              width="180"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="beginDraw(scope.row)"
                  v-hasPermi="['system:post:edit']"
                  >绘制</el-button
                >
                <el-button
                  link
                  type="primary"
                  @click="aiConfig(scope.$index,scope.row)"
                  v-hasPermi="['system:post:remove']"
                  >配置</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="11" :offset="1" class="right-draw">
        <div>
          <el-button
            @click="getPhoto"
            v-if="!algorithmManage.form.value.liveMap"
            >拍照取图</el-button
          >
          <el-button @click="getNewPhoto" v-else>重新取图</el-button>
          <el-button @click="clearDraw">重绘标记</el-button>
          <el-button @click="++drawIndex">重绘下一个</el-button>
        </div>
        <div class="right-draw-content">
          <img
            v-if="algorithmManage.form.value.liveMap"
            :src="algorithmManage.form.value.liveMap"
            class="drawImg"
            alt=""
          />
          <template v-else>
            <video controls ref="videoEle" class="drawImg">
              <source src="@/assets/movie.mp4" type="video/mp4" />
            </video>
            <canvas id="canvas"></canvas>
          </template>
          <svg
            @click="pointDraw"
            v-if="drawId && algorithmManage.form.value.liveMap"
            class="drawSvg"
          >
            <title>多边形</title>
            <polygon
              :fill="item.fill"
              stroke="blue"
              stroke-width="1"
              v-for="item in graph[drawId]"
              :points="item.point"
              :key="item.key"
            />
          </svg>
        </div>
        <div class="right">
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button type="primary" plain @click="algorithmManage.toClose"
            >取消</el-button
          >
        </div>
      </el-col>
    </el-row>
  </el-dialog>
  <el-dialog title="算法配置" v-model="aiAlgorithm.visible.value" width="30%">
    <el-form
      ref="algorithmManage.formRef"
      :model="aiAlgorithm.form"
      label-width="80px"
    >
      <el-form-item label="算法名称" prop="algorithmName">
        <el-input v-model="unref(aiAlgorithm.form).algorithmName" readonly />
      </el-form-item>
      <el-form-item label="告警间隔" prop="alarmInterval">
        <el-input
          placeholder="单位/秒"
          v-model="unref(aiAlgorithm.form).alarmInterval"
        />
      </el-form-item>
      <el-form-item label="行为持续多长时间报警" prop="continueWarnTime">
        <el-input
          placeholder="单位/秒"
          v-model="unref(aiAlgorithm.form).continueWarnTime"
        />
      </el-form-item>
      <el-form-item label="识别间隔（跳帧）" prop="identifyIntervals">
        <el-input v-model="unref(aiAlgorithm.form).identifyIntervals" />
      </el-form-item>
      <el-form-item label="标签阈值" prop="labelThreshold">
        <el-input v-model="unref(aiAlgorithm.form).labelThreshold" />
      </el-form-item>
      <div class="right">
        <el-button type="primary" @click="sureConfig">确认</el-button>
        <el-button type="primary" plain @click="aiAlgorithm.toClose"
          >取消</el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { reactify } from "@vueuse/core";
import { onMounted, ref, unref } from "vue";
const { algorithmManage } = defineProps({ algorithmManage: Object });
import { useIndex } from "../hooks";
import { colors, drawImage } from "../utils";
const device = useIndex({
  list: "/yunshou/aiDevice/list",
});
const aiAlgorithm = useIndex({
  list: "/yunshou/aiAlgorithmConfig/list",
  detail: "/yunshou/aiAlgorithmConfig/",
});
function handleDeviceChange(e, index) {
  const d = device.list.value.find((x) => x.id == e);
  algorithmManage.form.value.videoUrl = d.videoUrl;
}

function submit() {
  let algorithms = [];
  algorithmManage.form.value.runningState = '0';
  if (algorithmManage.form.value.id) {
    algorithms = unref(algorithmManage.form).aiRegionalLocationList;
  } else {
    unref(aiAlgorithm.list).forEach((val) => {
      algorithms.push({
        algorithmId: val.id,
        drawingArea: graph[val.id]
          ? JSON.stringify(graph[val.id])
          : val.drawingArea
          ? val.drawingArea
          : "",
        status: val.status,
        ...val.params,
      });
    });
  }
  algorithmManage.form.value.algorithms = algorithms;
  algorithmManage.toSubmit();
}
const configIndex = ref(0);
function aiConfig(index,e) {
  configIndex.value = index;
  const current = unref(aiAlgorithm.list)[index];
  aiAlgorithm.form.value = algorithmManage.form.value.id
    ? e
    : {
        algorithmName: current.algorithmName,
      };
  aiAlgorithm.visible.value = true;
}
// 确认配置
function sureConfig() {
  if (algorithmManage.form.value.id) {
    const current = unref(algorithmManage.form).aiRegionalLocationList[
      configIndex.value
    ];
    unref(algorithmManage.form).aiRegionalLocationList[configIndex.value] = {
      ...current,
      ...unref(aiAlgorithm.form),
    };
  } else {
    unref(aiAlgorithm.list)[configIndex.value].params = unref(aiAlgorithm.form);
  }
  aiAlgorithm.toClose();
}
let drawId = ref();
let drawIndex = ref(0);
const graph = reactive({});

const videoEle = ref(null);
function getPhoto() {
  algorithmManage.form.value.liveMap = drawImage(videoEle.value);
}
/* 重新取图 */
function getNewPhoto() {
  unref(algorithmManage.form).liveMap = "";
  for (let key in graph) {
    graph[key] = [];
  }
}
function beginDraw(e) {
  drawId.value = e.id;
  if (typeof e.drawingArea == "string" && e.drawingArea) {
    graph[e.id] = JSON.parse(e.drawingArea);
  }
  drawIndex.value = graph[drawId.value] ? graph[drawId.value].length : 0;
}
function clearDraw() {
  graph[drawId.value] = [];
  drawIndex.value = 0;
}
function pointDraw(e) {
  if (!graph[drawId.value]) {
    graph[drawId.value] = [];
  }
  if (!graph[drawId.value][drawIndex.value]) {
    graph[drawId.value][drawIndex.value] = {
      fill: colors(),
      point: "",
    };
  }
  graph[drawId.value][drawIndex.value].point += `${e.offsetX},${e.offsetY} `;
}
</script>

<style scoped lang="scss">
.form-title {
  display: flex;
  align-items: center; /*for vertical align*/
  font-size: 16px;
  font-weight: 600;
  border-radius: 5px;
  padding: 0;
}
.form-title::before {
  content: "";
  display: inline-block;
  width: 10px; /* 矩形的宽度 */
  height: 30px; /* 矩形的高度 */
  background-color: #1890ff; /* 矩形的背景颜色 */
  margin-right: 10px;
  border-radius: 8px;
}
.drawImg {
  width: 100%;
  height: 100%;
}
.right {
  text-align: right;
}
.right-draw {
  display: grid;
  grid-template-rows: 30px 1fr 30px;
  gap: 20px;
  .right-draw-content {
    position: relative;
    svg {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 100%;
    }
  }
}
</style>