<template>
  <MOSTY.FromPage :title="props.editObj.title" @closeDialog="closePost">
    <template #content>
      <div class="main">
        <div class="left">
          <div class="headerMessage">摄像头列表</div>
          <div class="name" :class="cameraSelection === index ? 'clickLayout' : null"
               @click.prevent="selectTheCameraPreview(item.sbbh, index)" v-for="(item, index) in cameraList"
               :key="index">
            <span>{{ (index + 1) + "、" + item.name }}</span>
          </div>
          <div class="actionSheet">
            <div class="headerMessage">摄像头画面操作</div>
            <div :class="cameraGraphicsOperationsIndex === index ? 'clickLayout name' : 'name'"
                 v-for="(item, index) in graphicOperation" :key="index"
                 @click="cameraScreenOperation(index)">
              <span>{{ item }}</span>
            </div>
            <div class="headerMessage">视频布局</div>
            <div class="name nameItem" :class="clickLayout === index ? 'clickLayout' : null"
                 v-for="(item, index) in videoLayout" :key="index"
                 @click="switchingLayout(index)">
              <span>{{ item.name }}</span>
            </div>
          </div>
        </div>
        <div class="center">
          <div v-for="index in splitScreenCount"
               :id="index === 1 ? 'center_item' : null"
               :class="cameraIndex ===  index - 1  ? 'active_video video_item' : 'video_item'"
               :style="{'width' : `${100/(clickLayout+1)}%`, 'height': `${100/(clickLayout+1)}%`}"
               :key="index">
            <div :class="cameraIndex !== index -1 ? 'empty' : '' " v-if=" cameraIndex !== index -1 ">
              <el-empty :image-size="40" />
            </div>
            <video v-else controls
                   :style="{ 'width': initialMonitoringOfContainersWidth, 'height': initialMonitoringOfContainersHeight,'objectFit': 'cover' }"
                   :id='"videoElement" + (index-1)'></video>
          </div>
        </div>
        <div class="right">
          <el-collapse v-model="activeNames" :accordion="true" @change="handleChange">
            <el-collapse-item title="镜头控制" name="1">
              <div class="lensContainer">
                <div v-for="(item, index) of  lensSetup" class="name nameItem">
                  <el-icon @mousedown="startTheCameraOperation(index, 0)" @mouseup="endOfCameraControl()">
                    <Minus />
                  </el-icon>
                  <span>{{ item }}</span>
                  <el-icon @mousedown="startTheCameraOperation(index, 1)" @mouseup="endOfCameraControl()">
                    <Plus />
                  </el-icon>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="方向控制" name="2">
              <div class="controller">
                <div v-for="btn in directionButton"
                     :key="btn.key"
                     :class="[btn.value!==9?'sector':'',btn.key]"
                     :title="btn.label"
                     @mousedown="handleRegulate(btn, 0)" @mouseup="handleRegulate(btn, 1)">
                  <el-icon>
                    <CaretLeft />
                  </el-icon>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="功能控制" name="3">
              <div class="lensContainer">
                <div v-for="item of  functionalControl" class="name nameItem">
                  <span>{{ item }}</span>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="预制点" name="4">
              <div style="text-align: right">
                <el-button size="small" @click="createPrefabricatedPoints()">创建</el-button>
              </div>
              <el-table size="small" :data="listOfPreFabricatedCameraPoints" style="width: 100%">
                <el-table-column prop="presetPointName" label="名称" />
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-icon style="margin-right: 10px" @click="cameraPositioning(scope.row)">
                      <Position />
                    </el-icon>
                    <el-icon @click="cameraPrefabricationPointModification(scope.row)" color="#0cba80"
                             style="margin-right: 10px">
                      <EditPen />
                    </el-icon>
                    <el-icon @click="cameraPreFabricatedPointDeletion(scope.row)" color="red">
                      <Delete />
                    </el-icon>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
            <el-collapse-item title="巡航线" name="5">
              <div style="text-align: right">
                <el-button size="small" @click="openTheCreateCruiseLineWindow(ruleFormRef)">创建</el-button>
              </div>
              <el-table :data="cameraCruisingHeartList" style="width: 100%">
                <el-table-column prop="cruiseName" label="巡航线名称" width="180" />
                <el-table-column prop="address" label="操作">
                  <template #default="scope">
                    <el-icon color="red" @click="deleteCameraCruiseLine(scope.row.channelId)">
                      <Delete />
                    </el-icon>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </template>
    <template #footer>
      <el-button @click="closepost">
        <el-icon>
          <DocumentDelete />
        </el-icon>
        关闭
      </el-button>
    </template>
  </MOSTY.FromPage>

  <el-dialog v-model="cameraHistoryWindow" title="视频抓图历史列表" width="70%">
    <el-form :model="cameraHistoryWindowForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="开始时间">
        <el-date-picker value-format="x" v-model="cameraHistoryWindowForm.startDate" type="datetime"
                        placeholder="请选择开始时间" />
      </el-form-item>
      <el-form-item label="结束时间" style="margin-left: 20px">
        <el-date-picker value-format="x" v-model="cameraHistoryWindowForm.endDate" type="datetime"
                        placeholder="请选择结束时间" />
      </el-form-item>
    </el-form>
    <div class="demo-image__preview" style="min-height: 300px">
      <el-image v-for="item of cameraHistoryWindowImgList" style="width: 100px; height: 100px" :src="item"
                :zoom-rate="1.2" :max-scale="2" :min-scale="0.2"
                :preview-src-list="cameraHistoryWindowImgList" show-progress :initial-index="4" fit="cover" />
    </div>
    <el-pagination v-model:current-page="cameraHistoryWindowForm.currentPage4"
                   v-model:page-size="cameraHistoryWindowForm.pageSize"
                   :page-sizes="[10, 20, 50, 100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="cameraHistoryWindowForm.total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />
  </el-dialog>
  <el-dialog v-model="cruiseLineWindow" title="创建巡航线" width="60%">
    <el-form ref="ruleFormRef" :rules="rules" status-icon
             :model="patrolRouteFormObject" :hide-required-asterisk="true">
      <el-row>
        <el-col :span="12">
          <el-form-item label="巡航线名称" :label-width="120" prop="cruiseName" :required="true">
            <el-input v-model="patrolRouteFormObject.cruiseName" placeholder="巡航线名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="预制点选择" :label-width="120">
        <span class="cruiseLine_item" v-for="(item, index) of listOfPreFabricatedCameraPoints"
              :key="index" @click="selectPrefabricatedPoints(item)">{{ item["cruiseName"] }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="设置预制点" :label-width="120">
            <div v-for="(item, index) of patrolRouteFormObject.prePointList" class="prefabricatedPointLabels"
                 :key="index">
              <div class="cruiseLine_item_container">
                <span class="cruiseLine_item">{{ item["cruiseName"] }}</span>
                <el-icon class="del_icon" color="#d0cbcb" @click="deletePrefabricatedPoints(index)">
                  <CloseBold />
                </el-icon>
              </div>
              <el-icon v-if="index < patrolRouteFormObject.prePointList.length -1 ">
                <Right />
              </el-icon>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cruiseLineWindow = false">取消</el-button>
        <el-button type="primary" @click="creationOfPatrolRoutes(ruleFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="editCruiseLine" title="编辑预制点">
    <el-form ref="ruleFormRef" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="预制点" prop="name">
        <el-input />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cruiseLineWindow = false">取消</el-button>
        <el-button type="primary" @click="creationOfPatrolRoutes(ruleFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
@import "./style/index";
</style>
<script setup>
import { ref, getCurrentInstance, onMounted, nextTick, reactive } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import { ElMessage, ElMessageBox } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import "viewerjs/dist/viewer.css"
import { api as viewerApi } from "v-viewer"

const props = defineProps({
  editObj: {
    type: Object,
    default: {}
  }
})


const { proxy } = getCurrentInstance()
const emit = defineEmits(["saveSuccess", "update:modelValue"])
const lensSetup = ref(["变倍", "变焦", "光圈"])
const graphicOperation = ref(["抓图", "查询历史抓图", "截图视频"])
const functionalControl = ref(["灯光", "两刷", "红外"])
const activeNames = ref(["5"])
const splitScreenCount = ref(16)
const rules = reactive({ cruiseName: [{ required: true, message: "巡航线不能为空", trigger: "blur" }] })
const cameraList = ref([])
const videoLayout = ref([
  { name: "1X1", num: 1 },
  { name: "2X2", num: 2 },
  { name: "3X3", num: 3 },
  { name: "4X4", num: 4 }
])
const directionButton = reactive([
  { label: "上", key: "up", value: 1 },
  { label: "右上", key: "up-right", value: 7 },
  { label: "右", key: "right", value: 4 },
  { label: "右下", key: "down-right", value: 8 },
  { label: "下", key: "down", value: 2 },
  { label: "左下", key: "down-left", value: 6 },
  { label: "左", key: "left", value: 3 },
  { label: "左上", key: "up-left", value: 5 },
  { label: "中心", key: "center", value: 9 }]
)
let initialMonitoringOfContainersWidth = ref("")
let initialMonitoringOfContainersHeight = ref("")
let cameraIndex = ref(0)
let clickLayout = ref(3)
let cameraInformation = reactive({})
let cameraSelection = ref(0)
let cameraGraphicsOperationsIndex = ref("")
let editCruiseLine = ref(false)
let cameraHistoryWindow = ref(false)
let cameraHistoryWindowImgList = ref([])
let cameraCruisingHeartList = ref([])
let cameraControlObjects = reactive({ step: 4 })
let cameraDirectionControl = reactive({ stepX: 4, stepY: 4 })
let ruleFormRef = ref()
let listOfPreFabricatedCameraPoints = ref([])
let cruiseLineWindow = ref(false)
let patrolRouteFormObject = reactive({
  cruiseName: "",
  prePointList: []
})
let cameraHistoryWindowForm = reactive({
  startDate: "",
  endDate: "",
  pageSize: 20,
  currentPage4: 1,
  total: 0
})
let hls = null
let channel_id = ""

onMounted(() => {
  // 查询摄像头列表
  getCameraList()
  xInitializeCameraContainer()
})

/**
 * 摄像头方向控制
 * @param btn
 * @param type
 */
const handleRegulate = async (btn, type) => {
  cameraDirectionControl.command = !type ? 1 : 0
  cameraDirectionControl.direct = btn.value
  let data = await postApi(cameraDirectionControl, "/mosty-lps/daSdk/operateDirect")
}

/**
 * 删除巡航路线
 * @param item_id
 */
const deleteCameraCruiseLine = async (item_id) => {
  let data = await postApi({ channelId: item_id }, "/mosty-lps/daSdk/deleteCruise")
}

/**
 * 镜头控制
 */
const cameraOperations = async () => {
  let data = await postApi(cameraControlObjects, "/mosty-lps/daSdk/operateCamera")
}

/**
 * 摄像头定位
 * @param data
 */
const cameraPositioning = (data) => {

}

/**
 * 摄像头预设点修改
 * @param data
 */
const cameraPrefabricationPointModification = (data) => {

}

/**
 * \摄像头预设点删除
 * @param data
 */
const cameraPreFabricatedPointDeletion = (data) => {

}


/**
 * 创建预设点
 */
const createPrefabricatedPoints = () => {
  ElMessageBox.prompt("输入预制点名称", "预制点创建", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /\S/,
    inputErrorMessage: "预制点名称不能为空"
  })
    .then(({ value }) => {
      let data = {
        presetPointCode: generateUniqueCode(listOfPreFabricatedCameraPoints.value),
        operateType: 3,
        presetPointName: value
      }
      cameraPreFabricationPointSetting(data)
    })
    .catch(() => ElMessage.info("取消创建"))
}

/**
 * 开启创建巡航线窗口
 * @param formEl
 */
const openTheCreateCruiseLineWindow = async (formEl) => {
  cruiseLineWindow.value = true
  if (patrolRouteFormObject.prePointList.length) patrolRouteFormObject.prePointList = []
  await nextTick(() => {
    if (!formEl) return
    formEl.resetFields()
  })
}

/**
 * 选择预设点形成巡航线
 * @param item
 */
const selectPrefabricatedPoints = (item) => patrolRouteFormObject.prePointList.push(item)

/**
 * 删除巡航线中的预设点
 * @param index
 */
const deletePrefabricatedPoints = (index) => patrolRouteFormObject.prePointList.splice(index, 1)

/**
 * 生成唯一编码
 * @param presetArray
 * @returns {string}
 */
function generateUniqueCode(presetArray) {
  const existingCodes = new Set(presetArray.map(item => item.presetPointCode))
  let code
  do {
    const num = Math.floor(Math.random() * 256) + 1
    code = num.toString().padStart(3, "0")
    if (existingCodes.size >= 256) throw new Error("所有可能的编码都已被占用")
  } while (existingCodes.has(code))
  return code
}

/**
 * 设置功能预制点
 * @param data
 */
const cameraPreFabricationPointSetting = async (data) => {
  await postApi({ ...data, channelId: channel_id }, "/mosty-lps/daSdk/operatePresetPoint")
  ElMessage.success("创建成功")
  await obtainPreFabricatedCameraPointsList(channel_id)
}


/**
 * 创建巡航路线
 * @param formEl
 * @returns {Promise<void>}
 */
const creationOfPatrolRoutes = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let response = await postApi({ ...patrolRouteFormObject, channelId: channel_id }, "/mosty-lps/daSdk/saveCruise")
      console.log("submit!")
      return
    }
    ElMessage.error("必填项校验不通过")
  })
}

/**
 * 获取巡航线
 * @param itemId
 */
const obtainCruiseLine = async (itemId) => {
  let data = await postApi({ channelId: itemId }, `/mosty-lps/daSdk/getCruises`)
  if (data instanceof Array) cameraCruisingHeartList.value = data
  console.log("巡航线", data)
}

/**
 * 开始控制镜头
 * @param index
 * @param mark
 */
const startTheCameraOperation = (index, mark) => {
  let operationType = new Map([[0, "1"], [1, "2"], [2, "3"]])
  cameraControlObjects.operateType = operationType.get(index)
  cameraControlObjects.direct = !mark ? 2 : 1
  cameraControlObjects.command = 1
  cameraOperations()
}

/**
 * 结束控制镜头
 */
const endOfCameraControl = () => {
  cameraControlObjects.command = 0
  cameraOperations()
}

/**
 * 图形画面操作
 * @param index
 */
const cameraScreenOperation = (index) => {
  cameraGraphicsOperationsIndex.value = index
  let cameraOperationsList = new Map([
    [0, captureImage],
    [1, historicalSearchMap]
  ])
  cameraOperationsList.get(index)()
}

/**
 * 查询历史抓图
 */
const historicalSearchMap = async () => {
  if (!cameraHistoryWindowForm.startDate.length && !cameraHistoryWindowForm.endDate.length) {
    const timestamp = (timestamp = 0) => {
      const now = new Date()
      const midnightTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + timestamp)
      return midnightTomorrow.getTime() / 1000
    }
    cameraHistoryWindowForm.startDate = timestamp()
    cameraHistoryWindowForm.endDate = timestamp(1)
  }
  let data = await postApi({
    ...cameraHistoryWindowForm,
    channelId: [cameraHistoryWindowForm.channelId],
    deviceCode: [cameraInformation.deviceCode]
  }, `/mosty-lps/daSdk/getHistoryCapturePic`)
  if (data instanceof Object) {
    let imgList = []
    data.records.forEach(item => imgList.push(item["capturePictureFront"]))
    cameraHistoryWindow.value = true
    cameraHistoryWindowImgList.value = imgList
    cameraHistoryWindowForm.total = data.total
  }
  console.log("抓取历史记录", data)
}

/**
 *
 * @param value
 */
const handleSizeChange = (value) => cameraHistoryWindowForm.pageSize = value

/**
 *
 */
const handleCurrentChange = () => historicalSearchMap()

/**
 * 布局切换
 * @param index
 */
const switchingLayout = (index) => {
  clickLayout.value = index
  nextTick(() => xInitializeCameraContainer())
}

/**
 * 图像抓图
 */
const captureImage = async () => {
  let response = await postApi(cameraInformation, "/mosty-lps/daSdk/capturePic")
  if (response !== null) viewerApi({ images: [response] })
}

/**
 * 查询摄像头列表
 */
const getCameraList = async () => {
  cameraList.value = await getApi({}, `/mosty-jcgl/aqsbssZb/getList?zbid=${props.editObj.id}`)
  await nextTick(() => initialCameraEquipment(cameraList.value[0]["sbbh"], "videoElement0"))
}


/**
 * 选择左边的摄像头
 * @param channelId
 * @param index
 * @returns {Promise<void>}
 */
const selectTheCameraPreview = async (channelId, index) => {
  cameraSelection.value = index
  cameraIndex.value = index
  await initialCameraEquipment(channelId, "videoElement" + index)
}

/**
 * 初始化视频容器
 */
const xInitializeCameraContainer = () => {
  let element = document.getElementById("center_item")
  initialMonitoringOfContainersWidth.value = element.clientWidth + "px"
  initialMonitoringOfContainersHeight.value = element.clientHeight + "px"
}

/**
 * 获取预置点
 * @param id
 */
const obtainPreFabricatedCameraPointsList = async (item_id) => {
  let data = await postApi({ channelId: item_id }, "/mosty-lps/daSdk/getPresetPoints")
  if (data instanceof Array) listOfPreFabricatedCameraPoints.value = data
  console.log("获取预制点", data)
}


/**
 * 初始化摄像头设备
 * @param channelId
 * @param domId
 */
const initialCameraEquipment = async (channelId, domId) => {
  cameraInformation.devChannel = channelId.slice(channelId.length - 1)
  cameraInformation.deviceCode = props.editObj.sbbh
  cameraHistoryWindowForm.channelId = channelId
  cameraControlObjects.channelId = channelId
  cameraDirectionControl.channelId = channelId
  channel_id = channelId
  if (hls !== null) hls.destroy()
  const videoElement = document.getElementById(domId)
  //调用Hls.isSupported()检查浏览器是否支持MSE
  let data = await postApi({ channelId, "streamType": 1, type: "hls" }, "/mosty-lps/daSdk/realtime")
  // 获取当前摄像头的预制点
  await obtainCruiseLine(channelId)
  await obtainPreFabricatedCameraPointsList(channelId)
  if (proxy?.$Hls.isSupported()) {
    hls = new Hls()
    hls.attachMedia(videoElement)
    hls.on(Hls.Events.MEDIA_ATTACHED, async () => {
      hls.loadSource(data)
      hls.on(Hls.Events.MANIFEST_PARSED, () => videoElement.play())
    })
    return
  } else if (videoElement.canPlayType("application/vnd.apple.mpegurl")) {
    // 如果支持原生播放
    videoElement.src = data
    videoElement.addEventListenter("canplay", () => videoElement.play())
    return
  }
  ElMessage.error("当前环境不支持初始化")
}

function closePost() {
  if (props.editObj.saveBtnShow) {
    proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？").then(() => {
      emit("changePage", "Main")
    })
  } else {
    emit("changePage", "Main")
  }
}

const handleChange = (val) => {
  console.log(val)
}
</script>
