<template>
  <div class="app-container home">
    <TabTitle :text="nowText" />
    <div class="add-but">
      <el-button type="primary" icon="Plus" @click="createPoint" plain
        >新增点位</el-button
      >
    </div>
    <el-row :gutter="10">
      <el-col :xs="0" :sm="2" :md="3" :lg="4">
        <el-card class="left-list">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="areaManger.list"
              :props="{ children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data, index }">
                <span class="areaNodes">
                  <span>{{ data.label }}</span>
                  <span @click.stop>
                    <!-- 添加dropdown -->
                    <el-dropdown trigger="click">
                      <el-dropdown-link class="dropdown-link">
                        <el-button type="text" size="small">
                          <el-icon size="20" color="#333333"
                            ><Setting
                          /></el-icon>
                        </el-button>
                      </el-dropdown-link>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="areaMangerAddBefore(data)"
                            >新增子区域</el-dropdown-item
                          >
                          <el-dropdown-item @click="areaManger.toEdit(data)"
                            >编辑该区域</el-dropdown-item
                          >
                          <el-dropdown-item
                            v-if="node.level != 1"
                            @click="areaManger.toDel(data)"
                            >删除该区域</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </span>
                </span>
              </template></el-tree
            >
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="16" :md="16" :lg="20">
        <el-scrollbar :height="globalScreenHeight + 'px'">
          <el-card class="right-list">
            <template v-slot:header>
              <div class="cleartitle" style="justify-content: flex-start">
                <img src="@/assets/images/logo_video.png" width="25px" alt />
                <span>{{ nowText }}</span>
              </div>
            </template>
            <el-table v-loading="loading" :data="algorithmManage.list.value">
              <el-table-column label="实况图" align="center" prop="postId">
                <template #default="scope">
                  <img
                    :src="scope.row.liveMap"
                    style="width: 60px; height: 40px"
                    alt=""
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="摄像头名称"
                align="center"
                prop="deviceName"
              />
              <el-table-column
                label="点位名称"
                align="center"
                prop="locationName"
              />
              <el-table-column
                label="所属区域"
                align="center"
                prop="regionalName"
              />
              <!-- <el-table-column -->
              <!-- label="推理间隔（秒）" -->
              <!-- align="center" -->
              <!-- prop="inferenceInterval" -->
              <!-- /> -->
              <el-table-column
                label="关联算法"
                align="center"
                prop="algorithmCount"
              >
                <template #default="scope">
                  <el-tooltip
                    :content="scope.row.algorithmName"
                    placement="top-start"
                  >
                    <el-button>{{ scope.row.algorithmCount }}个</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="时段配置" align="center" prop="postSort">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="configProTime(scope.row)"
                    >配置</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="设备拉流状态" align="center" prop="deviceFlowStatus">
                <template #default="scope">
                  <el-tag  :type="scope.row.deviceFlowStatus=='0'?'success':'danger'" effect="dark">{{scope.row.deviceFlowStatus=='0'?'正常':'失败' }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="运行状态" align="center" prop="postSort">
                <template #default="scope">
                  <!-- <el-tag -->
                  <!-- :type="scope.row.runningState == '1' ? 'success' : 'danger'" -->
                  <!-- :size="scope.row.runningState == '1' ? 'medium' : 'small'" -->
                  <!-- >{{ -->
                  <!-- scope.row.runningState == "1" ? "运行中" : "未运行" -->
                  <!-- }}</el-tag -->
                  <!-- > -->
                  <el-switch
                    v-model="scope.row.runningState"
                    active-value="0"
                    inactive-value="1"
                    @change="(e) => changeState(scope.row, e)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="180"
                align="left"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-tooltip content="修改" placement="top" v-if="scope.row.runningState=='1'">
                    <el-button link type="primary" icon="Edit" @click="algorithmManage.toEdit(scope.row)" ></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top" v-if="scope.row.runningState=='1'">
                    <el-button link type="primary" icon="Delete" @click="algorithmManage.toDel(scope.row)" ></el-button>
                  </el-tooltip>
                  <!-- <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="algorithmManage.toEdit(scope.row)"
                    v-hasPermi="['system:post:edit']"
                    ></el-button
                  >
                  <el-button
                    link
                    v-if="scope.row.runningState=='1'"
                    type="primary"
                    icon="Delete"
                    @click="algorithmManage.toDel(scope.row)"
                    v-hasPermi="['system:post:remove']"
                    ></el-button
                  > -->
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-right">
              <el-pagination
                background
                v-model:current-page="unref(algorithmManage.page).pageNum"
                v-model:page-size="unref(algorithmManage.page).pageSize"
                :total="unref(algorithmManage.page).total"
                layout="total, sizes, prev, pager, next, jumper"
              />
            </div>
          </el-card>
        </el-scrollbar>
      </el-col>
    </el-row>
    <template v-if="algorithmManage.visible.value">
      <drawPoint
        ref="drawPointRef"
        :algorithmManage="algorithmManage"
        :areaManger="areaManger"
      />
    </template>
    <el-dialog
      title="区域管理"
      v-model="areaManger.visible.value"
      width="40%"
      top="30%"
     
    >
      <el-form ref="areaMangerRef" :model="areaManger.form" label-width="120px">
        <el-form-item label="上级区域" prop="regionPath">
          <el-cascader
            v-model="unref(areaManger.form).parents"
            :options="areaManger.list.value"
            :props="{ children: 'children', value: 'id', checkStrictly: true }"
            placeholder="请选择上级区域"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionName">
          <el-input
            v-model="unref(areaManger.form).regionName"
            placeholder="请输入区域名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="areaManger.toClose">取 消</el-button>
          <el-button type="primary" @click="submitAreaForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="时段配置"
      v-model="aiAlarmPeriodTime.visible.value"
      width="45%"
    >
      <el-button style="margin-bottom: 10px" type="primary" @click="time.toAdd"
        >新增时段配置</el-button
      >

      <el-table v-loading="loading" :data="aiAlarmPeriodTime.list.value">
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="算法名称" align="center" prop="algorithmName" />
        <el-table-column label="告警时段" align="center">
          <template #default="scope">
            {{ scope.row.startTime }}-{{ scope.row.endTime }}
          </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"
              icon="Edit"
              @click="timeEdit(scope.row)"
              v-hasPermi="['system:post:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="timeDel(scope.row)"
              v-hasPermi="['system:post:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="时段配置" v-model="time.visible.value" width="20%">
      <el-form
        ref="aiAlarmPeriodTime.formRef"
        :model="aiAlarmPeriodTime.form"
        label-width="80px"
      >
        <el-form-item label="算法名称" prop="algorithmName">
          <el-select v-model="unref(aiAlarmPeriodTime.form).algorithmId">
            <el-option
              v-for="item in aiAlarmPeriodTimeList"
              :key="item.id"
              :label="item.algorithmName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="alarmInterval">
          <el-time-picker
            v-model="unref(aiAlarmPeriodTime.form).startTime"
            arrow-control
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="alarmInterval">
          <el-time-picker
            v-model="unref(aiAlarmPeriodTime.form).endTime"
            arrow-control
            value-format="HH:mm"
          />
        </el-form-item>
        <div class="right">
          <el-button type="primary" @click="timeSure">确认</el-button>
          <el-button type="primary" plain @click="time.toClose">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
  
<script setup name="Index">
import drawPoint from "./components/drawPoint.vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { onMounted, reactive, ref, unref, watch, watchEffect } from "vue";
import request from "@/utils/request";
import { useIndex } from "./hooks";
const { proxy } = getCurrentInstance();
const globalScreenHeight = inject("globalScreenHeight");
const drawPointRef = ref(null);
const nowText = ref("点位管理");
const deptName = ref("");
const loading = ref(false);
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
const deptTreeRef = ref(null);
watch(deptName, (val) => {
  deptTreeRef.value.filter(val);
});
const time = useIndex({});

const aiAlarmPeriodTime = useIndex({
  list: "/yunshou/aiAlarmPeriodTime/list",
  add: "/yunshou/aiAlarmPeriodTime",
  edit: "/yunshou/aiAlarmPeriodTime/",
  delete: "/yunshou/aiAlarmPeriodTime/",
  detail: "/yunshou/aiAlarmPeriodTime/",
});
const aiAlarmPeriodTimeList = ref([]);

/* 新增点位 */
function createPoint() {
  const searchValue = unref(algorithmManage.search);
  if (searchValue.regionalId) {
    algorithmManage.form.value.regionalId = searchValue.regionalId;
  }
  algorithmManage.toAdd();
}
/* 新增子区域 */
function areaMangerAddBefore(data){
  const parentIds = findParentIds(areaManger.list.value ,data.id);
  areaManger.form.value.parents =parentIds;
  console.log(data)
  areaManger.toAdd(data)
}

function findParentIds(nodes, targetId, path = [], result = []) {  
    for (let node of nodes) {  
        // 将当前节点的ID添加到路径中  
        path.push(node.id);  
        // 检查是否找到目标节点  
        if (node.id === targetId) {  
            // 复制当前路径到结果中（因为路径会被后续迭代修改）  
            result.push(...path);  

        }  
        // 如果当前节点有子节点，则递归查找  
        if (node.children) {  
            findParentIds(node.children, targetId, path, result);  
        }  
        // 回溯，移除当前节点ID  
        path.pop();  
    }  
    return result;  
}  
function configProTime(data) {
  aiAlarmPeriodTime.getList({ regionalLocationId: data.id });
  algorithmManage.getDetail(data.id).then(({ data }) => {
    aiAlarmPeriodTimeList.value = data.aiRegionalLocationList;
    aiAlarmPeriodTime.form.value.deviceId = data.deviceId;
    aiAlarmPeriodTime.form.value.regionalLocationId = data.id;
  });
  aiAlarmPeriodTime.toAdd();
}
function timeSure() {
  aiAlarmPeriodTime.toSubmit(false).then(() => {
    aiAlarmPeriodTime.getList({
      regionalLocationId: aiAlarmPeriodTime.form.value.regionalLocationId,
    });
    aiAlarmPeriodTime.form.value.startTime = "";
    aiAlarmPeriodTime.form.value.endTime = "";
    aiAlarmPeriodTime.form.value.algorithmId = "";
    time.toClose();
  });
}
function timeEdit(data) {
  aiAlarmPeriodTime.toEdit(data);
  time.visible.value = true;
}
function timeDel(data) {
  aiAlarmPeriodTime.toDel(data, false).then(() => {
    aiAlarmPeriodTime.getList({
      regionalLocationId: aiAlarmPeriodTime.form.value.regionalLocationId,
    });
    time.toClose();
  });
}
const areaManger = useIndex(
  {
    list: "/yunshou/aiRegionManage/list",
    add: "/yunshou/aiRegionManage",
    edit: "yunshou/aiRegionManage",
    delete: "yunshou/aiRegionManage/",
    detail: "/yunshou/aiRegionManage/",
  },
  ({ data }) => {
    data.parents = data.regionPath.split(",");
  },
  (data) => {
    algorithmManage.search.value.regionalId = data[0].id;
    algorithmManage.getList();
  }
);

const algorithmManage = useIndex(
  {
    list: "/yunshou/aiRegionalLocation/list",
    add: "/yunshou/aiRegionalLocation",
    edit: "/yunshou/aiRegionalLocation/",
    delete: "/yunshou/aiRegionalLocation/",
    detail: "/yunshou/aiRegionalLocation/",
  },
  ({ data }) => {},
  () => {},
  false
);
function submitAreaForm(e) {
  const { form } = areaManger;
  const valueForm = unref(form);
  if (valueForm.parents) {
    valueForm.regionPath = valueForm.parents?.join(",");
    if (valueForm.id) {
      valueForm.parentId = valueForm.parents[valueForm.parents.length - 2] ?? 0;
    } else {
      valueForm.parentId = valueForm.parents[valueForm.parents.length - 1] ?? 0;
    }
  }
  areaManger.toSubmit();
}
function handleNodeClick(e) {
  console.log(e);
  algorithmManage.form.value.regionalId = e.id;
  algorithmManage.search.value.regionalId = e.id;
  algorithmManage.search.value.status = 0;
  areaManger.form.value.id = e.id;
  algorithmManage.getList({ regionalId: e.id });
}

function changeState(data, e) {
  request({
    url: "/yunshou/aiRegionalLocation/updateRunningState",
    method: "POST",
    data: {
      id: data.id,
      runningState: e,
    },
  }).then(() => {
    proxy.$modal.msgSuccess("操作成功！");
    algorithmManage.getList({ regionalId: data.regionalId });
  });
}
</script>
  
<style scoped lang="scss">
@import url("./index.scss");
.left-list {
  min-height: 700px;
}
.add-but {
  position: absolute;
  display: flex;
  top: 30px;
  right: 30px;
}
.right-list {
  min-height: 700px;
  .alg-list {
    display: grid;
    // grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
    .el-card {
      border: 1px soild #ff6700;
    }
    .alg-item {
      width: 100%;
      // min-height: 350px;
      position: relative;
    }
  }
}
.danger-list {
  min-height: 700px;
  .alg-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 16px;
    .el-card {
      border: 1px soild #ff6700;
    }
    .alg-item {
      width: 100%;
      // min-height: 350px;
      cursor: pointer;
      position: relative;
    }
    .el-form-item--default,
    .el-form-item {
      font-size: 12px;
      margin-bottom: 0px;
    }
  }
}

.cleartitle {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
  
  