<template>
  <div class="app-container">
    <div ref="topContainerRef">
        <TableSearch
            :queryParams="queryParams"
            :showSearch="showSearch"
            label-width="90px"
            queryRef="queryRef"
            @refresh="resetQuery"
            @search="handleQuery"
        >
            <template #one>
                <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
                    <el-form-item label="车辆名称" prop="vehicleName">
                        <el-input
                        v-model="queryParams.vehicleName"
                        placeholder="请输入车辆名称"
                        clearable
                        style="width: 240px"
                        @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
                    <el-form-item label="车型" prop="vehicleModel">
                        <el-input
                        v-model="queryParams.vehicleModel"
                        placeholder="请输入车型"
                        clearable
                        style="width: 240px"
                        @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
            </template>
        </TableSearch>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                >删除</el-button>
            </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div :style="containerHeight">
      <!-- 表格数据 -->
      <el-table height="100%" v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="车辆名称" prop="vehicleName" />
         <el-table-column label="车型" prop="vehicleModel" />
         <el-table-column label="车架号" prop="vin" />
         <el-table-column label="颜色" prop="color"/>
         <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
               <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
               ></el-switch>
            </template>
         </el-table-column>
         <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="操作" align="center" 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)">修改</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</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"
      />

    </div>

      <!-- 添加或修改配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="carRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="车辆名称" prop="vehicleName">
               <el-input v-model="form.vehicleName" placeholder="请输入车辆名称" />
            </el-form-item>
            <el-form-item label="车型" prop="vehicleModel">
               <el-input v-model="form.vehicleModel" placeholder="请输入车型" />
            </el-form-item>
            <el-form-item label="车架号" prop="vin">
                <el-input v-model="form.vin" placeholder="请输入车架号" />
            </el-form-item>
            <el-form-item label="颜色" prop="vin">
                <el-input v-model="form.color" placeholder="请输入颜色" />
            </el-form-item>
            <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                    v-model="form.productionDate"
                    type="date"
                    style="width: 100%;"
                    placeholder="Pick a day"
                />
            </el-form-item>
            <el-form-item label="备注">
               <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>

   </div>
</template>

<script setup name="Role">
import TableSearch from "@/components/TableSearch/index.vue";
import { useContainerHeight } from "@/hooks/tableHeight";
import { addVehicle, getVehicleList, updateVehicle, deleteVehicle } from "@/api/intelligenceTest/car.js"
import { ElMessage, ElMessageBox } from 'element-plus'

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const tableDataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleName: undefined,
    vehicleModel: undefined
  },
  rules: {
    vehicleName: [{ required: true, message: "车辆名称不能为空", trigger: "blur" }],
    vehicleModel: [{ required: true, message: "车型不能为空", trigger: "blur" }],
    vin: [{ required: true, message: "车架号不能为空", trigger: "blur" }],
    color: [{ required: true, message: "颜色不能为空", trigger: "blur" }],
    productionDate: [{ required: true, message: "生产日期不能为空", trigger: "blur" }]
  },
});

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

/** 查询列表 */
const getList = async () =>  {
  loading.value = true;
  const res = await getVehicleList(queryParams.value)
  if (res.code === 200) {
    tableDataList.value = res.rows;
    total.value = res.total;
  }
  loading.value = false;
}

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

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
    const deleteIds = row.id || ids.value;
    ElMessageBox.confirm(`确定要删除编号为${deleteIds}的车辆吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteVehicle(deleteIds).then(() => {
            ElMessage.success("删除成功");
            getList();
        });
     });
}


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

/** 状态修改 */
function handleStatusChange(row) {
    let text = row.status === "0" ? "启用" : "停用";
    ElMessageBox.confirm('确认要"' + text + '""' + row.vehicleName + '"车辆吗?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        updateVehicle({
            ...row,
        }).then(() => {
            ElMessage.success(text + "成功");
            getList();
        });
    }).catch(() => {
        row.status = row.status === "0" ? "1" : "0";
    })
}

const reset = () => {
    carRef.value.resetFields()
};

const carRef = ref()
const isNew = ref(true)

/** 添加 */
function handleAdd() {
  open.value = true;
  isNew.value = true
  title.value = "添加";
}

/** 修改 */
function handleUpdate(row) {
  form.value = { ...row };
  open.value = true;
  isNew.value = false
  title.value = "修改";
}

/** 提交按钮 */
function submitForm() {
  carRef.value.validate((valid) => {
    if (valid) {
      if (isNew.value) {
        addVehicle(form.value).then(() => {
          ElMessage.success("添加成功");
          getList();
          open.value = false;
          reset();
        });
      } else {
        updateVehicle(form.value).then(() => {
          ElMessage.success("修改成功");
          getList();
          open.value = false;
          reset();
        });
      }
    }
  }); 
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>
