<script setup lang="ts">
// import axios from "axios";
import { onMounted, ref, reactive, toRaw } 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";
import TypeIt from "@/components/ReTypeit";
import Pie from "./components/Pie.vue";
import TopLine from "./components/TopLine.vue";
import Bar from "./components/Bar.vue";
import Radar from "./components/Radar.vue";
import Line from "./components/Line.vue";
import { abnormal, resource } from "./static";

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;
    }, 800);
  });
  // 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);
}
const dataValue1 = [2000, 3000, 2000, 2500, 3500, 3100];
const dataValue2 = [3100, 3500, 2000, 2500, 2000, 3000];
// function handleDelete(row) {
//   console.log(row);
// }
// const skeletonLoading = ref(true);
// setTimeout(() => {
//   skeletonLoading.value = !skeletonLoading.value;
// }, 800);
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]"
      v-if="false"
    >
      <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"
      v-if="false"
    >
      <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 #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="handleUpdate(row)"
            >
              播放视频
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-row :gutter="16">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <div
                class="w-full h-[32px] flex items-center justify-between mb-[8px]"
              >
                <div class="flex items-center justify-start">
                  <!-- <img :src="abnormal" /> -->
                  <component :is="toRaw(abnormal)" :key="abnormal" />

                  <!-- <SvgComponent :data="abnormal" /> -->
                  <!-- <div class="abnormal-icon">
                    <abnormal />
                  </div> -->
                  <span class="abnormal-title ml-2">异常总量</span>
                </div>
                <div class="flex items-center">
                  <div class="flex items-center mr-3">
                    <span class="abnormal-proportion">周同比12%</span>
                    <span class="delta-down" />
                  </div>
                  <div class="flex items-center">
                    <span class="abnormal-proportion">日同比11%</span>
                    <span class="delta" />
                  </div>
                </div>
              </div>
              <div class="w-full h-10 flex items-center">
                <h1 class="text-3xl">123131</h1>
              </div>
              <TopLine :data="dataValue1" color="#FECA50" />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <div
                class="w-full h-[32px] flex items-center justify-between mb-[8px]"
              >
                <div class="flex items-center justify-start">
                  <component :is="toRaw(resource)" :key="resource" />
                  <!-- <div class="resource-icon">
                    <resource />
                  </div> -->
                  <span class="abnormal-title ml-2">资源使用</span>
                </div>
                <div class="flex items-center">
                  <div class="flex items-center mr-3">
                    <span class="abnormal-proportion">周同比12%</span>
                    <span class="delta-down" />
                  </div>
                  <div class="flex items-center">
                    <span class="abnormal-proportion">日同比11%</span>
                    <span class="delta" />
                  </div>
                </div>
              </div>
              <div class="w-full h-10 flex items-center">
                <h1 class="text-3xl">123131</h1>
              </div>
              <TopLine :data="dataValue2" color="#5681F2" />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <div
                class="w-full h-[32px] flex items-center justify-between mb-[8px]"
              >
                <div class="flex items-center justify-start">
                  <!-- <component :is="toRaw(analysis)" :key="analysis" /> -->
                  <svg
                    width="32"
                    height="32"
                    viewBox="0 0 32 32"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <rect width="32" height="32" fill="#EEEEEE" />
                    <g clip-path="url(#clip)">
                      <rect
                        width="1440"
                        height="900"
                        transform="translate(-1048 -108)"
                        fill="#F5F5F5"
                      />
                      <rect
                        x="-16"
                        y="-16"
                        width="384"
                        height="156"
                        rx="8"
                        fill="white"
                      />
                      <circle cx="16" cy="16" r="16" fill="url(#linear)" />
                      <path
                        d="M22.6668 9.66675H9.3335V18.3334H22.6668V9.66675Z"
                        fill="white"
                        stroke="white"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                      <path
                        d="M15.3335 12.6667L17.3335 14.0001L15.3335 15.3334V12.6667Z"
                        fill="white"
                        stroke="#2ED7D7"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                      <path
                        d="M11.6667 21.3333H10"
                        stroke="white"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                      <path
                        d="M13.6665 21.3333H21.9998"
                        stroke="white"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                      <path
                        d="M13.6665 21.3333C13.6665 21.8856 13.2188 22.3333 12.6665 22.3333C12.1142 22.3333 11.6665 21.8856 11.6665 21.3333C11.6665 20.781 12.1142 20.3333 12.6665 20.3333C13.2188 20.3333 13.6665 20.781 13.6665 21.3333Z"
                        stroke="white"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                    </g>
                    <defs>
                      <linearGradient
                        id="linear"
                        x1="4.5"
                        y1="7"
                        x2="27.5"
                        y2="30"
                        gradientUnits="userSpaceOnUse"
                      >
                        <stop stop-color="#5FFCFC" />
                        <stop offset="1" stop-color="#13C2C2" />
                      </linearGradient>
                      <clipPath id="clip">
                        <rect
                          width="1440"
                          height="900"
                          fill="white"
                          transform="translate(-1048 -108)"
                        />
                      </clipPath>
                    </defs>
                  </svg>
                  <span class="abnormal-title ml-2">今日分析进度</span>
                </div>
                <div class="flex items-center">
                  <div class="flex items-center mr-3">
                    <span class="abnormal-proportion">周同比12%</span>
                    <span class="delta-down" />
                  </div>
                  <div class="flex items-center">
                    <span class="abnormal-proportion">日同比11%</span>
                    <span class="delta" />
                  </div>
                </div>
              </div>
              <div class="w-full h-10 flex items-center">
                <h1 class="text-3xl">78</h1>
              </div>
              <el-progress
                style="height: 6vh"
                :stroke-width="20"
                :percentage="78"
                :text-inside="true"
                color="#13C2C2"
              />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="17"
        :lg="17"
        :xl="17"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <template #header>
            <TypeIt
              class="font-semibold"
              :className="'type-it1'"
              :values="['违规总量']"
              :cursor="false"
              :speed="120"
            />
          </template>
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <Bar />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="7"
        :lg="7"
        :xl="7"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <template #header>
            <TypeIt
              class="font-semibold"
              :className="'type-it2'"
              :values="['异常表现']"
              :cursor="false"
              :speed="120"
            />
          </template>
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <Radar />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="12"
        :xl="12"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <template #header>
            <TypeIt
              class="font-semibold"
              :className="'type-it3'"
              :values="['视频分析']"
              :cursor="false"
              :speed="120"
            />
          </template>
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <Pie />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="12"
        :xl="12"
        class="mb-[18px]"
        v-motion
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card shadow="never">
          <template #header>
            <TypeIt
              class="font-semibold"
              :className="'type-it4'"
              :values="['视频分析结束时间(每日)']"
              :cursor="false"
              :speed="120"
            />
          </template>
          <el-skeleton animated :rows="7" :loading="loading">
            <template #default>
              <Line />
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
    </el-row>
  </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;
}

.abnormal-title {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 14px;
  font-weight: 600;
}

.abnormal-proportion {
  margin-right: 8px;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 12px;
  font-weight: 400;
  color: #4079ed;
}

.delta {
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-top-width: 0;
  border-bottom-color: #52c41a;
}

.delta-down {
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-top-color: #ff4d4f;
  border-bottom-width: 0;
}

/* .type-it1 {
  font-family: PingFang SC;
  font-size: 14px;
  font-weight: 400;
  color: #333;
} */
</style>
