<template>
  <div>
    <div style="display: flex; align-items: center;">
      <el-select v-model="carSelected" clearable style="width: 200px;">
        <el-option v-for="car in carList" :key="car.id" :label="car.licenseNumber" :value="car.id" />
      </el-select>
      <el-button type="primary" size="small" @click="addNewCar" style="margin-left: 8px;">
        新增车辆
      </el-button>
    </div>
    <AddCarForm ref="addCarForm" :customer-info="customerInfo" @success="handleCarAddSuccess" />
  </div>
</template>

<script>

import { remindCarMainPage } from "@/api/base/carmain";
import AddCarForm from "./AddCarForm.vue";

export default {
  name: "CarChoose",
  components: {
    AddCarForm
  },
  props: {
    value: {
      type: Object
    },
    cusName: {
      type: String,
    },
    customerInfo: {
      type: Object,
      required: true
    },
    inList: {
      type: Object,
      default: null,
      required: false
    }
  },
  watch: {
    carSelected(val) {
      if (val) {
        let car = this.carList.find(item => item.id === val);
        car = {
          ...car,
          modelStr: car?.brandStr + " " + car?.carModel
        }
        this.$emit('input', car);
      }
    },
    value(val) {
      this.carSelected = val ? val.id : null;
    },
    cusName: {
      handler(val, old) {
        if (val !== old) {
          // this.carSelected = null
          this.getCarList()
        }
      },
      immediate: true
    },
    inList(val) {
      if (val) {
        const flag = this.carList.findIndex(item => item.id === val.id)
        if (flag > 0) {
          this.carList.splice(flag, 1)
        }
        this.carList.unshift(val)
        this.carSelected = val.id
      }
    }
  },
  data() {
    return {
      carSelected: null,
      carList: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        cusName: null
      },
      total: 0
    }
  },
  methods: {
    async getCarList() {
      try {
        if (this.cusName) {
          this.queryParams["cusName"] = this.cusName
          const res = await remindCarMainPage(this.queryParams)
          this.carList = res.data.records
          this.total = res.data.total
        }
      } catch {
      }
    },
    addNewCar() {
      // 打开新增车辆表单
      this.$refs.addCarForm.open();
    },
    handleCarAddSuccess(carInfo) {
      // 新增成功后刷新车辆列表
      this.getCarList();
      // 自动选中新添加的车辆
      this.carSelected = carInfo.id;
    }
  }
}
</script>

<style scoped lang="scss"></style>
