<script setup lang="ts">
// import axios from "axios";
import { onMounted, ref, reactive } from "vue";
// import dplayer from "@/components/VideoPlayer/MyPlayer.vue";
// import OurPlayer from "@/components/VideoPlayer/OurPlayer.vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { PureTable } from "@pureadmin/table";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
// import { getConfig } from "@/config";
// import { getToken, formatToken } from "@/utils/auth";
import { getHomeList, getEvents } from "@/api/home";
import { welcomeUtil } from "./hook";

defineOptions({
  name: "Welcome"
});

// const AdminHostUrl = getConfig().AdminHostUrl;
const { openDialog } = welcomeUtil();
const formInline = reactive({
  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"
});
// const currentPlayingIndex = ref(-1); // 当前正在播放的视频索引，默认为没有视频正在播放

// 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));
// if (currentPlayingIndex.value !== -1) {
//   const videoElement = document.getElementById(
//     "video-" + currentPlayingIndex.value
//   );
//   videoElement.pause(); // 暂停当前正在播放的视频
// }
// currentPlayingIndex.value = index;
// }

function onSearch() {
  const params = {
    start_time: formInline.date === null ? undefined : formInline.date[0],
    end_time: formInline.date === null ? undefined : formInline.date[1],
    police_id: formInline.policeId || undefined,
    event_type: formInline.event || undefined,
    violation: violationMap.value[formInline.violation] || undefined,
    violation_type: formInline.violationType || undefined,
    page: currentPage.value || undefined,
    page_size: pageSize.value || undefined
  };
  getHomeList(params).then(response => {
    const dataList = response;
    totalNumber.value = dataList.count;
    pagination.total = dataList.count;
    if (!isDisplay) {
      tableData.value = dataList.results.filter(data => {
        return data.is_display === true;
      });
    } else {
      tableData.value = dataList.results;
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  });
  // 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;
  //     }
  //     setTimeout(() => {
  //       loading.value = false;
  //     }, 500);
  //   })
  //   .catch(error => {
  //     ElMessage({
  //       message: "网络暂不通畅",
  //       type: "warning"
  //     });
  //     setTimeout(() => {
  //       loading.value = false;
  //     }, 500);
  //     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
    });
};

async function getEvent() {
  // axios({
  //   url: AdminHostUrl + "events",
  //   headers: {
  //     token: formatToken(getToken().accessToken)
  //   }
  // })
  //   .then(response => {
  //     eventMap.value = response.data.data;
  //     // console.log(eventMap.value);
  //   })
  //   .catch(error => {
  //     ElMessage({
  //       message: "网络暂不通畅",
  //       type: "warning"
  //     });
  //     console.log(error);
  //   });
  const { results } = await getEvents();
  eventMap.value = results;
}

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

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

const columns: TableColumnList = [
  {
    label: "记录仪日期时间",
    prop: "record_time",
    minWidth: 100,
    sortable: true
  },
  {
    label: "警号",
    prop: "police_id",
    minWidth: 100
  },
  {
    label: "违法行为",
    prop: "event_type",
    minWidth: 100
  },
  {
    label: "是否违规",
    prop: "is_violation",
    minWidth: 100,
    slot: "violation"
  },
  {
    label: "违规行为",
    prop: "ai_analysis",
    minWidth: 100
  },
  {
    label: "时间点",
    prop: "relative_time",
    minWidth: 100
  },
  {
    label: "缩率图",
    slot: "image"
  },
  {
    label: "车牌号",
    prop: "car_number",
    minWidth: 100
  },
  // {
  //   label: "视频",
  //   slot: "video"
  // },
  {
    label: "操作",
    fixed: "right",
    width: 180,
    slot: "operation"
  }
];
const loading = ref(true);
const pagination = reactive<PaginationProps>({
  total: totalNumber.value,
  pageSize: pageSize.value,
  currentPage: currentPage.value,
  background: true
});
function handleUpdate(row) {
  openDialog("我的", row);
  console.log(row);
}
// function handleDelete(row) {
//   console.log(row);
// }
onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="main">
    <el-dialog
      width="60%"
      v-model="dialogVisible"
      :before-close="handleClose"
      destroy-on-close
    >
      <!-- <our-player /> -->
    </el-dialog>
    <el-form
      :inline="true"
      :model="formInline"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <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="getEvent"
        >
          <el-option
            v-for="(event, type) in eventMap"
            :key="type"
            :label="event"
            :value="event"
          />
        </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-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>
    <PureTableBar title="首页列表" :columns="columns" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          adaptive
          align-whole="center"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="tableData"
          :columns="dynamicColumns"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #violation="{ row }">
            {{ row.is_violation ? "是" : "否" }}
          </template>
          <template #image="{ row, index }">
            <el-image
              preview-teleported
              loading="lazy"
              :src="row.small_image"
              :preview-src-list="[row.small_image]"
              :initial-index="index"
              fit="cover"
              class="w-[100px] h-[100px]"
            />
          </template>
          <!-- <template #video="{ row, index }">
            <video
              width="180"
              height="180"
              controls
              :id="'video-' + index"
              @play="playVideo(row, index)"
            >
              <source :src="row.video_dir" type="video/mp4" />
            </video>
          </template> -->
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="handleUpdate(row)"
            >
              播放视频
            </el-button>
            <!-- <el-popconfirm title="是否确认删除?" @confirm="handleDelete(row)">
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm> -->
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <!-- <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="违法行为" />

      <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 {
  padding: 0;
  list-style-type: none;
}

a {
  color: #42b983;
}

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

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

.tablePage {
  display: flex;
  justify-content: flex-end;
  margin: 0 auto;
}
</style>
