<template>
  <div>
    <el-form ref="form" :model="form" style="padding: 20px 100px 0">
      <el-form-item label="现场开支：">
        <div style="color:#F56C6C">现场开支与借款挂钩,请慎重填写</div>
        <table border="1">
          <tr>
            <td colspan="5" class="head">现场开支表</td>
          </tr>
          <tr>
            <td>序号</td>
            <td>名称</td>
            <td>金额</td>
            <td>备注</td>
            <td>操作</td>
          </tr>
          <tr v-for="item, index in expensesList">
            <td>{{ index + 1 }}</td>
            <td>
              <el-select v-model="item.name" placeholder="请选择开支项" clearable @change="handleExpenseChange"
                style="width: 100%;">
                <el-option v-for="dict in dict.type.cmc_borrow_expense" clearable :key="dict.value" :label="dict.label"
                  :value="dict.value" />
                <!-- <el-option label="+新增更多开支项..." value="new_expense" /> -->
              </el-select>
            </td>
            <td>
              <el-input-number style="width: 100%;" :controls="false" v-model="item.amount"
                placeholder="请输入金额"></el-input-number>
            </td>
            <td>
              <el-input type="textarea" v-model="item.remark"></el-input>
            </td>
            <td>
              <el-button icon="el-icon-delete" type="text" style="color:#F56C6C"
                @click="deletExpensesList(index)">删除</el-button>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: right; font-weight: bold;">现场开支总计：</td>
            <td style="font-weight: bold;">{{ totalAmount }}</td>
            <td colspan="2"></td>
          </tr>
        </table>
        <el-button type="primary" plain icon="el-icon-plus" @click="addExpensesList" size="mini"></el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="新增开支项" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="newExpenseForm" :model="newExpenseForm" :rules="newExpenseRules" label-width="120px">
        <el-form-item label="开支项名称" prop="name">
          <el-input v-model="newExpenseForm.name" placeholder="请输入开支项名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNewExpense">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addData, getDicts } from "@/api/system/dict/data";
import { listSite, delSite } from "@/api/oa/budget/budgetSite.js";
export default {
  dicts: ['cmc_borrow_expense', 'cmc_unit'],
  props: {
    outerUsers: {
      type: Array,
      default: () => []
    },
    budgetId: {
      type: String,
      default: ''
    },
  },
  watch: {
    expensesList: {
      handler(newVal) {
        this.$emit('expensesList', [...newVal])
      },
    },
    budgetId() {
      this.initTable()
    },
  },
  data() {
    return {
      open: false,
      form: {},
      expensesList: [{
        name: '',
        amount: 0,
        remark: '',
      }],
      newExpenseForm: {
        name: ''
      },
      newExpenseRules: {
        name: [
          { required: true, message: "开支项不能为空", trigger: "blur" }
        ],
      }
    }
  },
  computed: {
    totalAmount() {
      let sum = this.expensesList.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
      this.$emit('siteCost', sum.toFixed(2))
      return sum.toFixed(2);
    }
  },
  created() {

  },
  methods: {
    initTable() {
      if (this.budgetId != '') {
        listSite({ pageSize: 100, budgetId: this.budgetId }).then(res => {
          if (res.rows.length > 0) {
            this.expensesList = res.rows;
          } else {
            this.expensesList = [{
              name: '',
              amount: 0,
              remark: '',
            }];
          }
        })
      }
    },
    addExpensesList() {
      this.expensesList.push({
        name: '',
        amount: 0,
      });
    },
    deletExpensesList(index) {
      let arr = this.expensesList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        const item = arr[index];
        if (item.id) {
          // If the item has an ID, it exists in the database, so delete it
          delSite(item.id).then(response => {
            this.$modal.msgSuccess("删除成功");
            arr.splice(index, 1);
          }).catch(() => {
            this.$modal.msgError("删除失败");
          });
        } else {
          // If the item doesn't have an ID, just remove it from the array
          arr.splice(index, 1);
        }
      }
    },
    handleExpenseChange(value) {
      if (value === 'new_expense') {
        this.open = true;
      } else if (value === '食宿费') {
        const currentIndex = this.expensesList.findIndex(item => item.name === value);
        if (currentIndex !== -1) {
          const totalDays = this.outerUsers.reduce((sum, user) => sum + (user.days || 0), 0);
          this.expensesList[currentIndex].amount = 130 * totalDays;
          this.expensesList[currentIndex].remark = '130元/人天，共计' + totalDays + '人天';
        }
      }
    },
    submitNewExpense() {
      this.$refs["newExpenseForm"].validate(valid => {
        if (valid) {
          let length = this.dict.type.cmc_borrow_expense.length;
          this.newExpenseForm.dictType = 'cmc_borrow_expense';
          this.newExpenseForm.dictLabel = this.newExpenseForm.name;
          this.newExpenseForm.dictValue = this.newExpenseForm.name;
          this.newExpenseForm.listClass = 'default';
          this.newExpenseForm.dictSort = length;
          addData(this.newExpenseForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.newExpenseForm.name = '';
            // 刷新字典数据
            getDicts("cmc_borrow_expense").then(res => {
              let arr = [];
              for (let i = 0; i < res.data.length; i++) {
                arr.push({
                  label: res.data[i].dictLabel,
                  value: res.data[i].dictValue,
                  raw: res.data[i]
                })
              }
              this.dict.type.cmc_borrow_expense = arr;
            })
          });
        }
      })
    }
  }
}
</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>