<template>
  <div>
    <el-form ref="form" :model="form" style="padding: 20px 100px 0">
      <el-form-item label="选择车辆：">
        <span v-if="chooseCarList.length != 0">
          <el-tag effect="plain" type="success" v-for="item in chooseCarList" style="margin: 5px; font-size: 14px"
            :key="item.carId" closable @close="removeCar(item.carId)">
            {{ item.licensePlate + item.brand }}
          </el-tag>
        </span>
        <el-button type="success" plain icon="el-icon-plus" @click="openCar = true" size="mini">新增</el-button>
      </el-form-item>
      <el-form-item v-if="chooseCarList.length != 0">
        <table border="1">
          <tr>
            <td :colspan="4" class="head">车辆成本预算</td>
          </tr>
          <tr>
            <td style="width: 120px">车牌号</td>
            <td style="width: 110px">折旧成本（天）</td>
            <td style="width: 110px">预算天数</td>
            <td style="width: 100px">总额</td>
          </tr>
          <tr v-for="car in chooseCarList" :key="car.carId">
            <td>{{ car.licensePlate + car.brand }}</td>
            <td>
              {{ car.dayCost }}
            </td>
            <td>
              <el-input-number  :controls="false" v-model="car.days" placeholder="请输入天数"
                @blur="calculateCarTotal(car)"></el-input-number>
            </td>
            <td class="carCost">{{ car.amount }}</td>
          </tr>
          <tr>
            <td colspan="3"><b>车辆成本合计</b></td>
            <td><b>{{ form.carCost }}</b></td>
          </tr>
        </table>
      </el-form-item>
    </el-form>
    <!-- 选择车辆对话框 -->
    <el-dialog title="选择车辆" :visible.sync="openCar" width="700px" append-to-body>
      <chooseCar @chooseList="getChooseCar" :selectedCarIds="chooseCarList.map(c => c.carId)"></chooseCar>
    </el-dialog>
  </div>
</template>

<script>
import chooseCar from './components/chooseCar'
import { listBudgetCar, addBudgetCar, delBudgetCar } from "@/api/oa/budget/budgetCar.js";
export default {
  components: {
    chooseCar
  },
  props: {
    budgetId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        carCost: 0
      },
      chooseCarList: [],
      openCar: false,
    }
  },
  watch: {
    'form.carCost'(newval) {
      if (!isNaN(newval)) {
        this.$emit('carCost', newval);
      }
    },
    budgetId() {
      this.initForm()
    },
    chooseCarList: {
      handler(newVal) {
        this.$emit('chooseCar', newVal)
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    }
  },
  created() {
    this.initForm();
  },
  methods: {
    initForm() {
      if (this.budgetId != '') {
        listBudgetCar({ pageSize: 100, budgetId: this.budgetId }).then((res) => {
          this.chooseCarList = res.rows
          for (let car of this.chooseCarList) {
            car.fuel = car.car.fuel
            car.insurance = car.car.insurance
            car.maintenance = car.car.maintenance
            car.licensePlate = car.car.licensePlate
            car.dayCost = car.car.dayCost
            car.brand = car.car.brand
          }
          this.initCarCost();
        })
      }
    },
    initCarCost() {
      let carCost = 0;
      for (let car of this.chooseCarList) {
        carCost = carCost + Number(car.amount);
      }
      this.form.carCost = carCost.toFixed(2)
    },
    getChooseCar(val) {
      const newCars = val.filter(v => !this.chooseCarList.some(c => c.carId === v.carId));
      this.chooseCarList = this.chooseCarList.concat(newCars);
      this.openCar = false;
      this.recalculateCost(this.chooseCarList, 'amount', 'carCost');
    },
    removeCar(carId) {
      this.chooseCarList = this.chooseCarList.filter(c => c.carId !== carId);
      this.recalculateCost(this.chooseCarList, 'amount', 'carCost');
    },
    calculateCarTotal(car) {
      let total = Number(car.dayCost) * Number(car.days);
      let sum = total.toFixed(2);
      this.$set(car, "depreciation", car.dayCost);
      this.$set(car, "amount", sum);
      this.getCost("amount", "carCost", this.chooseCarList);
    },
    recalculateCost(arr, name, formName) {
      let sum = arr.reduce((accumulator, item) => {
        // 检查 carCost 属性是否存在且为数字（或可转换为数字）  
        if (item[name] != null && !isNaN(Number(item[name]))) {
          return accumulator + Number(item[name]);
        }
        return accumulator;
      }, 0);
      this.$set(this.form, formName, sum.toFixed(2));
    },
    getCost(name1, name2, list) {
      let sum = 0;
      for (let user of list) {
        sum = sum + Number(user[name1]);
      }
      this.form[name2] = sum.toFixed(2);
    },
  },
}
</script>

<style lang="scss" scoped>
table {
  width: 100%;
  /*居中*/
  // margin: 0 auto;
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  border: 1px solid #DCDFE6;

  /*设置背景颜色*/
  /* background-color: #bfa; */
  td {
    padding: 1px;
  }

  .head {
    background-color: #e7f6f3;
    font-family: '微软雅黑';
    font-size: 18;
    font-weight: bold;
  }
}
</style>