<template>

    <!-- 对话框(添加 / 修改) -->
    <el-drawer
      title="选择车辆"
      size="60%"
      :visible.sync="drawVisible"
      @close="cancelForm"
    >
      <div style="padding: 0 10px;margin-bottom: 70px">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

        <el-form-item label="车牌号" prop="licenseNumber">
          <el-input v-model="queryParams.licenseNumber" placeholder="请输入车牌号" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>

        <el-form-item label="车辆型号" prop="carModel" label-width="90">
          <el-input v-model="queryParams.carModel" placeholder="请输入车辆型号" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="carBrand" label-width="90">
          <el-input v-model="queryParams.carBrand" placeholder="请输入车辆品牌" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="发动机号" prop="engineNumber" label-width="90">
          <el-input v-model="queryParams.engineNumber" placeholder="请输入发动机号" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作工具栏 -->
      <el-row>
        <el-col :span="3">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                     v-hasPermi="['base:car-main:create']">新增
          </el-button>
        </el-col>
        <el-col :span="3" v-for="car in multipleSelection">
          <el-tag
            :key="car.id"
            type="danger"
            @close="tagClose(car)"
            closable>
            {{car.licenseNumber}}
          </el-tag>
        </el-col>
      </el-row>

      <el-table
        ref="multipleTable"
        height="460"
        v-loading="formLoading"
        :data="list"
        :stripe="true"
        @select="selectRow"
        @select-all="handleSelectAll"
        :show-overflow-tooltip="true">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="车牌号" align="center" prop="licenseNumber"/>
        <el-table-column label="车辆品牌" align="center" prop="brandStr"/>
        <el-table-column label="车辆型号" align="center" prop="modelStr"/>
        <el-table-column label="发动机号码" align="center" prop="engineNumber" />
        <el-table-column label="车架号" align="center" prop="vin" />
        <el-table-column label="登记时间" align="center" prop="createTime" >
          <template v-slot="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>



      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
      </div>
        <div style="position: absolute;bottom: 0;width: 100%;right: 0;padding: 5px 20px 0;z-index: 999;background: white;text-align: right">
          <div class="demo-drawer__footer"  >
            <el-button @click="cancelForm">取 消</el-button>
            <el-button type="primary" @click="submitForm" >确 定</el-button>
          </div>
        </div>
      <CarMainForm ref="formRef" @success="getList" />

    </el-drawer>
  <!-- 对话框(添加 / 修改) -->
</template>

<script>
import * as CarMainApi from '@/api/base/carmain';
import CarMainForm from '@/views/base/carmain/CarMainForm.vue';
export default {
  name: "ChooseCarDraw",
  components: {CarMainForm},
  data() {
    return {
      // 弹出层标题
      // 是否显示弹出层
      drawVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      //回参
      formData: {},
      // 总条数
      total: 0,
      // 车辆信息列表
      list: [],
      multipleSelection:[],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        licenseNumber: null,
        carModel: null,
        carBrand: null,
        engineNumber: null,
      },

    };
  },
  methods: {

    /** 打开弹窗 */
    async open(multipleSelection) {
      this.drawVisible = true;
      this.formLoading = true;
      this.reset();
      try {
        const res = await CarMainApi.getCarMainPage(this.queryParams);
        this.list = res.data.records;
        this.total = res.data.total;
        this.multipleSelection = JSON.parse(JSON.stringify(multipleSelection))
        this.defaultChecked(multipleSelection)
      } finally {
        this.formLoading = false;
      }
    },
    /**标签删除事件*/
    tagClose(row){
      const that = this;
      let id1 = this.multipleSelection.findIndex(item => {
        if (item.id == row.id) {
          this.$nextTick(() => {
            that.$refs.multipleTable.toggleRowSelection(
              this.list.find( // 这是弹框表格的数据
              carItem => item.id === carItem.id
            ), false);
          });
          return true
        }
      })
      this.multipleSelection.splice(id1, 1)
    },

    /**选中*/
    selectRow(val,row){
      //当前点击是否勾选
      let selectBool = val.length && val.indexOf(row) !== -1
      if(!selectBool){
        //取消勾选
        this.multipleSelection.forEach((item,i) => {
          if(item.id == row.id){
            this.multipleSelection.splice(i,1)
          }
        })
      }else{
        //选中
        this.multipleSelection.push(row)
      }
    },

    /**全选*/
    handleSelectAll(val){
      if(val.length == this.list.length){ //全选
        this.multipleSelection = this.multipleSelection.concat(val)
        //去重
        let obj = {}
        let result = []
        this.multipleSelection.forEach(item => {
          if(!obj[item.id]){
            result.push(item)
            obj[item.id] = true
          }
        })
        this.multipleSelection = result
      }else{ //取消全选
        this.list.forEach(item => {
          this.multipleSelection.forEach((multItem,i) => {
            if(item.id == multItem.id){
              this.multipleSelection.splice(i,1)
            }
          })
        })
      }
    },

    /**设置默认选中*/
    defaultChecked(multipleSelection) {
      const that = this;
      this.$nextTick(() => {
        that.list.forEach((v, i) => {
          multipleSelection.map(item => {
            if (item.id === v.id){
              that.$refs.multipleTable.toggleRowSelection(v, true);
            }
          })
        });
      });
    },

    cancelForm(){
      this.drawVisible = false
    },

    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },

    /** 查询列表 */
    async getList() {
      try {
        this.formLoading = true
        const res = await CarMainApi.getCarMainPage(this.queryParams);
        this.list = res.data.records;
        this.total = res.data.total;
        this.defaultChecked(this.multipleSelection)
      } finally {
        this.formLoading = false
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /**重置参数*/
    reset() {
      this.queryParams= {
        pageNo: 1,
          pageSize: 10,
          licenseNumber: null,
          carModel: null,
          carBrand: null,
          engineNumber: null,
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.drawVisible = false
      this.$emit('success',this.multipleSelection)
    },

  }
};
</script>
