<script lang="ts" setup>
import { getCurrentInstance } from 'vue'
import ItemSelect from './ItemSelect.vue'

import { getHisFlows, getCarImagesList } from '@/api/history'
import { useRouter } from 'vue-router'

import { ASYNC_DIRECTIONS, CAR_TYPES } from '@/config/dict'
import DEFAULT_ICON from '@/assets/images/common/list-default.png'

const USE_CAR_TYPES = CAR_TYPES.map(({ name, type }) => {
  return { name, key: type }
})

const app = getCurrentInstance()

const loading = ref(false) // 加载状态
const listData = ref([]) // 车辆列表
const jumperNum = ref(null) // 跳转页码

const router = useRouter()

const params = reactive({
  // carType: ['0', '1', '2', '3', '4'], // 车辆类型
  carPlate: '', // 车牌
  direction: ['上行', '下行'],
  edDurationSecond: null, // 通行时间
  firstStartTime: null,
  firstEndTime: null,
  pageNo: 1,
  pageSize: 10,
  total: 0
})

const areaTime = computed({
  set(e) {
    if (e) {
      params.firstStartTime = e[0]
      params.firstEndTime = e[1]
    } else {
      params.firstStartTime = null
      params.firstEndTime = null
    }
  },
  get() {
    return [params.firstStartTime, params.firstEndTime]
  }
})

const allPages = computed(() => {
  const left = params.total % params.pageSize
  const num = (params.total - left) / params.pageSize
  return num + (left ? 1 : 0) || 1
})

const directMap = computed(() => {
  return Object.fromEntries(
    ASYNC_DIRECTIONS().map((item) => {
      return [item.seKey, item]
    })
  )
})

// 获取列表
const getCars = async (x?: number) => {
  params.pageNo = x || 1
  loading.value = true

  const newPms = {}
  for (let key in params) {
    if (params[key]) {
      newPms[key] = params[key]
    }
  }

  const res1 = await getHisFlows(newPms)

  if (res1.list.length) {
    const res2 = await getCarImagesList(res1.list.map((item) => item.guid))
    listData.value = res1.list.map((item) => {
      return {
        ...item,
        ...res2[item.guid]
      }
    })
  } else {
    listData.value = res1.list
  }

  params.total = res1.total
  loading.value = false
}
const BASE_PATH = import.meta.env.VITE_PORT_IMAGE_BASE

// 图片预览
const imageView = (urls, str,cp) => {
  app?.proxy?.$openImage([BASE_PATH+urls], str,cp)
}

// 分页跳转
const goJumper = () => {
  getCars(jumperNum.value || 1)
}

// 重置
const reset = () => {
  params.carPlate = ''
  params.firstStartTime = null
  params.firstEndTime = null
  params.direction = ['上行', '下行']
  params.edDurationSecond = null
  params.pageNo = 1
  getCars()
}

// 回溯
const goTrack = (row) => {
  router.push({
    path: 'history-track',
    query: {
      id: row.guid,
      plate: row.carPlate,
      from: 'history'
    }
  })
}

onBeforeMount(() => {
  getCars()
})
</script>

<template>
  <div class="car-track">
    <!-- 查询 -->
    <div class="search">
      <div class="inp-item">
        <div class="i-name">车牌号：</div>
        <div class="i-content">
          <el-input v-model="params.carPlate" class="x-inp" placeholder="请输入..." />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">隧道方向：</div>
        <div class="i-content">
          <ItemSelect v-model="params.direction" :selects="ASYNC_DIRECTIONS()" />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">车辆类型：</div>
        <div class="i-content">
         <ItemSelect v-model="params.carType" :selects="USE_CAR_TYPES" />
               <!--<Filter v-bind="{ options: CAR_TYPES, defaultText: '车辆类型' }" v-model="params.vehicleType" />-->

        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">进入时间：</div>
        <div class="i-content">
          <el-date-picker
            class="def"
            v-model="areaTime"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :teleported="false"
          />
        </div>
      </div>

      <div class="inp-item">
        <div class="i-name">留存时间：</div>
        <div class="i-content i-more">
          <span>≤</span>
          <el-input-number
            :controls="false"
            :min="0"
            v-model="params.edDurationSecond"
            class="num-inp def"
            placeholder="请输入..."
          />
          <span>分钟</span>
        </div>
      </div>

      <div class="btns">
        <el-button @click="getCars()" type="primary">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>

    <!-- 列表 -->
    <div class="list-content">
      <el-table
        v-loading="loading"
        :data="listData"
        :row-class-name="
          ({ rowIndex }) => {
            return rowIndex % 2 === 0 ? 'stripe-row' : ''
          }
        "
        class="car-table"
      >
        <el-table-column align="center" label="序号" width="80">
          <template #default="{ $index }">
            {{ $index + (params.pageNo - 1) * params.pageSize + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="carPlate" label="车牌" />
        <el-table-column prop="carType" label="车辆类型" width="180" />
        <el-table-column label="车头照片" width="200">
          <template #default="{ row }">
            <el-image
              @click="() => imageView([row.headImage], '车头照片')"
              class="car-image"
              :src="row.headImage"
              fit="contain"
            >
              <template #error>
                <el-image class="image-error" :src="DEFAULT_ICON" fit="cover" />
              </template>
              <template #placeholder>
                <el-image class="image-error" :src="DEFAULT_ICON" fit="cover" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="车牌照片" width="200">
          <template #default="{ row }">
            <el-image
              @click="() => imageView([row.plateImage], '车牌照片',true)"
              class="car-image"
              :src="row.plateImage"
              fit="contain"
            >
              <template #error>
                <el-image class="image-error" :src="DEFAULT_ICON" fit="cover" />
              </template>
              <template #placeholder>
                <el-image class="image-error" :src="DEFAULT_ICON" fit="cover" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="averageSpeed" label="平均车速" width="190" />
        <el-table-column prop="directionName" label="方向" width="190">
          <template #default="{ row }">
            {{ directMap[row.tunnelId].name }}
          </template>
        </el-table-column>
        <el-table-column prop="inTunnelTime" label="进入时间" width="240" />
        <el-table-column prop="duration" label="留存时间" width="230" />
        <el-table-column label="操作" width="110">
          <template #default="{ row }">
            <div @click="goTrack(row)" class="def-btn">轨迹回溯</div>
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty">
            <span v-if="!loading">没有数据</span>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->

      <div class="pages">
        <div class="sum">共 {{ params.total }} 条</div>

        <el-select v-model="params.pageSize" class="page-select" :teleported="false">
          <el-option
            v-for="item in [10, 20, 30, 50]"
            :key="item"
            :label="item + '条/页'"
            :value="item"
          />
        </el-select>

        <el-pagination
          v-model:currentPage="params.pageNo"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          :total="params.total"
          class="def"
          @change="getCars"
        />

        <div class="jumper">
          前往
          <el-input-number
            class="def"
            v-model="jumperNum"
            @blur="goJumper"
            @keyup.enter="goJumper"
            :min="1"
            :max="allPages"
            :controls="false"
          />
          页
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.car-track {
  .search {
    margin: 20px 40px 16px;
    padding: 16px 34px;
    color: white;
    background: rgba(69, 116, 182, 0.2);
    box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
    border-radius: 8px;

    display: grid;
    grid-template-columns: 504px 470px auto;
    row-gap: 14px;

    .inp-item {
      display: flex;
      align-items: center;
      margin-right: 60px;
      .i-name {
        font-size: 14px;
        white-space: nowrap;
        width: 82px;
      }

      .i-more {
        display: flex;
        align-items: center;
        & > span {
          white-space: nowrap;
        }
      }
      .i-content {
        flex-grow: 1;
        position: relative;
      }
    }
    .x-inp {
      width: 320px;
    }
    .num-inp {
      margin: 0 5px;
    }
  }

  .list-content {
    margin: 0 40px;
    overflow: hidden;
    .car-image {
      width: 40px;
      height: 40px;
      cursor: pointer;
      :deep(.image-error) {
        height: 100%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666666;
      }
    }
    .empty {
      color: rgba(240, 245, 255, 0.45);
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .def-btn {
      color: #00aeff;
      cursor: pointer;
    }
    .pages {
      margin: 20px 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      color: white;
      .sum {
        margin-right: 20px;
      }
      .page-select {
        width: 128px;
        margin-right: 20px;
      }
      .jumper {
        margin-left: 24px;
        font-size: 16px;
      }
    }
  }
}
</style>
