<template>
  <div class="p-2">
    <Pageheader title="车辆管理"></Pageheader>
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="车牌号" prop="carNum">
              <el-input v-model.trim="queryParams.carNum" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model.trim="queryParams.carBrand" placeholder="请输入车辆品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="车身颜色" prop="carColor">
              <el-input v-model.trim="queryParams.carColor" placeholder="请输入车身颜色" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['car:car:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['car:car:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['car:car:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="carList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="车牌号" align="center" prop="carNum" />
        <el-table-column label="车辆品牌" align="center" prop="carBrand" />
        <el-table-column label="车辆型号" align="center" prop="carModel" />
        <el-table-column label="车身颜色" align="center" prop="carColor" />
        <el-table-column label="持有人" align="center" prop="residentId">
          <template #default="scope"> {{ getResidentName(scope.row.residentId) }} </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['car:car:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['car:car:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Car" lang="ts">
import Pageheader from '@/components/Pageheader/index.vue';
import { listCar, getCar, delCar, addCar, updateCar } from '@/api/system/cars/index';
import { CarVO, CarQuery, CarForm } from '@/api/system/cars/type';
import { listResident } from '@/api/system/resident';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const router = useRouter();

const carList = ref<CarVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const carFormRef = ref<ElFormInstance>();

const initFormData: CarForm = {
  id: undefined,
  areaId: undefined,
  parkingId: undefined,
  residentId: undefined,
  carNum: undefined,
  carBrand: undefined,
  carModel: undefined,
  carColor: undefined,
  remark: undefined,
  carImageUrl: undefined,
  createBy: undefined,
  createTime: undefined,
  updateBy: undefined,
  updateTime: undefined
};
const data = reactive<PageData<CarForm, CarQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    villageId: Number(localStorage.getItem('villageid')),
    areaId: undefined,
    parkingId: undefined,
    residentId: undefined,
    carNum: undefined,
    carBrand: undefined,
    carModel: undefined,
    carColor: undefined,
    carImageUrl: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '车辆管理表id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 持有人 */
const ResidentList = ref([]);
const getResidentName = (id: string | number) => {
  console.log(ResidentList.value, id);
  const find = ResidentList.value.find((item) => item.id == id);
  console.log(find);
  return find.name;
};

/** 查询车辆管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCar(queryParams.value);
  const res1 = await listResident();
  ResidentList.value = res1.rows;
  carList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CarVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/carArea/addCars'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CarVO) => {
  router.push({
    path: '/carArea/addCars',
    query: {
      id: row.id
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CarVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('该信息删除后无法恢复，确定要删除吗？').finally(() => (loading.value = false));
  await delCar(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  getList();
});
</script>
