<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆ID" prop="vehicleId">
        <el-input
          v-model="queryParams.vehicleId"
          placeholder="请输入车辆ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlateNumber">
        <el-input
          v-model="queryParams.licensePlateNumber"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型ID" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入类型ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="owningUnit">
        <el-input
          v-model="queryParams.owningUnit"
          placeholder="请输入所属单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input
          v-model="queryParams.contactPerson"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片URL" prop="imageUrl">
        <el-input
          v-model="queryParams.imageUrl"
          placeholder="请输入图片URL"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:vehicle_info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:vehicle_info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:vehicle_info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:vehicle_info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehicle_infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆ID" align="center" prop="vehicleId" />
      <el-table-column label="车牌号" align="center" prop="licensePlateNumber" />
      <el-table-column label="VIN码" align="center" prop="vinNumber" />
      <el-table-column label="车辆类型" align="center" prop="typeId">
        <template slot-scope="scope">
          {{ getVehicleTypeName(scope.row.typeId) }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="所属单位" align="center" prop="owningUnit" />
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="图片URL" align="center" prop="imageUrl" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:vehicle_info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:vehicle_info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车牌号" prop="licensePlateNumber">
          <el-input v-model="form.licensePlateNumber" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="VIN码" prop="vinNumber">
          <el-input v-model="form.vinNumber" placeholder="请输入VIN码" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="typeId">
          <treeselect v-model="form.typeId" :options="vehicleTypeOptions" :normalizer="normalizer" placeholder="请选择车辆类型" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="所属单位" prop="owningUnit">
          <el-input v-model="form.owningUnit" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="form.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVehicle_info, getVehicle_info, delVehicle_info, addVehicle_info, updateVehicle_info } from "@/api/system/vehicle_info"
import { listVehicle_type } from "@/api/system/vehicle_type"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Vehicle_info",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆信息表格数据
      vehicle_infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleId: null,
        licensePlateNumber: null,
        typeId: null,
        brand: null,
        owningUnit: null,
        contactPerson: null,
        phoneNumber: null,
        imageUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vehicleId: [
          { required: true, message: "车辆ID不能为空", trigger: "blur" }
        ],
        licensePlateNumber: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "类型ID不能为空", trigger: "blur" }
        ],
      },
      // 车辆类型选项
      vehicleTypeOptions: []
    }
  },
  created() {
    this.getList()
    this.getVehicleTypeList()
  },
  methods: {
    /** 查询车辆信息列表 */
    getList() {
      this.loading = true
      listVehicle_info(this.queryParams).then(response => {
        this.vehicle_infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取车辆类型列表 */
    getVehicleTypeList() {
      listVehicle_type().then(response => {
        // 直接使用树形数据，不包含"顶级节点"
        this.vehicleTypeOptions = this.handleTree(response.data, "typeId", "parentId");
      });
    },
    /** 转换车辆类型数据结构 (供 Treeselect 使用) */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        vehicleId: null,
        licensePlateNumber: null,
        vinNumber: null,
        typeId: null,
        brand: null,
        owningUnit: null,
        contactPerson: null,
        phoneNumber: null,
        imageUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.vehicleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getVehicleTypeList()
      this.open = true
      this.title = "添加车辆信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getVehicleTypeList()
      const vehicleId = row.vehicleId || this.ids
      getVehicle_info(vehicleId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改车辆信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.vehicleId != null) {
            updateVehicle_info(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addVehicle_info(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const vehicleIds = row.vehicleId || this.ids
      this.$modal.confirm('是否确认删除车辆信息编号为"' + vehicleIds + '"的数据项？').then(function() {
        return delVehicle_info(vehicleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/vehicle_info/export', {
        ...this.queryParams
      }, `vehicle_info_${new Date().getTime()}.xlsx`)
    },
    /** 根据typeId获取车辆类型名称，格式为"一级类型/二级类型" */
    getVehicleTypeName(typeId) {
      if (!typeId || !this.vehicleTypeOptions.length) {
        return "未知类型";
      }
      
      // 递归查找类型及其路径
      const findTypeWithPath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          const currentPath = [...path, node.typeName];
          
          if (node.typeId === targetId) {
            return currentPath;
          }
          
          if (node.children && node.children.length > 0) {
            const result = findTypeWithPath(node.children, targetId, currentPath);
            if (result) {
              return result;
            }
          }
        }
        return null;
      };
      
      const typePath = findTypeWithPath(this.vehicleTypeOptions, typeId);
      if (typePath) {
        return typePath.join('/');
      }
      
      return "未知类型";
    }
  }
}
</script>
