<template>
  <div>
    <el-form ref="form" :model="form" style="padding: 20px 100px 0">
      <el-form-item label="选择设备：">
        <span v-if="chooseDeviceList.length != 0">
          <el-tag effect="plain" type="success" v-for="item in chooseDeviceList" style="margin: 5px; font-size: 14px"
            :key="item.deviceId" closable @close="removeDevice(item.deviceId)">
            {{ item.name + '-' + item.series + '-' + item.brand }}
          </el-tag>
        </span>
        <el-button type="success" plain icon="el-icon-plus" @click="openDevice = true" size="mini">新增</el-button>
      </el-form-item>
      <el-form-item v-if="chooseDeviceList.length != 0">
        <table border="1">
          <tr>
            <td :colspan="6" class="head">设备成本预算</td>
          </tr>
          <tr>
            <td style="width: 100px">出厂编号</td>
            <td style="width: 120px">设备名称</td>
            <td style="width: 120px">规格型号</td>
            <td style="width: 120px">品牌</td>
            <td style="width: 120px">折旧成本（天）</td>
            <td style="width: 100px">预算天数</td>
            <td style="width: 100px">总额</td>
          </tr>
          <tr v-for="device in chooseDeviceList" :key="device.deviceId">
            <td>{{ device.code }}</td>
            <td>{{ device.name }}</td>
            <td>{{ device.series }}</td>
            <td>{{ device.brand }}</td>
            <td>
              {{ device.depreciation }}
            </td>
            <td>
              <el-input-number :controls="false" v-model="device.days" placeholder="请输入天数"
                @blur="calculateDeviceTotal(device)"></el-input-number>
            </td>
            <td class="deviceCost">{{ device.amount }}</td>
          </tr>
          <tr>
            <td colspan="5"><b>设备成本合计</b></td>
            <td><b>{{ form.deviceCost }}</b></td>
          </tr>
        </table>
      </el-form-item>
    </el-form>
    <!-- 选择设备对话框 -->
    <el-dialog title="选择设备" :visible.sync="openDevice" width="750px" append-to-body>
      <chooseDevice @chooseList="getChooseDevice" :selectedDeviceIds="chooseDeviceList.map(d => d.deviceId)"></chooseDevice>
    </el-dialog>
  </div>
</template>

<script>
import chooseDevice from './components/chooseDevice'
import { listBudgetDevice, addBudgetDevice, delBudgetDevice } from "@/api/oa/budget/budgetDevice.js";
export default {
  components: {
    chooseDevice
  },
  props: {
    budgetId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        deviceCost: 0
      },
      chooseDeviceList: [],
      openDevice: false,
    }
  },
  watch: {
    'form.deviceCost'(newval) {
      if (!isNaN(newval)) {
        this.$emit('deviceCost', newval);
      }
    },
    budgetId() {
      this.initForm()
    },
    chooseDeviceList: {
      handler(newVal) {
        this.$emit('chooseDevice', newVal)
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    }
  },
  created() {
    this.initForm();
  },
  methods: {
    initForm() {
      if (this.budgetId != '') {
        listBudgetDevice({ pageSize: 100, budgetId: this.budgetId }).then((res) => {
          this.chooseDeviceList = res.rows;
          for (let device of this.chooseDeviceList) {
            device.code = device.device.code
            device.brand = device.device.brand
            device.depreciation = device.device.dayCost
            device.name = device.device.name
            device.series = device.device.series
          }
          this.initDeviceCost();
        })
      }
    },
    initDeviceCost() {
      let deviceCost = 0;
      for (let device of this.chooseDeviceList) {
        deviceCost = deviceCost + Number(device.amount);
      }
      this.form.deviceCost = deviceCost.toFixed(2)
    },
    getChooseDevice(val) {
      // 过滤掉已存在的设备
      const newDevices = val.filter(v => !this.chooseDeviceList.some(d => d.deviceId === v.deviceId));
      // 追加新设备
      this.chooseDeviceList = this.chooseDeviceList.concat(newDevices);
      this.openDevice = false;
      for (let v of newDevices) {
        v.depreciation = v.dayCost;
      }
      this.recalculateCost(this.chooseDeviceList, 'amount', 'deviceCost');
    },
    removeDevice(deviceId) {
      this.chooseDeviceList = this.chooseDeviceList.filter(d => d.deviceId !== deviceId);
      this.recalculateCost(this.chooseDeviceList, 'amount', 'deviceCost');
    },
    calculateDeviceTotal(device) {
      let total = Number(device.depreciation) * Number(device.days);
      total = isNaN(total) ? 0 : total
      this.$set(device, "amount", total.toFixed(2));
      this.getCost("amount", "deviceCost", this.chooseDeviceList);
    },
    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>