<script lang="tsx" setup>
import { onMounted, reactive, ref, watch, h, watchEffect, nextTick } from 'vue';
import { NButton, NTag, useNotification, NImage, NSpace } from 'naive-ui';
import { ArrowLeft20Filled } from '@vicons/fluent';
import { EllipsisVertical } from '@vicons/ionicons5';
/** api_algorithms 算法列表 api_modifyAlgorithms 修改算法 */
import { api_getAlarmLog, api_delAlarmLog, api_modifyAlarmLog, api_getAreaNode, api_modifyAlgorithms } from '@/api/index';
import type { ItablePagination } from '@/views/AlgorithmConfiguration/index';
import { Message } from '@vicons/tabler';
import JSMpeg from '@cycjimmy/jsmpeg-player';
import { localStg } from '@/utils/storage';

const page = ref(1);
// const serviceUrl = 'ws://192.168.1.140:9999';

const serviceUrl = import.meta.env.VITE_VIDEO_URL;
const apiUrl = import.meta.env.VITE_SERVICE_URL;
const webSocketUrl = import.meta.env.VITE_WEBSOCKET_URL;


const pageSize = ref(10);
const showModal = ref(false);
const tableData = ref([
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  },
  {
    name: "!",
    status: 1
  }
]);
const gridLogStatus = ref('')
const isTable = ref(true);

const tableParam = reactive({
  algorithmGrade: "",  // 报警等级
  algorithmName: "",   // 算法名称
  pageNum: "",         // 页码
  pageSize: "",        // 展示条数
  resourceNo: "",       // 监控点位
  status: "",           // 报警处理状态
});

const isInfo = ref(false);
const notification = useNotification();
const show = ref(false);
const isDefaultPreview = ref(true);

const value = ref(null);

// 下拉 - 报警状态配置对象
const alarmStatusOpt = reactive([
  {
    label: '待处理',
    value: '0',
  },
  {
    label: '正确报警',
    value: '1',
  },
  {
    label: '错误报警',
    value: '2',
  },
]);

// 下拉 - 算法报警等级
const gradeOptions = reactive([
  {
    label: '一级',
    value: '0',
  },
  {
    label: '二级',
    value: '1',
  },
  {
    label: '三级',
    value: '2',
  },
  {
    label: '四级',
    value: '3',
  },
  {
    label: '五级',
    value: '4',
  }
]);

// 下拉 - 状态
const options = reactive([
  {
    label: '错误报警',
    value: '2',
  },
  {
    label: '正确报警',
    value: '1'
  }
]);

// 下拉 - 节点信息
let nodeOptions = reactive([]);

interface INodeInfo {
  label: string;
  value?: string;
  id?: string;
}

const getTreeNode = async () => {
  let obj = [];

  const getNodeInfo = (arr: INodeInfo[], data: INodeInfo[]) => {
    data.map(item => {
      arr.push({ label: item.label, value: item.id })
      Array.isArray(item.children) && getNodeInfo(arr, item.children)
    })

  }



  await api_getAreaNode().then(res => {
    if (res.data.code === 200) {
      getNodeInfo(nodeOptions, res.data.data.items);
      // nodeOptions = obj;
      nodeOptions = nodeOptions.slice(1);
      // console.log(" =================== obj", obj, res.data.data.items)
    }
  })
}

// 删除日志
const delAlarmLog = async (id: strring) => {
  await api_delAlarmLog(id).then(res => {
    if (res.data.code === 200) {
      getAlarmLog();
      notification.success({
        duration: 3000,
        content: '删除成功!'
      });
    } else {
      notification.error({
        content: res.data.msg,
        duration: 3000
      });
    }
  })
}

const handleUpdateStatusValue = (val: string) => {
  tableParam.status = val;
}

// 获取日志
const total = ref(0);
const getAlarmLog = async () => {
  show.value = true;

  const param = {
    ...tableParam,
    pageNum: page.value,
    pageSize: pageSize.value
  };

  await api_getAlarmLog(param)
    .then(res => {
      if (res.data.code === 200) {
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
      }
      show.value = false;
    })
    .catch(() => (show.value = false));
};

// 变更状态
const modifyAlramStatus = async (id: string, status: string) => {
  await api_modifyAlarmLog(id, status).then(res => {
    if (res.data.code === 200) {
      gridLogStatus.value = '';
      getAlarmLog();
      notification.success({
        duration: 3000,
        content: '状态变更成功!'
      });
      showModal.value = false;
    } else {
      notification.error({
        content: res.data.msg,
        duration: 3000
      })
    }
  })
};

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
];

/** algorithmAddress : "http://localhost:8080" algorithmName : "人员打电话检测" grade : 2 id : "9" version : "v1.0" */

const curInfo = ref({});
let cLogInfo = reactive({});
const tableColumn = [
  {
    title: 'ID',
    key: 'id',
    align: 'center',
  },
  {
    title: '视频分析任务名称',
    key: 'videoName',
    align: 'center',
  },
  {
    title: '摄像头名称',
    key: 'cameraName',
    align: 'center',
  },
  {
    title: '报警图片',
    key: 'image',
    align: 'center',
    render: (row: any) => {
      let r = row;
      return h(NImage, {
        class: "nnimage",
        width: '100',
        src: row.image,
        "preview-disabled": true,
        onclick: (e) => {
          e.stopPropagation();
          e.preventDefault();
          isDefaultPreview.value = true;
          switchVideoPlayer();
          cLogInfo = r;;
          showModal.value = true;
        }
      });
    }
  },
  {
    title: '报警时间',
    key: 'createTime',
    align: 'center',
    // minWidth: 120,
  },
  {
    title: '算法名称',
    key: 'algorithmName',
    align: 'center',
  },
  {
    title: '算法报警等级',
    key: 'algorithmGrade',
    align: 'center',
    render: (row: any) => {
      return row.algorithmGrade === 0 ? (
        <NTag type="error">一级</NTag>
      ) : row.algorithmGrade === 1 ? (
        <NTag type="warning">二级</NTag>
      ) : row.algorithmGrade === 2 ? (
        <NTag type="info">三级</NTag>
      ) : row.algorithmGrade === 3 ? (
        <NTag type="success">四级</NTag>
      ) : (
        <NTag>五级</NTag>
      );
    }
  },
  {
    title: '报警处理状态',
    key: 'status',
    align: 'center',
    render: (row: any) => {
      let status = row.status;
      return status === 0 ? (<n-button quaternary type="warning"> 待处理 </n-button>) : status === 1 ? <n-button quaternary type="error">正确报警</n-button> : <n-button quaternary> 错误报警 </n-button>
    }
  },
  {
    title: '操作',
    minWidth: 220,
    align: 'center',
    key: 'actions',
    render(row: any) {
      return (
        <NSpace justify='center'>
          <n-button
            onClick={() => modifyAlramStatus(row.id, '1')}
            type="primary"
            quater
            quaternary
          >
            正确报警
          </n-button>

          <n-button
            onClick={() => modifyAlramStatus(row.id, '2')}
            quater
            quaternary
            type="primary"
          >
            错误报警
          </n-button>

          <n-button
            onClick={() => delAlarmLog(row.id)}
            quaternary
            type="error"
          >
            删除
          </n-button>
        </NSpace>
      );
    }
  }
];

const selectWebCaM = ref<any>([]);

const handleCheck = (rowKeys: any) => {
  selectWebCaM.value = rowKeys;
};

const generalOptions = reactive([
  {
    id: 0,
    label: '一级'
  },
  {
    id: 1,
    label: '二级'
  },
  {
    id: 2,
    label: '三级'
  },
  {
    id: 3,
    label: '四级'
  },
  {
    id: 4,
    label: '五级'
  }
]);

const onSubmit = async () => {
  await api_modifyAlgorithms(curInfo.value?.id, curInfo.value?.grade).then(res => {
    if (res.data.code === 200) {
      getAlarmLog();
      notification.success({
        duration: 4000,
        content: '修改成功!'
      });
    } else {
      notification.error({
        content: res.data.msg,
        duration: 4000
      });
    }
  });
};

watch(page, () => {
  getAlarmLog();
});

watch(pageSize, () => {
  getAlarmLog();
});

// 切换视频播放源头
const switchVideoPlayer = () => {
  console.log("switchVideoPlayer ==============", "rtsp://admin:gemho10-7@192.168.0.56:554/h264/ch1/main/av_stream`")
  // nextTick(() => {
  //   try {
  //     // 临时测试
  //     const rtsp1 = 'rtsp://admin:gemho10-7@192.168.0.56:554/h264/ch1/main/av_stream';
  //     // eslint-disable-next-line no-new
  //     new JSMpeg.Player(
  //       `ws://192.168.1.147:9999/rtsp?url=${btoa(rtsp1)}&scale=640:-1&-b:v=1k&brightness=0.2&saturation=1.8`,
  //       {
  //         canvas: document.getElementById('canvas-3'),
  //         preserveDrawingBuffer: true
  //       }
  //     );
  //   } catch (e) { }
  // })
}

watch(isDefaultPreview, (o, n) => {
  console.log("=============== 最新", o, n)

  if (!o) {
    nextTick(() => {
      try {
        // 临时测试
        const rtsp1 = 'rtsp://admin:gemho10-7@192.168.0.56:554/h264/ch1/main/av_stream';
        // eslint-disable-next-line no-new
        new JSMpeg.Player(
          `${serviceUrl}/rtsp?url=${btoa(rtsp1)}&scale=640:-1&-b:v=1k&brightness=0.2&saturation=1.8`,
          {
            canvas: document.getElementById('canvas-3'),
            preserveDrawingBuffer: true
          }
        );
      } catch (e) { }
    })
  }
});

onMounted(() => {
  getAlarmLog();
  getTreeNode();
});

</script>

<template>
  <div id="alarmLog">
    <NModal v-model:show="showModal">
      <NCard v-if="isDefaultPreview" style="width: 800px;" @close="showModal = false" closable>
        <template #header>
          <NFlex justify=" space-between">
            <NFlex justify="start" align="center">
              <NTag size="large" v-if="cLogInfo.algorithmGrade === 0" type="error"> 一 级 </NTag>
              <NTag size="large" v-else-if="cLogInfo.algorithmGrade === 1" type="warning"> 二 级 </NTag>
              <NTag size="large" v-else-if="cLogInfo.algorithmGrade === 2" type="info"> 三 级 </NTag>
              <NTag size="large" v-else-if="cLogInfo.algorithmGrade === 3" type="success"> 四 级 </NTag>
              <NTag size="large" v-else>五级</NTag>
              <NSpace style="font-size: 14px;">
                <span>{{ cLogInfo.algorithmName }}</span>
                <span>{{ cLogInfo.cameraName }}</span>
                <span>{{ cLogInfo.createTime }}</span>
              </NSpace>


              <!-- ======================= 状态 | S -->
              <n-tag v-if="cLogInfo.status === 0" :bordered="false" type="warning">
                处理中
              </n-tag>

              <n-tag v-if="cLogInfo.status === 1" :bordered="false" type="success">
                正确报警
              </n-tag>

              <n-tag v-if="cLogInfo.status === 2" :bordered="false" type="error">
                错误报警
              </n-tag>
              <!-- ======================= 状态 | E -->
            </NFlex>

            <!-- <NButton @click.stop="() => {
              isDefaultPreview = false;
            }" strong secondary type="info" size="small">回放</NButton> -->
          </NFlex>
        </template>
        <!-- 图片区域 -->
        <div style="width: 100%; height: 400px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
          <NImage :src="cLogInfo?.image" />
        </div>
        <!-- 操作区域 -->
        <template #footer>
          <NFlex justify="center">
            <NSpace>
              <n-button quaternary round type="primary"
                @click.stop="() => modifyAlramStatus(cLogInfo?.id, '1')">正确报警</n-button>
              <n-button quaternary round type="error"
                @click.stop="() => modifyAlramStatus(cLogInfo?.id, '2')">错误报警</n-button>
            </NSpace>
          </NFlex>
        </template>
      </NCard>

      <NCard v-else style="width: 800px;" @close="showModal = false" closable>
        <template #header>
          <span @click="() => {
            switchVideoPlayer();
            isDefaultPreview = true;
          }
            ">
            <NIcon size="20" style="position: relative; top: 2px;">
              <ArrowLeft20Filled />
            </NIcon>
            <span style="position: relative; top: -1px;  margin-left: 5px">返回</span>
          </span>
          <NDivider vertical />
          {{ cLogInfo.cameraName }}
        </template>
        <!-- 视频回放 -->
        <div style="width: 100%; height: 400px; padding-bottom: 10px;">
          <!-- MP4 切换视频 -->
          <video controls style="width: 100%; height: 100%; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);">
            <source :src="`${apiUrl}/v1/playVideo/${cLogInfo.remark}`" type="audio/mpeg">
            </source>
          </video>
        </div>
      </NCard>
    </NModal>

    <div v-if="!isInfo">
      <NSpin :show="show">
        <NCard size="medium">
          <!-- 筛选条件 -->
          <template #header>
            <n-flex justify="space-between">
              <n-row>
                <!--  -->
                <n-col :span="6">
                  <n-button-group>
                    <n-button @click="isTable = true">
                      <template #icon>
                        <icon-ic:round-table-view class="text-icon" />
                      </template>
                      表格
                    </n-button>
                    <n-button @click="isTable = false">
                      <!-- ic:twotone-format-list-bulleted -->
                      <template #icon>
                        <icon-ic:twotone-format-list-bulleted class="text-icon" />
                      </template>
                      <!-- ic:baseline-assistant-photo -->
                      宫格
                    </n-button>
                  </n-button-group>
                </n-col>
                <n-col :span="18">
                  <n-flex justify="end"><n-row gutter="12">
                      <n-col :span="5" key="resourceNo______">
                        <NSelect :options="nodeOptions" placeholder="监控点位" clearable
                          @update:value="(val) => tableParam.resourceNo = val" />
                      </n-col>
                      <n-col :span="5" key="grade______">
                        <NSelect clearable placeholder="算法报警等级" @update:value="(val) => tableParam.algorithmGrade = val"
                          :options="gradeOptions" />
                      </n-col>
                      <n-col :span="5" key="status______">
                        <NSelect clearable placeholder="报警处理状态" @update:value="(val) => tableParam.status = val"
                          :options="alarmStatusOpt" />
                      </n-col>
                      <n-col :span="5">
                        <n-input placeholder="算法名称" v-model:value="tableParam.algorithmName" />
                      </n-col>
                      <n-col :span="4">
                        <n-button type="primary" @click="() => getAlarmLog()">
                          <template #icon>
                            <icon-ic:baseline-search class="text-icon" />
                          </template>
                          查询</n-button>
                      </n-col>
                    </n-row></n-flex>
                </n-col>
              </n-row>
            </n-flex>
          </template>

          <div v-if="!isTable">
            <n-row gutter="12">
              <!-- ============================== 表格项 -->
              <n-col :span="6" v-for="item in tableData" :key="10000">
                <div
                  style="box-shadow: 2px 3px 10px rgba(24, 114, 240, 0.24); margin: 10px; padding: 0 0  5px 0 ; border-radius: 5px; overflow: hidden; min-width: 250px; cursor: pointer; ">
                  <div style="height: 150px; position: relative;">
                    <div
                      style="position: absolute;
                      cursor: pointer;
                      top: 7px; right: 7px; width: 27px; height: 27px; background-color: #fff; display: flex; justify-content: center; align-items: center; border-radius: 50%">
                      <n-popselect v-model:value="gridLogStatus"
                        @update:value="(val) => modifyAlramStatus(item.id, val)" :options="options" trigger="click">
                        <n-icon size="17" color="#333333">
                          <EllipsisVertical />
                        </n-icon>
                      </n-popselect>
                    </div>
                    <img @click="(e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      switchVideoPlayer();
                      cLogInfo = item;
                      isDefaultPreview = true;
                      showModal = true;
                    }"
                      style="width: 100%;  height: 100%; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); translate: scale(1);"
                      :src="item?.image" />
                  </div>
                  <n-flex style="margin: 5px 5px 2px 5px;" justify="space-between">
                    <span style="font-size: 15px; font-weight: 550;">
                      {{ item?.algorithmName || `` }}
                    </span>
                    <span style="font-size: 14px; color:#333;">
                      {{ item?.createTime || `` }}
                    </span>
                  </n-flex>
                  <n-flex style="margin: 0 5px;" align="center" justify="space-between;">
                    <span>{{ item.cameraName }}</span>
                    <n-button v-if="item.status === 0" quaternary type="warning"> 待处理 </n-button>
                    <n-button v-else-if="item.status === 1" quaternary type="error">正确报警</n-button>
                    <n-button v-else quaternary> 错误报警 </n-button>
                  </n-flex>
                </div>
              </n-col>
            </n-row>
          </div>

          <!-- Table 数据 -->
          <NDataTable :bordered="true" v-else :row-key="row => row.id" :columns="tableColumn" :data="tableData"
            @update:checked-row-keys="handleCheck" />


          <div style="display: flex; justify-content: end">
            <NPagination
             :item-count="total"
            v-model:page="page" v-model:page-size="pageSize" style="margin-top: 20px"
              :display-order="['quick-jumper', 'pages', 'size-picker']" :page-count="100" show-quick-jumper
              show-size-picker :page-sizes="pageSizes" />
          </div>
        </NCard>
      </NSpin>
    </div>

    <NRow v-else gutter="12">
      <NCol :span="8">
        <NCard>
          <template #header-extra>
            <span style="font-size: 15px">
              ID : {{ curInfo?.id }}
              <NDivider vertical />
              版本 {{ curInfo?.version }}
            </span>
          </template>
          <template #header>
            <span style="font-size: 15px" @click="() => {
              isInfo = false;
            }
              ">
              <NIcon>
                <ArrowLeft20Filled />
              </NIcon>
              <span style="position: relative; top: -1px; margin-left: 5px">返回</span>
            </span>
            <NDivider vertical />
            {{ curInfo.algorithmName }}
          </template>
          <template #footer>
            <div style="font-weight: 550">选择报警类型</div>
            <NSelect v-model:value="curInfo.grade" style="margin-top: 10px" value-field="id" label-field="label"
              placeholder="请选择分组" :options="generalOptions" />
          </template>
          <template #action>
            <div class="active">
              <NButton type="info" @click="onSubmit">保存</NButton>
            </div>
          </template>
        </NCard>
      </NCol>
    </NRow>
  </div>
</template>

<style>
#alarmLog {
  .active {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.nnimage {
  cursor: pointer;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2) !important;
}
</style>
