<template>
  <div>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item :label="$t.value.LicensePlateNo">
        <el-input
          v-model="queryForm.plate_number"
          :placeholder="$t.value.carPlateInput"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t.value.VehicleType">
        <el-select
          v-model="queryForm.vehicle_type_id"
          :placeholder="$t.value.carTypeSelect"
          clearable
          style="width:160px"
        >
          <el-option
            v-for="item in typeList"
            :key="item.ID"
            :label="item.name"
            :value="item.ID"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t.value.CarOwner">
        <el-select
          v-model="queryForm.owner_id"
          clearable
          :placeholder="$t.value.ownerSelect"
          style="width: 180px"
        >
          <el-option
            v-for="item in ownerList"
            :key="item.ID"
            :label="item.owner_name"
            :value="item.ID"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          icon="Search"
          type="primary"
          @click="getVehicleList"
        >{{ $t.value.Search }}</el-button>
        <el-button
          icon="Refresh"
          @click="resetQuery"
        >{{ $t.value.Reset }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="Plus"
          type="primary"
          @click="openDialog($t.value.addCar, null)"
        >{{ $t.value.new }}</el-button>
        <el-button
          type="warning"
          @click="openTypeDrawer"
        >{{ $t.value.manageCarType }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 车辆列表 -->
    <el-table
      :data="vehicleList"
      height="605"
      border
    >
      <el-table-column
        label="ID"
        align="center"
        prop="ID"
        width="80"
      />
      <el-table-column
        :label="$t.value.LicensePlateNo"
        align="center"
        prop="plate_number"
      />
      <el-table-column
        :label="$t.value.ElectronicTag"
        align="center"
        prop="rfid_tag"
      />
      <el-table-column
        :label="$t.value.VehicleType"
        align="center"
      >
        <template #default="scope">
          <el-tag type="primary">
            {{ scope.row.vehicle_type?.name || $t.value.unknown }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t.value.VehicleBrand"
        align="center"
        prop="vehicle_brand"
      />
      <el-table-column
        :label="$t.value.VehicleColor"
        align="center"
        prop="vehicle_color"
      />
      <el-table-column
        :label="$t.value.CarOwner"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.owner?.owner_name || $t.value.tempCar }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t.value.Action"
        align="center"
        width="180"
      >
        <template #default="scope">
          <el-button
            icon="Edit"
            type="primary"
            text
            @click="openDialog($t.value.editCar, scope.row)"
          >{{ $t.value.modify }}</el-button>
          <el-button
            icon="Delete"
            type="danger"
            text
            @click="deleteVehicle(scope.row.ID)"
          >{{ $t.value.remove }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-box">
      <el-pagination
        :current-page="queryForm.page"
        :page-size="queryForm.pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
    >
      <el-form
        label-width="120px"
        :model="formData"
      >
        <el-form-item :label="$t.value.LicensePlateNo">
          <el-input
            v-model="formData.plate_number"
            :placeholder="$t.value.carPlateInput"
          />
        </el-form-item>
        <el-form-item :label="$t.value.ElectronicTag">
          <el-input
            v-model="formData.rfid_tag"
            :placeholder="$t.value.rfidLabel"
          />
        </el-form-item>
        <el-form-item :label="$t.value.VehicleType">
          <el-select
            v-model="formData.vehicle_type_id"
            placeholder=""
            style="width:100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t.value.VehicleBrand">
          <el-input
            v-model="formData.vehicle_brand"
            :placeholder="$t.value.placeholderPorsche"
          />
        </el-form-item>
        <el-form-item :label="$t.value.VehicleColor">
          <el-input
            v-model="formData.vehicle_color"
            :placeholder="$t.value.placeholderBlack"
          />
        </el-form-item>
        <el-form-item :label="$t.value.BindOwner">
          <el-select
            v-model="formData.owner_id"
            :placeholder="$t.value.tempCarOptional"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in ownerList"
              :key="item.ID"
              :label="item.owner_name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ $t.value.Cancel }}</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >{{ $t.value.Confirm }}</el-button>
      </template>
    </el-dialog>

    <!-- ===================== 车辆类型抽屉（Drawer）===================== -->
    <el-drawer
      v-model="typeDrawerVisible"
      :title="$t.value.manageCarType"
      size="700px"
    >
      <div style="display:flex; justify-content:space-between; margin-bottom:10px">
        <el-form-item :label="$t.value.typeName">
          <el-input
            v-model="typeQuery.name"
            placeholder=""
            clearable
            style="width:200px"
            @input="getTypeList"
          />
        </el-form-item>
        <el-button
          type="primary"
          icon="Plus"
          @click="openTypeForm($t.value.new)"
        >{{ $t.value.AddNewType }}</el-button>
      </div>

      <el-table
        :data="typeList"
        border
      >
        <el-table-column
          label="ID"
          prop="ID"
        />
        <el-table-column
          :label="$t.value.typeName"
          prop="name"
        />
        <el-table-column
          :label="$t.value.Remarks"
          prop="remarks"
        />
        <el-table-column :label="$t.value.Action">
          <template #default="scope">
            <el-button
              text
              type="primary"
              @click="openTypeForm($t.value.modify, scope.row)"
            >{{ $t.value.modify }}</el-button>
            <el-button
              text
              type="danger"
              @click="deleteType(scope.row.ID)"
            >{{ $t.value.remove }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="typeQuery.page"
        v-model:page-size="typeQuery.pageSize"
        :total="typeTotal"
        layout="total, prev, pager, next"
        style="margin-top:10px; text-align:right"
        @current-change="getTypeList"
      />
    </el-drawer>

    <!-- 车辆类型 新增/编辑 弹窗 -->
    <el-dialog
      v-model="typeDialogVisible"
      :title="typeTitle"
      width="450px"
    >
      <el-form
        label-width="100px"
        :model="typeForm"
      >
        <el-form-item :label="$t.value.typeName">
          <el-input
            v-model="typeForm.name"
            :placeholder="$t.value.parkTip"
          />
        </el-form-item>
        <el-form-item :label="$t.value.Remarks">
          <el-input
            v-model="typeForm.remarks"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialogVisible = false">{{ $t.value.Cancel }}</el-button>
        <el-button
          type="primary"
          @click="saveType"
        >{{ $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 { t } from '@/lang/index.js'

import {
  obtainVehicleList,
  addVehicle,
  editVehicle,
  removeVehicleList
} from '@/api/vehicle'
import { obtainCarOwnerList } from '@/api/carOwner'
// 车辆类型接口
import {
  obtainVehicleTypeList,
  createVehicleType,
  editVehicleType,
  removeVehicleType,
  getAllVehicleTypes
} from '@/api/vehicle'

// ==================== 车辆管理原有逻辑 ====================
const queryForm = reactive({
  plate_number: '',
  vehicle_type_id: null,
  owner_id: null,
  page: 1,
  pageSize: 10
})

const vehicleList = ref([])
const total = ref(0)
const ownerList = ref([])
const typeList = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  ID: 0,
  plate_number: '',
  rfid_tag: '',
  vehicle_type_id: null,
  vehicle_brand: '',
  vehicle_color: '',
  owner_id: null
})

const getVehicleList = async() => {
  try {
    const res = await obtainVehicleList(queryForm)
    if (res.code === 0) {
      vehicleList.value = res.data.list
      total.value = res.data.total
    }
  } catch (err) {
    ElMessage.error(t.value.getListFail)
  }
}

const resetQuery = () => {
  queryForm.plate_number = ''
  queryForm.vehicle_type_id = null
  queryForm.owner_id = null
  queryForm.page = 1
  getVehicleList()
}

const openDialog = (title, row) => {
  dialogTitle.value = title
  dialogVisible.value = true
  if (!row) {
    Object.assign(formData, {
      ID: 0, plate_number: '', rfid_tag: '',
      vehicle_type_id: null, vehicle_brand: '',
      vehicle_color: '', owner_id: null
    })
    return
  }
  Object.assign(formData, row)
}

const submitForm = async() => {
  if (!formData.plate_number) {
    ElMessage.warning(t.value.carPlateInput)
    return
  }
  try {
    if (formData.ID > 0) {
      await editVehicle(formData).then(res => {
        if (res.code === 0) {
          ElMessage.success(t.value.editSuccess)
        } else {
          console.log(res.data)
        }
      })
    } else {
      await addVehicle(formData).then(res => {
        if (res.code === 0) {
          ElMessage.success(t.value.addSuccess)
        } else {
          console.log(res.data)
        }
      })
    }
    dialogVisible.value = false
    await getVehicleList()
  } catch (err) {
    ElMessage.error(t.value.saveFail)
  }
}

const deleteVehicle = async(id) => {
  await ElMessageBox.confirm(t.value.confirmDeleteCar, t.value.tip,
    { type: 'warning', confirmButtonText: t.value.Confirm,
      cancelButtonText: t.value.Cancel })
  try {
    await removeVehicleList({ id })
    ElMessage.success(t.value.deleteSuccess)
    getVehicleList()
  } catch (err) {
    ElMessage.error(t.value.deleteFailed)
  }
}

const handlePageChange = (page) => {
  queryForm.page = page
  getVehicleList()
}
const handleSizeChange = (size) => {
  queryForm.pageSize = size
  queryForm.page = 1
  getVehicleList()
}

// ==================== 车辆类型 抽屉逻辑 ====================
const typeDrawerVisible = ref(false)
const typeDialogVisible = ref(false)
const typeTitle = ref('')

const typeQuery = reactive({
  name: '',
  page: 1,
  pageSize: 10
})
const typeTotal = ref(0)

const typeForm = reactive({
  ID: 0,
  name: '',
  remarks: ''
})

// 打开类型抽屉
const openTypeDrawer = () => {
  typeDrawerVisible.value = true
  getTypeList()
}

// 获取类型列表
const getTypeList = async() => {
  const res = await obtainVehicleTypeList(typeQuery)
  if (res.code === 0) {
    typeList.value = res.data.list
    typeTotal.value = res.data.total
  }
}

// 打开新增/编辑
const openTypeForm = (title, row = null) => {
  typeTitle.value = title
  typeDialogVisible.value = true
  if (!row) {
    Object.assign(typeForm, { ID: 0, name: '', remarks: '' })
    return
  }
  Object.assign(typeForm, row)
}

// 保存
const saveType = async() => {
  if (!typeForm.name) {
    ElMessage.warning(t.value.inputTypeName)
    return
  }
  try {
    if (typeForm.ID > 0) {
      await editVehicleType(typeForm)
      ElMessage.success(t.value.editSuccess)
    } else {
      await createVehicleType(typeForm)
      ElMessage.success(t.value.addSuccess)
    }
    typeDialogVisible.value = false
    await getTypeList()
    await loadAllTypes()
  } catch (e) {
    ElMessage.error(t.value.saveFail)
  }
}

// 删除
const deleteType = async(id) => {
  await ElMessageBox.confirm(t.value.confirmDelete)
  await removeVehicleType(id)
  ElMessage.success(t.value.deleteSuccess)
  await getTypeList()
  await loadAllTypes()
}

// 加载所有类型（下拉框）
const loadAllTypes = async() => {
  const res = await getAllVehicleTypes()
  if (res.code === 0) typeList.value = res.data
}

// ==================== 初始化 ====================
const getOwnerList = async() => {
  const res = await obtainCarOwnerList()
  if (res.code === 0) ownerList.value = res.data.list
}

onMounted(async() => {
  await loadAllTypes()
  await getVehicleList()
  await getOwnerList()
})
</script>

<style scoped lang="scss">
.pagination-box {
  width: 100%;
  display: flex;
  justify-content: end;
  padding: 10px;
}
</style>
