<template>
  <div class="shortlist-page">
    <!-- 查询条件 -->
    <el-form
      inline
      :model="queryForm"
    >
      <el-form-item :label="$t.value.LicensePlateNo">
        <el-input
          v-model="queryForm.plate_number"
          :placeholder="$t.value.licensePlate"
          clearable
        />
      </el-form-item>

      <el-form-item :label="$t.value.RFID_Tag">
        <el-input
          v-model="queryForm.rfid_tag"
          placeholder="RFID"
          clearable
        />
      </el-form-item>

      <el-form-item :label="$t.value.List_Type">
        <el-select
          v-model="queryForm.list_type"
          placeholder=""
          clearable
        >
          <el-option
            :label="$t.value.WhiteList"
            value="白名单"
          />
          <el-option
            :label="$t.value.BlackList"
            value="黑名单"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="getList"
        >{{ $t.value.Search }}</el-button>
        <el-button @click="resetQuery">{{ $t.value.Reset }}</el-button>
        <el-button
          type="success"
          icon="Plus"
          @click="add"
        >{{ $t.value.new }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="list"
      border
      stripe
    >
      <el-table-column
        prop="ID"
        label="ID"
        align="center"
        width="70"
      />
      <el-table-column
        prop="list_type"
        :label="$t.value.List_Type"
        align="center"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="scope.row.list_type === '白名单' ? 'success' : 'danger'">
            {{ scope.row.list_type === '白名单' ? $t.value.WhiteList : $t.value.BlackList }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t.value.licensePlate"
        align="center"
        prop="vehicle.plate_number"
      />
      <el-table-column
        label="RFID"
        align="center"
        prop="vehicle.rfid_tag"
      />
      <el-table-column
        :label="$t.value.VehicleType"
        align="center"
        prop="vehicle.vehicle_type.name"
      />
      <el-table-column
        :label="$t.value.Action"
        align="center"
        width="200"
      >
        <template #default="scope">
          {{ formatTime(scope.row.expiration_time) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t.value.Action"
        align="center"
        width="180"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="edit(scope.row)"
          >{{ $t.value.modify }}</el-button>
          <el-button
            link
            type="danger"
            @click="del(scope.row.ID)"
          >{{ $t.value.remove }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      style="margin-top:20px; text-align:right"
      @current-change="getList"
    />

    <!-- 新增/编辑弹窗 → 车辆下拉选择 -->
    <el-dialog
      v-model="dialogVisible"
      :title="$t.value.blackWhiteList"
      width="550px"
    >
      <el-form
        :model="form"
        label-width="120px"
      >
        <el-form-item
          :label="$t.value.List_Type"
          required
        >
          <el-radio-group v-model="form.list_type">
            <el-radio value="白名单">{{ $t.value.WhiteList }}</el-radio>
            <el-radio value="黑名单">{{ $t.value.BlackList }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="$t.value.SelectVehicle"
          required
        >
          <el-select
            v-model="form.vehicle_id"
            :placeholder="$t.value.pleaseSelectVehicle"
            style="width:100%"
          >
            <el-option
              v-for="v in vehicleList"
              :key="v.ID"
              :label="`${v.plate_number} | ${v.rfid_tag || $t.value.noLabel}`"
              :value="v.ID"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t.value.expireTime">
          <el-date-picker
            v-model="form.expiration_time"
            type="datetime"
            :placeholder="$t.value.permanentValidity"
            style="width:100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">{{ $t.value.Cancel }}</el-button>
        <el-button
          type="primary"
          @click="submit"
        >{{ $t.value.Confirm }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryShortlistList, addShortlist, updateShortlist, deleteShortlist } from '@/api/shortlist'
import { queryAllVehicles } from '@/api/vehicle' // 你现有的车辆接口
import { t } from '@/lang/index.js'

// 数据列表
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

// 查询表单
const queryForm = reactive({
  plate_number: '',
  rfid_tag: '',
  list_type: ''
})

// 车辆下拉列表
const vehicleList = ref([])

// 弹窗
const dialogVisible = ref(false)
const form = reactive({
  ID: 0,
  list_type: t.value.WhiteList,
  vehicle_id: '',
  expiration_time: null
})

// 时间格式化
const formatTime = (time) => {
  if (!time) return t.value.permanentValid
  return time.replace('T', ' ').split('+')[0]
}

// 获取黑白名单列表
const getList = async() => {
  const res = await queryShortlistList({
    page: page.value,
    pageSize: pageSize.value,
    ...queryForm
  })
  list.value = res.data.list
  total.value = res.data.total
}

// 获取所有车辆（下拉）
const getVehicleAll = async() => {
  const res = await queryAllVehicles()
  vehicleList.value = res.data
}

// 重置
const resetQuery = () => {
  queryForm.plate_number = ''
  queryForm.rfid_tag = ''
  queryForm.list_type = ''
  page.value = 1
  getList()
}

// 新增
const add = () => {
  form.ID = 0
  form.list_type = '白名单'
  form.vehicle_id = ''
  form.expiration_time = null
  dialogVisible.value = true
}

// 编辑
const edit = (row) => {
  form.ID = row.ID
  form.list_type = row.list_type
  form.vehicle_id = row.vehicle_id
  form.expiration_time = row.expiration_time ? formatTime(row.expiration_time) : null
  dialogVisible.value = true
}

// 提交
const submit = async() => {
  if (!form.vehicle_id) {
    ElMessage.warning(t.value.pleaseSelectVehicle)
    return
  }
  try {
    if (form.ID > 0) {
      await updateShortlist(form)
      ElMessage.success(t.value.editSuccess)
    } else {
      await addShortlist(form)
      ElMessage.success(t.value.addSuccess)
    }
    dialogVisible.value = false
    getList()
  } catch (e) {
    ElMessage.error(t.value.saveFail)
  }
}

// 删除
const del = async(id) => {
  await ElMessageBox.confirm(
    t.value.confirmDelete,
    t.value.tip,
    {
      confirmButtonText: t.value.confirm,
      cancelButtonText: t.value.Cancel,
      type: 'warning',
    }
  )
    .then(() => {
      deleteShortlist(id).then(res => {
        if (res.code === 0) {
          ElMessage.success(t.value.deleteSuccess)
          getList()
        } else {
          ElMessage({
            type: 'error',
            message: t.value.deleteFailed,
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: t.value.cancelDelete,
      })
    })
}

// 初始化
onMounted(() => {
  getList()
  getVehicleAll()
})
</script>

<style scoped lang="scss">
.shortlist-page {
  padding: 20px;
  background: #fff;
  min-height: 100%;
}
</style>
