<script setup lang="ts">
import axios from "axios";
import { onMounted, ref } from "vue";
import dplayer from "@/components/VideoPlayer/MyPlayer.vue";
import OurPlayer from "@/components/VideoPlayer/OurPlayer.vue";
import { ElMessageBox } from "element-plus";
import { getConfig } from "@/config";
import { getToken, formatToken } from "@/utils/auth";

defineOptions({
  name: "Welcome"
});

const AdminHostUrl = getConfig().AdminHostUrl;

const formInline = ref({
  date: [],
  policeId: "",
  event: "",
  violation: "",
  violationType: ""
});

const currentPage = ref(1);
const totalNumber = ref(0);
const pageSize = ref(10);
const isDisplay = true;

const dialogVisible = ref(false);

const tableData = ref([]);

const eventMap = ref({});

const violationMap = ref({
  "是": "1",
  "否": "0",
  "所有": "2"
})


function playVideo(data) {
  data = JSON.parse(JSON.stringify(data));
  // console.log(AdminHostUrl)
  dialogVisible.value = true;
  const highlights = [
    // 进度条时间点高亮
    {
      text: data.event_type,
      time: data.relative_time
    }
  ];
  sessionStorage.setItem("video_url", data.video_dir);
  sessionStorage.setItem("highlights", JSON.stringify(highlights));
}

function onSearch() {
  let start_time;
  let end_time;
  if (formInline.value.date) {
    start_time = formInline.value.date[0];
    end_time = formInline.value.date[1];
  }

  axios({
    url: AdminHostUrl,
    params: {
      start_time: start_time || undefined,
      end_time: end_time || undefined,
      police_id: formInline.value.policeId || undefined,
      event_type: formInline.value.event || undefined,
      violation: violationMap.value[formInline.value.violation] || undefined,
      violation_type: formInline.value.violationType || undefined,
      page: currentPage.value || undefined,
      page_size: pageSize.value || undefined
    },
    headers: {
      token: formatToken(getToken().accessToken)
    }
  })
    .then(response => {
      // console.log(response.data);
      totalNumber.value = response.data.count;
      if (!isDisplay) {
        tableData.value = response.data.results.filter(data => {
          return data.is_display === true;
        });
      } else {
        tableData.value = response.data.results;
      }
    })
    .catch(error => {
      // console.log("请求失败");
      console.log(error);
    });
}

function handleSearch() {
  currentPage.value = 1;
  onSearch();
}

function handleRefresh() {
  onSearch();
}

function handleSizeChange(val) {
  pageSize.value = val;
  onSearch();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  onSearch();
}

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定关掉此视频")
    .then(() => {
      dialogVisible.value = false;
      done();
    })
    .catch(() => {
      // catch error
    });
};

function getEvents() {

  axios({
    url: AdminHostUrl + "events",
    headers: {
      token: formatToken(getToken().accessToken)
    }
  })
    .then(response => {
      eventMap.value = response.data.data;
      // console.log(eventMap.value);
    })
    .catch(error => {
      // console.log("请求失败");
      console.log(error);
    });

}

function pickerOptions(time){
  return time.getTime() > Date.now()
}

const now_date = new Date();
now_date.setMonth(now_date.getMonth() - 1)
const lastMonth = now_date

onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="hello">
    <el-dialog
      width="60%"
      v-model="dialogVisible"
      :before-close="handleClose"
      destroy-on-close
    >
      <our-player></our-player>
    </el-dialog>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="日期:" style="font-weight: bold">
        <el-date-picker
          v-model="formInline.date"
          type="daterange"
          unlink-panels
          range-separator="--"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :disabled-date="pickerOptions"
          :default-value="lastMonth"
        />
      </el-form-item>

      <el-form-item label="警号:">
        <el-input v-model="formInline.policeId" placeholder="警号" clearable style="width: 198px" />
      </el-form-item>

      <el-form-item label="违法行为:">
        <!--        <el-input v-model="formInline.event" placeholder="事件"/>-->
        <el-select v-model="formInline.event" placeholder="违法行为" clearable @click="getEvents">
          <el-option v-for="(event, type) in eventMap" :key="type" :label="event" :value="event"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否违规:">
        <el-select v-model="formInline.violation" placeholder="是否违规" clearable>
          <el-option v-for="(event, type) in violationMap" :key="event" :label="type" :value="type"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="违规行为:">
        <el-input v-model="formInline.violationType" placeholder="违规行为" clearable style="width: 198px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleRefresh"
        >刷新
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      stripe
      :default-sort="{ prop: 'record_time', order: 'descending' }"
      style="width: 100%"
    >
      <el-table-column prop="record_time" sortable label="记录仪日期时间" />
      <el-table-column prop="police_id" label="警号" />
      <el-table-column prop="event_type" label="违法行为">
        <template v-slot="scope">
          <span>
            {{ scope.row.event_type || "未定义事件" }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="is_violation" label="是否违规">
        <template v-slot="scope">
          <span v-if="scope.row.is_violation">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>

      <el-table-column prop="ai_analysis" label="违规行为" />
      <el-table-column prop="relative_time" label="时间点">
        <template v-slot="scope">
          <span>第 {{ scope.row.relative_time }} 秒</span>
        </template>
      </el-table-column>

      <el-table-column prop="small_image" label="缩率图">
        <template v-slot="scope">
          <el-image
            :preview-src-list="[scope.row.small_image]"
            style="width: 65px; height: 65px"
            :src="scope.row.small_image"
            :preview-teleported="true"
          />
        </template>
      </el-table-column>

      <el-table-column prop="car_number" label="车牌号" />

      <el-table-column show-overflow-tooltip label="视频">
        <template v-slot="scope">
          <el-button @click="playVideo(scope.row)">
            <span v-if="scope.row.video_dir">播放视频</span>
            <span v-else>暂无视频</span>
          </el-button>

        </template>

      </el-table-column>
    </el-table>
    <el-pagination
      class="tablePage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      :total="totalNumber"
    />
  </div>
</template>

<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
}

a {
  color: #42b983;
}

.hello {
  margin: 5px auto;
  text-align: right;
  overflow: hidden;
}

.demo-form-inline {
  align-items: center;
  display: flex;
  justify-content: flex-end;
  margin: 0 auto;
}

.tablePage {
  display: flex;
  justify-content: flex-end;
  margin: 0 auto;
}

</style>
