<template>
  <div class="alarm-all">
    <a-grid :cols="4" :col-gap="20" :row-gap="16" class="grid-demo-grid">
      <a-grid-item class="demo-item">
        <label>{{ $t('previewList.bjlx') }}</label>
        <a-select
          v-model="paramObj.AlertType"
          allow-clear
          :style="{ width: '320px' }"
          :placeholder="$t('previewList.qxz')"
        >
          <a-option
            v-for="item in typeAlarmOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-option
          >
        </a-select>
      </a-grid-item>
      <a-grid-item class="demo-item">
        <label>{{ $t('previewList.bjsj') }}</label>
        <a-range-picker
          show-time
          :time-picker-props="{ defaultValue: ['00:00:00', '00:00:00'] }"
          format="YYYY-MM-DD HH:mm:ss"
          @ok="onOk"
        />
      </a-grid-item>
      <a-grid-item class="demo-item">
        <label>{{ $t('previewList.bjgd') }}</label>
        <a-select
          v-model="paramObj.Archived"
          allow-clear
          :style="{ width: '320px' }"
          :placeholder="$t('previewList.qxz')"
        >
          <a-option
            v-for="item in alarmArchivingOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-option
          >
        </a-select>
      </a-grid-item>
      <a-grid-item class="demo-item">
        <a-radio-group
          type="button"
          :model-value="radioActive"
          @change="(v) => (radioActive = v)"
        >
          <a-radio value="bg">{{ $t('previewList.bg') }}</a-radio>
          <a-radio value="gg">{{ $t('previewList.gg') }}</a-radio>
        </a-radio-group>
        <a-button type="primary" size="small" @click="searchBtn">{{
          $t('previewList.cx')
        }}</a-button>
      </a-grid-item>
    </a-grid>
    <template v-if="radioActive === 'bg'">
      <a-table
        :data="alarmData"
        :scroll="{ y: '100%' }"
        :pagination="false"
        :bordered="{ cell: true }"
        :loading="loading"
        style="height: calc(100% - 114px)"
      >
        <template #columns>
          <a-table-column
            :title="$t('previewList.bjlx')"
            :ellipsis="true"
            :tooltip="true"
            data-index="type"
          >
          </a-table-column>
          <a-table-column
            :title="$t('previewList.bjsj')"
            data-index="timeN"
            :width="180"
          ></a-table-column>
          <a-table-column
            :title="$t('previewList.status')"
            data-index="status"
            :width="150"
            :body-cell-style="
              (record) => ({
                background: record.status ? '#4cd26380' : '#7e2d2d80',
              })
            "
          >
            <template #cell="{ record }">
              <span>{{
                record.status ? $t('previewList.ycl') : $t('previewList.wcl')
              }}</span>
            </template>
          </a-table-column>
          <a-table-column
            :title="$t('previewList.bjgd')"
            data-index="AlarmArchiving"
            :width="150"
            :body-cell-style="
              (record) => ({
                background:
                  record.AlarmArchiving == '0'
                    ? '#ffb65d80'
                    : record.AlarmArchiving == '1'
                    ? '#4cd26380'
                    : '#7e2d2d80',
              })
            "
          >
            <template #cell="{ record }">
              <span>{{
                record.AlarmArchiving == '0'
                  ? '未归档'
                  : record.AlarmArchiving == '1'
                  ? '正确报警'
                  : '错误报警'
              }}</span>
            </template>
          </a-table-column>
          <!-- <a-table-column
            :title="$t('previewList.dqstatus')"
            data-index="isRead"
            :width="150"
            :body-cell-style="
              (record) => ({
                background: record.isRead ? '' : '#2d4f7e',
              })
            "
          >
            <template #cell="{ record }">
              <span>{{
                record.isRead ? $t('previewList.yd') : $t('previewList.wd')
              }}</span>
            </template>
          </a-table-column> -->
          <a-table-column :title="$t('previewList.cz')" :width="150">
            <template #cell="{ record }">
              <a-button type="text" size="mini" @click="showView(record)">{{
                $t('previewList.ck')
              }}</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </template>
    <template v-else>
      <a-scrollbar>
        <ul class="img-list">
          <li
            v-for="(item, i) in alarmImgData"
            :key="i"
            class="img-list-item"
            @click="showView(item)"
          >
            <a-spin v-if="item.imgLoading" dot />
            <img :src="item.tImg" @load="() => (item.imgLoading = false)" />
          </li>
        </ul>
        <a-empty v-if="!alarmImgData.length" />
      </a-scrollbar>
    </template>
    <div class="pagination">
      <a-pagination
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="pageChange"
        @page-size-change="pageSizeChange"
      />
    </div>
    <ViewDrawer
      ref="viewDrawerRef"
      :view-data="viewData"
      :guid="guid"
      :is-show-cl="true"
      @update:view-data="(v) => Object.assign(viewData, v)"
    />
  </div>
</template>

<script setup lang="ts">
  // import dayjs from 'dayjs';
  import { useAppStore } from '@/store';
  import { ref, reactive, onMounted, provide } from 'vue';
  import {
    getAlarmImgFiles,
    getAlarmLog,
    getAlgorithmList,
  } from '@/api/system';
  import ViewDrawer from './view-drawer.vue';

  interface AlarmData {
    [key: string]: number | string | boolean;
  }
  const app = useAppStore();
  const props = defineProps<{
    guid?: string;
  }>();
  const viewDrawerRef = ref();
  const radioActive = ref<any>('bg');
  const paramObj = reactive<{
    PageNum: number;
    PageSize: number;
    AlertType: string;
    Archived: string;
    StartDate: string | number;
    EndDate: string | number;
  }>({
    PageNum: 1,
    PageSize: 10,
    AlertType: '',
    Archived: '',
    StartDate: '',
    EndDate: '',
  });
  const loading = ref(false);
  const total = ref(0);
  const typeAlarmOptions = ref<any[]>([]);
  const alarmArchivingOptions = ref<any[]>([
    {
      label: '未归档',
      value: '0',
    },
    {
      label: '正确报警',
      value: '1',
    },
    {
      label: '错误报警',
      value: '2',
    },
  ]);
  const viewData = ref<AlarmData>({});
  provide('viewData', viewData);
  const alarmData = ref<AlarmData[]>([
    // {
    //   type: '行人闯入',
    //   timeN: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    //   status: 0,
    //   isRead: false,
    // },
  ]);
  const alarmImgData = ref<any[]>([
    // {
    //   url: 'https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp',
    //   time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    // },
  ]);

  const getList = async () => {
    loading.value = true;
    alarmImgData.value = [];
    try {
      const alarmLog = await getAlarmLog(paramObj, { GUID: props.guid });
      total.value = alarmLog.data.TotalCount;
      const jsonPromises = alarmLog.data.AlarmList.map((v: any) =>
        getAlarmImgFiles(v.JsonFile, { GUID: props.guid })
      );
      Promise.all(jsonPromises)
        .then((results) => {
          alarmData.value = alarmLog.data.AlarmList.map(
            (item: any, i: number) => {
              return {
                ...item,
                type: item.Name,
                timeN: item.CreatedAt,
                status: +item.HandleStatus,
                isRead: false,
                img: `${app.ip}/rpc/rabbitMQ/KunPengYun/Files/${item.OriginPicture}&GUID=${props.guid}`,
                tImg: `${app.ip}/rpc/rabbitMQ/KunPengYun/Files/${item.Thumbnail}&GUID=${props.guid}`,
                imgJson: results[i],
                imgLoading: true,
                AlarmArchiving: `${item.Archived}`,
              };
            }
          );
          alarmImgData.value = alarmData.value;
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    } catch (e) {
      loading.value = false;
    }
  };
  const onOk = (value: any[], date: any[], dateString: any[]) => {
    paramObj.StartDate = new Date(dateString[0]).getTime() / 1000;
    paramObj.EndDate = new Date(dateString[1]).getTime() / 1000;
  };
  const pageChange = (current: number) => {
    paramObj.PageNum = current;
    getList();
  };
  const pageSizeChange = (pageSize: number) => {
    paramObj.PageSize = pageSize;
    getList();
  };

  const showView = (record: any) => {
    viewData.value = record;
    viewDrawerRef.value.open();
  };

  const searchBtn = () => {
    getList();
  };
  onMounted(async () => {
    const algorithmList = await getAlgorithmList({}, { GUID: props.guid });
    // eslint-disable-next-line no-restricted-syntax, guard-for-in
    for (const key in algorithmList.data) {
      typeAlarmOptions.value.push({
        label: algorithmList.data[key],
        value: key,
      });
    }
    getList();
  });
</script>

<style lang="less" scoped>
  .alarm-all {
    display: flex;
    flex-direction: column;
    height: 100%;
    gap: 15px;
    .pagination {
      display: flex;
      justify-content: flex-end;
    }
    .demo-item {
      display: flex;
      align-items: center;
      gap: 10px;
      & > label {
        min-width: 65px;
      }
      &:last-child {
        justify-content: flex-end;
      }
    }
    .arco-scrollbar {
      height: calc(100% - 114px);
      :deep(.arco-scrollbar-container) {
        height: 100%;
        overflow-y: auto;
      }
    }
    .img-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      grid-template-rows: repeat(auto-fill, 135px);
      gap: 15px;
      .img-list-item {
        width: 100%;
        height: 135px;
        overflow: hidden;
        background-color: #333;
        cursor: pointer;
        position: relative;
        .arco-spin {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
        img {
          height: 100%;
          width: 100%;
          object-fit: cover;
        }
      }
    }
  }
</style>
