<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="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入车辆类型ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型级别 (1:一级, 2:二级)" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入类型级别 (1:一级, 2:二级)"
          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_type: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_type: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_type:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</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_type:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="vehicle_typeList"
      row-key="typeId"
      :default-expand-all="isExpandAll"
      @selection-change="handleSelectionChange"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类型ID" align="center" prop="typeId" />
      <el-table-column label="类型名称" align="center" prop="typeName" />
      <el-table-column label="类型级别 (1:一级, 2:二级)" align="center" prop="level" />
      <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_type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:vehicle_type:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:vehicle_type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改车辆类型对话框 -->
    <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="parentId">
          <treeselect v-model="form.parentId" :options="vehicle_typeOptions" :normalizer="normalizer" placeholder="选择上级类型" />
        </el-form-item>
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型级别" prop="level">
          <el-input v-model="form.level" placeholder="请输入类型级别 (1:一级, 2:二级)" />
        </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_type, getVehicle_type, delVehicle_type, addVehicle_type, updateVehicle_type } from "@/api/system/vehicle_type"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Vehicle_type",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数 (车辆类型是树形结构，此项可能不直接使用，但为保持一致性添加)
      total: 0,
      // 车辆类型表格数据
      vehicle_typeList: [],
      // 车辆类型树选项
      vehicle_typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        typeId: null,
        typeName: null,
        level: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: "车辆类型ID不能为空", trigger: "blur" }
        ],
        typeName: [
          { required: true, message: "类型名称不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "类型级别 (1:一级, 2:二级)不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询车辆类型列表 */
    getList() {
      this.loading = true
      listVehicle_type(this.queryParams).then(response => {
        this.vehicle_typeList = this.handleTree(response.data, "typeId", "parentId")
        this.loading = false
      })
    },
    /** 转换车辆类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      // 如果是顶级节点，则用方括号包裹
      const label = node.typeId === 0 ? `[${node.typeName}]` : node.typeName;

      return {
        id: node.typeId,
        label: label,
        children: node.children
      }
    },
	/** 查询车辆类型下拉树结构 */
    getTreeselect() {
      listVehicle_type().then(response => {
        // 获取实际的树形数据
        const actualTreeData = this.handleTree(response.data, "typeId", "parentId");

        // 准备"顶级节点"作为一个独立的选项
        // 设置 children 为 null，使其本身可被选中作为叶子节点
        const topNodeOption = { typeId: 0, typeName: '顶级节点', children: [] };

        // 将"顶级节点"选项与实际的树形数据合并
        // 这使得"顶级节点"和所有实际的车辆类型根节点都可以在下拉框中直接选择。
        this.vehicle_typeOptions = [topNodeOption].concat(actualTreeData);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: null,
        parentId: null,
        typeName: null,
        level: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.typeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.typeId) {
        this.form.parentId = row.typeId
      } else {
        this.form.parentId = 0
      }
      this.open = true
      this.title = "添加车辆类型"
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const typeId = row.typeId || this.ids
      getVehicle_type(typeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改车辆类型"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果parentId为0，则设置为null，因为顶级节点没有父ID
          if (this.form.parentId === 0) {
            this.form.parentId = null;
          }
          if (this.form.typeId != null) {
            updateVehicle_type(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addVehicle_type(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const typeIds = row.typeId || this.ids
      this.$modal.confirm('是否确认删除车辆类型编号为"' + typeIds + '"的数据项？').then(function() {
        return delVehicle_type(typeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/vehicle_type/export', {
        ...this.queryParams
      }, `vehicle_type_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
