<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="车辆vin码" prop="carVin">
        <el-input
          v-model="queryParams.carVin"
          placeholder="请输入车辆vin码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="carType">
        <el-input
          v-model="queryParams.carType"
          placeholder="请输入车辆类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="车辆状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择车辆状态" clearable>
          <el-option
            v-for="dict in dict.type.car_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电机厂商" prop="carElectricalmachiney">
        <el-input
          v-model="queryParams.carElectricalmachiney"
          placeholder="请输入电机厂商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电池厂商" prop="carBattery">
        <el-input
          v-model="queryParams.carBattery"
          placeholder="请输入电池厂商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电机编号" prop="carElectricalmachineyId">
        <el-input
          v-model="queryParams.carElectricalmachineyId"
          placeholder="请输入电机编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电池编号" prop="carBatteryId">
        <el-input
          v-model="queryParams.carBatteryId"
          placeholder="请输入电池编号"
          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:car: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:car: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:car: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:car:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="carId" />
      <el-table-column label="车辆vin" align="center" prop="carVin" />
      <el-table-column label="车辆类型" align="center" prop="carType" />
      <el-table-column label="电子围栏" align="center" prop="carFenceId" />
      <el-table-column label="车辆状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.car_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="电机厂商" align="center" prop="carElectricalmachiney" />
      <el-table-column label="电池厂商" align="center" prop="carBattery" />
      <el-table-column label="电机编号" align="center" prop="carElectricalmachineyId" />
      <el-table-column label="电池编号" align="center" prop="carBatteryId" />
      <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-success"
            v-if="scope.row.state === 1"
            @click="handleUpdateOpen(scope.row.carVin)"
            v-hasPermi="['system:car:edit']"
          >上线</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-error"
            v-if="scope.row.state === 0"
            @click="handleUpdateClose(scope.row.carVin)"
            v-hasPermi="['system:car:edit']"
          >下线</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:car:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:car:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-eleme"
            @click="$router.push({
          path:'track',
          query:{
            carVin:scope.row.carVin}})"
          >实时轨迹查询</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="carType">
          <el-input v-model="form.carType" placeholder="请输入车辆类型" />
        </el-form-item>

        <el-form-item label="电子围栏" prop="carFenceId">
          <el-checkbox-group v-model="selectedFenceIds">
            <el-checkbox
              v-for="fence in selectFence"
              :key="fence.fenceId"
              :label="fence.fenceId"
              :value="fence.fenceId"
            >
              {{ fence.fenceName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="电机厂商" prop="carElectricalmachiney">
          <el-input v-model="form.carElectricalmachiney" placeholder="请输入电机厂商" />
        </el-form-item>
        <el-form-item label="电池厂商" prop="carBattery">
          <el-input v-model="form.carBattery" placeholder="请输入电池厂商" />
        </el-form-item>
        <el-form-item label="电机编号" prop="carElectricalmachineyId">
          <el-input v-model="form.carElectricalmachineyId" placeholder="请输入电机编号" />
        </el-form-item>
        <el-form-item label="电池编号" prop="carBatteryId">
          <el-input v-model="form.carBatteryId" placeholder="请输入电池编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </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 {list, add, update, findById, del, exportA, selectFence,open,close} from "@/api/system/car";
import {getRealTimeDataTwo} from "@/api/system/car";

export default {
  name: "Car",
  dicts: ['car_state'],
  data() {
    return {
      selectFence:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //电子围栏空数组
      // fenceIds:[],
      //电子围栏选中的数组
      selectedFenceIds: [],
      // 车辆管理表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carVin: null,
        carType: null,
        state: null,
        carElectricalmachiney: null,
        carBattery: null,
        carElectricalmachineyId: null,
        carBatteryId: null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.selectFenceList()
  },
  methods: {
    selectFenceList(){
      selectFence().then(res=>{
        this.selectFence=res.data
        console.log(this.selectFence)
      })
    },
    /** 查询车辆管理列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.carList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        carVin: null,
        carType: null,
        carFenceId: null,
        state: null,
        carElectricalmachiney: null,
        carBattery: null,
        carElectricalmachineyId: null,
        carBatteryId: 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.carId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.selectFenceList()
      this.title = "添加车辆管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carId = row.carId || this.ids
      findById(carId).then(response => {
        console.log("Response Data:",response.data);
        this.form = response.data;
        console.log("Car Fence IDs:",this.form.carFenceId)
        this.selectedFenceIds = this.form.carFenceId.split(",");
        console.log("selectedFenceIds:"+this.selectedFenceIds)
        this.open = true;
        this.title = "修改车辆管理";
      });
    },
    /** 启用车辆 **/
    handleUpdateOpen(carVin){
      open(carVin).then(res=>{
        this.$message.success('上线成功')
        this.getList();
      })
    },
    /** 禁用车辆 **/
    handleUpdateClose(carVin){
      close(carVin).then(res=>{
        this.$message.success('下线成功')
        this.getList();
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //判断是否为数组，如果不正确转为数组
          if (!Array.isArray(this.form.carFenceId)){
            this.form.carFenceId=[this.form.carFenceId]
          }
          //将每个元素转换为字符串
          this.form.carFenceId = this.form.carFenceId.map(item => String(item)); //
          //拼接获取到数据的数组，切割
          this.form.carFenceId = this.selectedFenceIds.join(",");
          if (this.form.carId != null) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids;
      this.$modal.confirm('是否确认删除车辆管理编号为"' + carIds + '"的数据项？').then(function() {
        return del(carIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      exportA(this.queryParams).then(response => {
        // 创建一个 Blob 对象，指定 MIME 类型为 Excel 文件类型
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        // 创建一个 <a> 标签
        const link = document.createElement('a');
        // 将 Blob 对象添加到 <a> 标签的 href 属性中
        link.href = window.URL.createObjectURL(blob);
        // 设置下载文件的名称
        link.download = `car_${new Date().getTime()}.xlsx`;
        // 将 <a> 标签添加到页面中
        document.body.appendChild(link);
        // 模拟点击 <a> 标签，触发文件下载
        link.click();
        // 释放 Blob 对象的 URL
        window.URL.revokeObjectURL(link.href);
        // 移除 <a> 标签
        document.body.removeChild(link);
      }).catch(error => {
        console.error('导出失败:', error);
        // 处理导出失败的逻辑
      });
    }



  }
};
</script>
